org-compat.el: Silent the byte-compiler about a warning related to XEmacs support.
[org-mode.git] / contrib / lisp / org-export.el
blobefcb879698f257717de80f3b853a786a814eca1e
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 "./org-e-ascii.el")
97 (require 'org-e-html "./org-e-html.el")
98 (require 'org-e-latex "./org-e-latex.el")
99 (require 'org-e-odt "./org-e-odt.el")
100 (require 'org-e-publish "./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-bold . org-export-filter-bold-functions)
181 (:filter-babel-call . org-export-filter-babel-call-functions)
182 (:filter-center-block . org-export-filter-center-block-functions)
183 (:filter-code . org-export-filter-code-functions)
184 (:filter-comment . org-export-filter-comment-functions)
185 (:filter-comment-block . org-export-filter-comment-block-functions)
186 (:filter-drawer . org-export-filter-drawer-functions)
187 (:filter-dynamic-block . org-export-filter-dynamic-block-functions)
188 (:filter-entity . org-export-filter-entity-functions)
189 (:filter-example-block . org-export-filter-example-block-functions)
190 (:filter-export-block . org-export-filter-export-block-functions)
191 (:filter-export-snippet . org-export-filter-export-snippet-functions)
192 (:filter-final-output . org-export-filter-final-output-functions)
193 (:filter-fixed-width . org-export-filter-fixed-width-functions)
194 (:filter-footnote-definition . org-export-filter-footnote-definition-functions)
195 (:filter-footnote-reference . org-export-filter-footnote-reference-functions)
196 (:filter-headline . org-export-filter-headline-functions)
197 (:filter-horizontal-rule . org-export-filter-horizontal-rule-functions)
198 (:filter-inline-babel-call . org-export-filter-inline-babel-call-functions)
199 (:filter-inline-src-block . org-export-filter-inline-src-block-functions)
200 (:filter-inlinetask . org-export-filter-inlinetask-functions)
201 (:filter-italic . org-export-filter-italic-functions)
202 (:filter-item . org-export-filter-item-functions)
203 (:filter-keyword . org-export-filter-keyword-functions)
204 (:filter-latex-environment . org-export-filter-latex-environment-functions)
205 (:filter-latex-fragment . org-export-filter-latex-fragment-functions)
206 (:filter-line-break . org-export-filter-line-break-functions)
207 (:filter-link . org-export-filter-link-functions)
208 (:filter-macro . org-export-filter-macro-functions)
209 (:filter-paragraph . org-export-filter-paragraph-functions)
210 (:filter-parse-tree . org-export-filter-parse-tree-functions)
211 (:filter-plain-list . org-export-filter-plain-list-functions)
212 (:filter-plain-text . org-export-filter-plain-text-functions)
213 (:filter-property-drawer . org-export-filter-property-drawer-functions)
214 (:filter-quote-block . org-export-filter-quote-block-functions)
215 (:filter-quote-section . org-export-filter-quote-section-functions)
216 (:filter-radio-target . org-export-filter-radio-target-functions)
217 (:filter-section . org-export-filter-section-functions)
218 (:filter-special-block . org-export-filter-special-block-functions)
219 (:filter-src-block . org-export-filter-src-block-functions)
220 (:filter-statistics-cookie . org-export-filter-statistics-cookie-functions)
221 (:filter-strike-through . org-export-filter-strike-through-functions)
222 (:filter-subscript . org-export-filter-subscript-functions)
223 (:filter-superscript . org-export-filter-superscript-functions)
224 (:filter-table . org-export-filter-table-functions)
225 (:filter-table-cell . org-export-filter-table-cell-functions)
226 (:filter-table-row . org-export-filter-table-row-functions)
227 (:filter-target . org-export-filter-target-functions)
228 (:filter-time-stamp . org-export-filter-time-stamp-functions)
229 (:filter-underline . org-export-filter-underline-functions)
230 (:filter-verbatim . org-export-filter-verbatim-functions)
231 (:filter-verse-block . org-export-filter-verse-block-functions))
232 "Alist between filters properties and initial values.
234 The key of each association is a property name accessible through
235 the communication channel its value is a configurable global
236 variable defining initial filters.
238 This list is meant to install user specified filters. Back-end
239 developers may install their own filters using
240 `org-BACKEND-filters-alist', where BACKEND is the name of the
241 considered back-end. Filters defined there will always be
242 prepended to the current list, so they always get applied
243 first.")
245 (defconst org-export-default-inline-image-rule
246 `(("file" .
247 ,(format "\\.%s\\'"
248 (regexp-opt
249 '("png" "jpeg" "jpg" "gif" "tiff" "tif" "xbm"
250 "xpm" "pbm" "pgm" "ppm") t))))
251 "Default rule for link matching an inline image.
252 This rule applies to links with no description. By default, it
253 will be considered as an inline image if it targets a local file
254 whose extension is either \"png\", \"jpeg\", \"jpg\", \"gif\",
255 \"tiff\", \"tif\", \"xbm\", \"xpm\", \"pbm\", \"pgm\" or \"ppm\".
256 See `org-export-inline-image-p' for more information about
257 rules.")
261 ;;; User-configurable Variables
263 ;; Configuration for the masses.
265 ;; They should never be accessed directly, as their value is to be
266 ;; stored in a property list (cf. `org-export-option-alist').
267 ;; Back-ends will read their value from there instead.
269 (defgroup org-export nil
270 "Options for exporting Org mode files."
271 :tag "Org Export"
272 :group 'org)
274 (defgroup org-export-general nil
275 "General options for export engine."
276 :tag "Org Export General"
277 :group 'org-export)
279 (defcustom org-export-with-archived-trees 'headline
280 "Whether sub-trees with the ARCHIVE tag should be exported.
282 This can have three different values:
283 nil Do not export, pretend this tree is not present.
284 t Do export the entire tree.
285 `headline' Only export the headline, but skip the tree below it.
287 This option can also be set with the #+OPTIONS line,
288 e.g. \"arch:nil\"."
289 :group 'org-export-general
290 :type '(choice
291 (const :tag "Not at all" nil)
292 (const :tag "Headline only" 'headline)
293 (const :tag "Entirely" t)))
295 (defcustom org-export-with-author t
296 "Non-nil means insert author name into the exported file.
297 This option can also be set with the #+OPTIONS line,
298 e.g. \"author:nil\"."
299 :group 'org-export-general
300 :type 'boolean)
302 (defcustom org-export-with-creator 'comment
303 "Non-nil means the postamble should contain a creator sentence.
305 The sentence can be set in `org-export-creator-string' and
306 defaults to \"Generated by Org mode XX in Emacs XXX.\".
308 If the value is `comment' insert it as a comment."
309 :group 'org-export-general
310 :type '(choice
311 (const :tag "No creator sentence" nil)
312 (const :tag "Sentence as a comment" 'comment)
313 (const :tag "Insert the sentence" t)))
315 (defcustom org-export-creator-string
316 (format "Generated by Org mode %s in Emacs %s."
317 (if (boundp 'org-version) org-version "(Unknown)")
318 emacs-version)
319 "String to insert at the end of the generated document."
320 :group 'org-export-general
321 :type '(string :tag "Creator string"))
323 (defcustom org-export-with-drawers t
324 "Non-nil means export contents of standard drawers.
326 When t, all drawers are exported. This may also be a list of
327 drawer names to export. This variable doesn't apply to
328 properties drawers.
330 This option can also be set with the #+OPTIONS line,
331 e.g. \"d:nil\"."
332 :group 'org-export-general
333 :type '(choice
334 (const :tag "All drawers" t)
335 (const :tag "None" nil)
336 (repeat :tag "Selected drawers"
337 (string :tag "Drawer name"))))
339 (defcustom org-export-with-email nil
340 "Non-nil means insert author email into the exported file.
341 This option can also be set with the #+OPTIONS line,
342 e.g. \"email:t\"."
343 :group 'org-export-general
344 :type 'boolean)
346 (defcustom org-export-with-emphasize t
347 "Non-nil means interpret *word*, /word/, and _word_ as emphasized text.
349 If the export target supports emphasizing text, the word will be
350 typeset in bold, italic, or underlined, respectively. Not all
351 export backends support this.
353 This option can also be set with the #+OPTIONS line, e.g. \"*:nil\"."
354 :group 'org-export-general
355 :type 'boolean)
357 (defcustom org-export-exclude-tags '("noexport")
358 "Tags that exclude a tree from export.
360 All trees carrying any of these tags will be excluded from
361 export. This is without condition, so even subtrees inside that
362 carry one of the `org-export-select-tags' will be removed.
364 This option can also be set with the #+EXPORT_EXCLUDE_TAGS:
365 keyword."
366 :group 'org-export-general
367 :type '(repeat (string :tag "Tag")))
369 (defcustom org-export-with-fixed-width t
370 "Non-nil means lines starting with \":\" will be in fixed width font.
372 This can be used to have pre-formatted text, fragments of code
373 etc. For example:
374 : ;; Some Lisp examples
375 : (while (defc cnt)
376 : (ding))
377 will be looking just like this in also HTML. See also the QUOTE
378 keyword. Not all export backends support this.
380 This option can also be set with the #+OPTIONS line, e.g. \"::nil\"."
381 :group 'org-export-translation
382 :type 'boolean)
384 (defcustom org-export-with-footnotes t
385 "Non-nil means Org footnotes should be exported.
386 This option can also be set with the #+OPTIONS line,
387 e.g. \"f:nil\"."
388 :group 'org-export-general
389 :type 'boolean)
391 (defcustom org-export-headline-levels 3
392 "The last level which is still exported as a headline.
394 Inferior levels will produce itemize lists when exported. Note
395 that a numeric prefix argument to an exporter function overrides
396 this setting.
398 This option can also be set with the #+OPTIONS line, e.g. \"H:2\"."
399 :group 'org-export-general
400 :type 'integer)
402 (defcustom org-export-default-language "en"
403 "The default language for export and clocktable translations, as a string.
404 This may have an association in
405 `org-clock-clocktable-language-setup'."
406 :group 'org-export-general
407 :type '(string :tag "Language"))
409 (defcustom org-export-preserve-breaks nil
410 "Non-nil means preserve all line breaks when exporting.
412 Normally, in HTML output paragraphs will be reformatted.
414 This option can also be set with the #+OPTIONS line,
415 e.g. \"\\n:t\"."
416 :group 'org-export-general
417 :type 'boolean)
419 (defcustom org-export-with-entities t
420 "Non-nil means interpret entities when exporting.
422 For example, HTML export converts \\alpha to &alpha; and \\AA to
423 &Aring;.
425 For a list of supported names, see the constant `org-entities'
426 and the user option `org-entities-user'.
428 This option can also be set with the #+OPTIONS line,
429 e.g. \"e:nil\"."
430 :group 'org-export-general
431 :type 'boolean)
433 (defcustom org-export-with-priority nil
434 "Non-nil means include priority cookies in export.
436 When nil, remove priority cookies for export.
438 This option can also be set with the #+OPTIONS line,
439 e.g. \"pri:t\"."
440 :group 'org-export-general
441 :type 'boolean)
443 (defcustom org-export-with-section-numbers t
444 "Non-nil means add section numbers to headlines when exporting.
446 When set to an integer n, numbering will only happen for
447 headlines whose relative level is higher or equal to n.
449 This option can also be set with the #+OPTIONS line,
450 e.g. \"num:t\"."
451 :group 'org-export-general
452 :type 'boolean)
454 (defcustom org-export-select-tags '("export")
455 "Tags that select a tree for export.
457 If any such tag is found in a buffer, all trees that do not carry
458 one of these tags will be ignored during export. Inside trees
459 that are selected like this, you can still deselect a subtree by
460 tagging it with one of the `org-export-exclude-tags'.
462 This option can also be set with the #+EXPORT_SELECT_TAGS:
463 keyword."
464 :group 'org-export-general
465 :type '(repeat (string :tag "Tag")))
467 (defcustom org-export-with-special-strings t
468 "Non-nil means interpret \"\-\", \"--\" and \"---\" for export.
470 When this option is turned on, these strings will be exported as:
472 Org HTML LaTeX
473 -----+----------+--------
474 \\- &shy; \\-
475 -- &ndash; --
476 --- &mdash; ---
477 ... &hellip; \ldots
479 This option can also be set with the #+OPTIONS line,
480 e.g. \"-:nil\"."
481 :group 'org-export-general
482 :type 'boolean)
484 (defcustom org-export-with-sub-superscripts t
485 "Non-nil means interpret \"_\" and \"^\" for export.
487 When this option is turned on, you can use TeX-like syntax for
488 sub- and superscripts. Several characters after \"_\" or \"^\"
489 will be considered as a single item - so grouping with {} is
490 normally not needed. For example, the following things will be
491 parsed as single sub- or superscripts.
493 10^24 or 10^tau several digits will be considered 1 item.
494 10^-12 or 10^-tau a leading sign with digits or a word
495 x^2-y^3 will be read as x^2 - y^3, because items are
496 terminated by almost any nonword/nondigit char.
497 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
499 Still, ambiguity is possible - so when in doubt use {} to enclose
500 the sub/superscript. If you set this variable to the symbol
501 `{}', the braces are *required* in order to trigger
502 interpretations as sub/superscript. This can be helpful in
503 documents that need \"_\" frequently in plain text.
505 This option can also be set with the #+OPTIONS line,
506 e.g. \"^:nil\"."
507 :group 'org-export-general
508 :type '(choice
509 (const :tag "Interpret them" t)
510 (const :tag "Curly brackets only" {})
511 (const :tag "Do not interpret them" nil)))
513 (defcustom org-export-with-toc t
514 "Non-nil means create a table of contents in exported files.
516 The TOC contains headlines with levels up
517 to`org-export-headline-levels'. When an integer, include levels
518 up to N in the toc, this may then be different from
519 `org-export-headline-levels', but it will not be allowed to be
520 larger than the number of headline levels. When nil, no table of
521 contents is made.
523 This option can also be set with the #+OPTIONS line,
524 e.g. \"toc:nil\" or \"toc:3\"."
525 :group 'org-export-general
526 :type '(choice
527 (const :tag "No Table of Contents" nil)
528 (const :tag "Full Table of Contents" t)
529 (integer :tag "TOC to level")))
531 (defcustom org-export-with-tables t
532 "If non-nil, lines starting with \"|\" define a table.
533 For example:
535 | Name | Address | Birthday |
536 |-------------+----------+-----------|
537 | Arthur Dent | England | 29.2.2100 |
539 This option can also be set with the #+OPTIONS line, e.g. \"|:nil\"."
540 :group 'org-export-general
541 :type 'boolean)
543 (defcustom org-export-with-tags t
544 "If nil, do not export tags, just remove them from headlines.
546 If this is the symbol `not-in-toc', tags will be removed from
547 table of contents entries, but still be shown in the headlines of
548 the document.
550 This option can also be set with the #+OPTIONS line,
551 e.g. \"tags:nil\"."
552 :group 'org-export-general
553 :type '(choice
554 (const :tag "Off" nil)
555 (const :tag "Not in TOC" not-in-toc)
556 (const :tag "On" t)))
558 (defcustom org-export-with-tasks t
559 "Non-nil means include TODO items for export.
560 This may have the following values:
561 t include tasks independent of state.
562 todo include only tasks that are not yet done.
563 done include only tasks that are already done.
564 nil remove all tasks before export
565 list of keywords keep only tasks with these keywords"
566 :group 'org-export-general
567 :type '(choice
568 (const :tag "All tasks" t)
569 (const :tag "No tasks" nil)
570 (const :tag "Not-done tasks" todo)
571 (const :tag "Only done tasks" done)
572 (repeat :tag "Specific TODO keywords"
573 (string :tag "Keyword"))))
575 (defcustom org-export-time-stamp-file t
576 "Non-nil means insert a time stamp into the exported file.
577 The time stamp shows when the file was created.
579 This option can also be set with the #+OPTIONS line,
580 e.g. \"timestamp:nil\"."
581 :group 'org-export-general
582 :type 'boolean)
584 (defcustom org-export-with-timestamps t
585 "If nil, do not export time stamps and associated keywords."
586 :group 'org-export-general
587 :type 'boolean)
589 (defcustom org-export-with-todo-keywords t
590 "Non-nil means include TODO keywords in export.
591 When nil, remove all these keywords from the export."
592 :group 'org-export-general
593 :type 'boolean)
595 (defcustom org-export-allow-BIND 'confirm
596 "Non-nil means allow #+BIND to define local variable values for export.
597 This is a potential security risk, which is why the user must
598 confirm the use of these lines."
599 :group 'org-export-general
600 :type '(choice
601 (const :tag "Never" nil)
602 (const :tag "Always" t)
603 (const :tag "Ask a confirmation for each file" confirm)))
605 (defcustom org-export-snippet-translation-alist nil
606 "Alist between export snippets back-ends and exporter back-ends.
608 This variable allows to provide shortcuts for export snippets.
610 For example, with a value of '\(\(\"h\" . \"html\"\)\), the HTML
611 back-end will recognize the contents of \"@h{<b>}\" as HTML code
612 while every other back-end will ignore it."
613 :group 'org-export-general
614 :type '(repeat
615 (cons
616 (string :tag "Shortcut")
617 (string :tag "Back-end"))))
619 (defcustom org-export-coding-system nil
620 "Coding system for the exported file."
621 :group 'org-export-general
622 :type 'coding-system)
624 (defcustom org-export-copy-to-kill-ring t
625 "Non-nil means exported stuff will also be pushed onto the kill ring."
626 :group 'org-export-general
627 :type 'boolean)
629 (defcustom org-export-initial-scope 'buffer
630 "The initial scope when exporting with `org-export-dispatch'.
631 This variable can be either set to `buffer' or `subtree'."
632 :group 'org-export-general
633 :type '(choice
634 (const :tag "Export current buffer" 'buffer)
635 (const :tag "Export current subtree" 'subtree)))
637 (defcustom org-export-show-temporary-export-buffer t
638 "Non-nil means show buffer after exporting to temp buffer.
639 When Org exports to a file, the buffer visiting that file is ever
640 shown, but remains buried. However, when exporting to
641 a temporary buffer, that buffer is popped up in a second window.
642 When this variable is nil, the buffer remains buried also in
643 these cases."
644 :group 'org-export-general
645 :type 'boolean)
647 (defcustom org-export-dispatch-use-expert-ui nil
648 "Non-nil means using a non-intrusive `org-export-dispatch'.
649 In that case, no help buffer is displayed. Though, an indicator
650 for current export scope is added to the prompt \(i.e. \"b\" when
651 output is restricted to body only, \"s\" when it is restricted to
652 the current subtree and \"v\" when only visible elements are
653 considered for export\). Also, \[?] allows to switch back to
654 standard mode."
655 :group 'org-export-general
656 :type 'boolean)
660 ;;; The Communication Channel
662 ;; During export process, every function has access to a number of
663 ;; properties. They are of three types:
665 ;; 1. Environment options are collected once at the very beginning of
666 ;; the process, out of the original buffer and configuration.
667 ;; Collecting them is handled by `org-export-get-environment'
668 ;; function.
670 ;; Most environment options are defined through the
671 ;; `org-export-option-alist' variable.
673 ;; 2. Tree properties are extracted directly from the parsed tree,
674 ;; just before export, by `org-export-collect-tree-properties'.
676 ;; 3. Local options are updated during parsing, and their value
677 ;; depends on the level of recursion. For now, only `:ignore-list'
678 ;; belongs to that category.
680 ;; Here is the full list of properties available during transcode
681 ;; process, with their category (option, tree or local) and their
682 ;; value type.
684 ;; + `:author' :: Author's name.
685 ;; - category :: option
686 ;; - type :: string
688 ;; + `:back-end' :: Current back-end used for transcoding.
689 ;; - category :: tree
690 ;; - type :: symbol
692 ;; + `:creator' :: String to write as creation information.
693 ;; - category :: option
694 ;; - type :: string
696 ;; + `:date' :: String to use as date.
697 ;; - category :: option
698 ;; - type :: string
700 ;; + `:description' :: Description text for the current data.
701 ;; - category :: option
702 ;; - type :: string
704 ;; + `:email' :: Author's email.
705 ;; - category :: option
706 ;; - type :: string
708 ;; + `:exclude-tags' :: Tags for exclusion of subtrees from export
709 ;; process.
710 ;; - category :: option
711 ;; - type :: list of strings
713 ;; + `:footnote-definition-alist' :: Alist between footnote labels and
714 ;; their definition, as parsed data. Only non-inlined footnotes
715 ;; are represented in this alist. Also, every definition isn't
716 ;; guaranteed to be referenced in the parse tree. The purpose of
717 ;; this property is to preserve definitions from oblivion
718 ;; (i.e. when the parse tree comes from a part of the original
719 ;; buffer), it isn't meant for direct use in a back-end. To
720 ;; retrieve a definition relative to a reference, use
721 ;; `org-export-get-footnote-definition' instead.
722 ;; - category :: option
723 ;; - type :: alist (STRING . LIST)
725 ;; + `:headline-levels' :: Maximum level being exported as an
726 ;; headline. Comparison is done with the relative level of
727 ;; headlines in the parse tree, not necessarily with their
728 ;; actual level.
729 ;; - category :: option
730 ;; - type :: integer
732 ;; + `:headline-offset' :: Difference between relative and real level
733 ;; of headlines in the parse tree. For example, a value of -1
734 ;; means a level 2 headline should be considered as level
735 ;; 1 (cf. `org-export-get-relative-level').
736 ;; - category :: tree
737 ;; - type :: integer
739 ;; + `:headline-numbering' :: Alist between headlines and their
740 ;; numbering, as a list of numbers
741 ;; (cf. `org-export-get-headline-number').
742 ;; - category :: tree
743 ;; - type :: alist (INTEGER . LIST)
745 ;; + `:ignore-list' :: List of elements and objects that should be
746 ;; ignored during export.
747 ;; - category :: local
748 ;; - type :: list of elements and objects
750 ;; + `:input-file' :: Full path to input file, if any.
751 ;; - category :: option
752 ;; - type :: string or nil
754 ;; + `:keywords' :: List of keywords attached to data.
755 ;; - category :: option
756 ;; - type :: string
758 ;; + `:language' :: Default language used for translations.
759 ;; - category :: option
760 ;; - type :: string
762 ;; + `:macro-input-file' :: Macro returning file name of input file,
763 ;; or nil.
764 ;; - category :: option
765 ;; - type :: string or nil
767 ;; + `:parse-tree' :: Whole parse tree, available at any time during
768 ;; transcoding.
769 ;; - category :: global
770 ;; - type :: list (as returned by `org-element-parse-buffer')
772 ;; + `:preserve-breaks' :: Non-nil means transcoding should preserve
773 ;; all line breaks.
774 ;; - category :: option
775 ;; - type :: symbol (nil, t)
777 ;; + `:section-numbers' :: Non-nil means transcoding should add
778 ;; section numbers to headlines.
779 ;; - category :: option
780 ;; - type :: symbol (nil, t)
782 ;; + `:select-tags' :: List of tags enforcing inclusion of sub-trees
783 ;; in transcoding. When such a tag is present,
784 ;; subtrees without it are de facto excluded from
785 ;; the process. See `use-select-tags'.
786 ;; - category :: option
787 ;; - type :: list of strings
789 ;; + `:target-list' :: List of targets encountered in the parse tree.
790 ;; This is used to partly resolve "fuzzy" links
791 ;; (cf. `org-export-resolve-fuzzy-link').
792 ;; - category :: tree
793 ;; - type :: list of strings
795 ;; + `:time-stamp-file' :: Non-nil means transcoding should insert
796 ;; a time stamp in the output.
797 ;; - category :: option
798 ;; - type :: symbol (nil, t)
800 ;; + `:with-archived-trees' :: Non-nil when archived subtrees should
801 ;; also be transcoded. If it is set to the `headline' symbol,
802 ;; only the archived headline's name is retained.
803 ;; - category :: option
804 ;; - type :: symbol (nil, t, `headline')
806 ;; + `:with-author' :: Non-nil means author's name should be included
807 ;; in the output.
808 ;; - category :: option
809 ;; - type :: symbol (nil, t)
811 ;; + `:with-creator' :: Non-nild means a creation sentence should be
812 ;; inserted at the end of the transcoded string. If the value
813 ;; is `comment', it should be commented.
814 ;; - category :: option
815 ;; - type :: symbol (`comment', nil, t)
817 ;; + `:with-drawers' :: Non-nil means drawers should be exported. If
818 ;; its value is a list of names, only drawers with such names
819 ;; will be transcoded.
820 ;; - category :: option
821 ;; - type :: symbol (nil, t) or list of strings
823 ;; + `:with-email' :: Non-nil means output should contain author's
824 ;; email.
825 ;; - category :: option
826 ;; - type :: symbol (nil, t)
828 ;; + `:with-emphasize' :: Non-nil means emphasized text should be
829 ;; interpreted.
830 ;; - category :: option
831 ;; - type :: symbol (nil, t)
833 ;; + `:with-fixed-width' :: Non-nil if transcoder should interpret
834 ;; strings starting with a colon as a fixed-with (verbatim) area.
835 ;; - category :: option
836 ;; - type :: symbol (nil, t)
838 ;; + `:with-footnotes' :: Non-nil if transcoder should interpret
839 ;; footnotes.
840 ;; - category :: option
841 ;; - type :: symbol (nil, t)
843 ;; + `:with-priority' :: Non-nil means transcoding should include
844 ;; priority cookies.
845 ;; - category :: option
846 ;; - type :: symbol (nil, t)
848 ;; + `:with-special-strings' :: Non-nil means transcoding should
849 ;; interpret special strings in plain text.
850 ;; - category :: option
851 ;; - type :: symbol (nil, t)
853 ;; + `:with-sub-superscript' :: Non-nil means transcoding should
854 ;; interpret subscript and superscript. With a value of "{}",
855 ;; only interpret those using curly brackets.
856 ;; - category :: option
857 ;; - type :: symbol (nil, {}, t)
859 ;; + `:with-tables' :: Non-nil means transcoding should interpret
860 ;; tables.
861 ;; - category :: option
862 ;; - type :: symbol (nil, t)
864 ;; + `:with-tags' :: Non-nil means transcoding should keep tags in
865 ;; headlines. A `not-in-toc' value will remove them
866 ;; from the table of contents, if any, nonetheless.
867 ;; - category :: option
868 ;; - type :: symbol (nil, t, `not-in-toc')
870 ;; + `:with-tasks' :: Non-nil means transcoding should include
871 ;; headlines with a TODO keyword. A `todo' value
872 ;; will only include headlines with a todo type
873 ;; keyword while a `done' value will do the
874 ;; contrary. If a list of strings is provided, only
875 ;; tasks with keywords belonging to that list will
876 ;; be kept.
877 ;; - category :: option
878 ;; - type :: symbol (t, todo, done, nil) or list of strings
880 ;; + `:with-timestamps' :: Non-nil means transcoding should include
881 ;; time stamps and associated keywords. Otherwise, completely
882 ;; remove them.
883 ;; - category :: option
884 ;; - type :: symbol: (t, nil)
886 ;; + `:with-toc' :: Non-nil means that a table of contents has to be
887 ;; added to the output. An integer value limits its
888 ;; depth.
889 ;; - category :: option
890 ;; - type :: symbol (nil, t or integer)
892 ;; + `:with-todo-keywords' :: Non-nil means transcoding should
893 ;; include TODO keywords.
894 ;; - category :: option
895 ;; - type :: symbol (nil, t)
898 ;;;; Environment Options
900 ;; Environment options encompass all parameters defined outside the
901 ;; scope of the parsed data. They come from five sources, in
902 ;; increasing precedence order:
904 ;; - Global variables,
905 ;; - Buffer's attributes,
906 ;; - Options keyword symbols,
907 ;; - Buffer keywords,
908 ;; - Subtree properties.
910 ;; The central internal function with regards to environment options
911 ;; is `org-export-get-environment'. It updates global variables with
912 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
913 ;; the different sources.
915 ;; The internal functions doing the retrieval are:
916 ;; `org-export-get-global-options',
917 ;; `org-export-get-buffer-attributes',
918 ;; `org-export-parse-option-keyword',
919 ;; `org-export-get-subtree-options' and
920 ;; `org-export-get-inbuffer-options'
922 ;; Also, `org-export-confirm-letbind' and `org-export-install-letbind'
923 ;; take care of the part relative to "#+BIND:" keywords.
925 (defun org-export-get-environment (&optional backend subtreep ext-plist)
926 "Collect export options from the current buffer.
928 Optional argument BACKEND is a symbol specifying which back-end
929 specific options to read, if any.
931 When optional argument SUBTREEP is non-nil, assume the export is
932 done against the current sub-tree.
934 Third optional argument EXT-PLIST is a property list with
935 external parameters overriding Org default settings, but still
936 inferior to file-local settings."
937 ;; First install #+BIND variables.
938 (org-export-install-letbind-maybe)
939 ;; Get and prioritize export options...
940 (let ((options (org-combine-plists
941 ;; ... from global variables...
942 (org-export-get-global-options backend)
943 ;; ... from buffer's attributes...
944 (org-export-get-buffer-attributes)
945 ;; ... from an external property list...
946 ext-plist
947 ;; ... from in-buffer settings...
948 (org-export-get-inbuffer-options
949 backend
950 (and buffer-file-name
951 (org-remove-double-quotes buffer-file-name)))
952 ;; ... and from subtree, when appropriate.
953 (and subtreep (org-export-get-subtree-options))
954 ;; Also install back-end symbol.
955 `(:back-end ,backend))))
956 ;; Return plist.
957 options))
959 (defun org-export-parse-option-keyword (options &optional backend)
960 "Parse an OPTIONS line and return values as a plist.
961 Optional argument BACKEND is a symbol specifying which back-end
962 specific items to read, if any."
963 (let* ((all
964 (append org-export-option-alist
965 (and backend
966 (let ((var (intern
967 (format "org-%s-option-alist" backend))))
968 (and (boundp var) (eval var))))))
969 ;; Build an alist between #+OPTION: item and property-name.
970 (alist (delq nil
971 (mapcar (lambda (e)
972 (when (nth 2 e) (cons (regexp-quote (nth 2 e))
973 (car e))))
974 all)))
975 plist)
976 (mapc (lambda (e)
977 (when (string-match (concat "\\(\\`\\|[ \t]\\)"
978 (car e)
979 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
980 options)
981 (setq plist (plist-put plist
982 (cdr e)
983 (car (read-from-string
984 (match-string 2 options)))))))
985 alist)
986 plist))
988 (defun org-export-get-subtree-options ()
989 "Get export options in subtree at point.
991 Assume point is at subtree's beginning.
993 Return options as a plist."
994 (let (prop plist)
995 (when (setq prop (progn (looking-at org-todo-line-regexp)
996 (or (save-match-data
997 (org-entry-get (point) "EXPORT_TITLE"))
998 (org-match-string-no-properties 3))))
999 (setq plist
1000 (plist-put
1001 plist :title
1002 (org-element-parse-secondary-string
1003 prop
1004 (cdr (assq 'keyword org-element-string-restrictions))))))
1005 (when (setq prop (org-entry-get (point) "EXPORT_TEXT"))
1006 (setq plist (plist-put plist :text prop)))
1007 (when (setq prop (org-entry-get (point) "EXPORT_AUTHOR"))
1008 (setq plist (plist-put plist :author prop)))
1009 (when (setq prop (org-entry-get (point) "EXPORT_DATE"))
1010 (setq plist (plist-put plist :date prop)))
1011 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
1012 (setq plist (org-export-add-options-to-plist plist prop)))
1013 plist))
1015 (defun org-export-get-inbuffer-options (&optional backend files)
1016 "Return current buffer export options, as a plist.
1018 Optional argument BACKEND, when non-nil, is a symbol specifying
1019 which back-end specific options should also be read in the
1020 process.
1022 Optional argument FILES is a list of setup files names read so
1023 far, used to avoid circular dependencies.
1025 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1026 (org-with-wide-buffer
1027 (goto-char (point-min))
1028 (let ((case-fold-search t) plist)
1029 ;; 1. Special keywords, as in `org-export-special-keywords'.
1030 (let ((special-re (org-make-options-regexp org-export-special-keywords)))
1031 (while (re-search-forward special-re nil t)
1032 (let ((element (org-element-at-point)))
1033 (when (eq (org-element-type element) 'keyword)
1034 (let* ((key (org-element-property :key element))
1035 (val (org-element-property :value element))
1036 (prop
1037 (cond
1038 ((string= key "SETUP_FILE")
1039 (let ((file
1040 (expand-file-name
1041 (org-remove-double-quotes (org-trim val)))))
1042 ;; Avoid circular dependencies.
1043 (unless (member file files)
1044 (with-temp-buffer
1045 (insert (org-file-contents file 'noerror))
1046 (org-mode)
1047 (org-export-get-inbuffer-options
1048 backend (cons file files))))))
1049 ((string= key "OPTIONS")
1050 (org-export-parse-option-keyword val backend))
1051 ((string= key "MACRO")
1052 (when (string-match
1053 "^\\([-a-zA-Z0-9_]+\\)\\(?:[ \t]+\\(.*?\\)[ \t]*$\\)?"
1054 val)
1055 (let ((key
1056 (intern
1057 (concat ":macro-"
1058 (downcase (match-string 1 val)))))
1059 (value (org-match-string-no-properties 2 val)))
1060 (cond
1061 ((not value) nil)
1062 ;; Value will be evaled. Leave it as-is.
1063 ((string-match "\\`(eval\\>" value)
1064 (list key value))
1065 ;; Value has to be parsed for nested
1066 ;; macros.
1068 (list
1070 (let ((restr (org-element-restriction 'macro)))
1071 (org-element-parse-secondary-string
1072 ;; If user explicitly asks for
1073 ;; a newline, be sure to preserve it
1074 ;; from further filling with
1075 ;; `hard-newline'. Also replace
1076 ;; "\\n" with "\n", "\\\n" with "\\n"
1077 ;; and so on...
1078 (replace-regexp-in-string
1079 "\\(\\\\\\\\\\)n" "\\\\"
1080 (replace-regexp-in-string
1081 "\\(?:^\\|[^\\\\]\\)\\(\\\\n\\)"
1082 hard-newline value nil nil 1)
1083 nil nil 1)
1084 restr)))))))))))
1085 (setq plist (org-combine-plists plist prop)))))))
1086 ;; 2. Standard options, as in `org-export-option-alist'.
1087 (let* ((all (append org-export-option-alist
1088 ;; Also look for back-end specific options
1089 ;; if BACKEND is defined.
1090 (and backend
1091 (let ((var
1092 (intern
1093 (format "org-%s-option-alist" backend))))
1094 (and (boundp var) (eval var))))))
1095 ;; Build alist between keyword name and property name.
1096 (alist
1097 (delq nil (mapcar
1098 (lambda (e) (when (nth 1 e) (cons (nth 1 e) (car e))))
1099 all)))
1100 ;; Build regexp matching all keywords associated to export
1101 ;; options. Note: the search is case insensitive.
1102 (opt-re (org-make-options-regexp
1103 (delq nil (mapcar (lambda (e) (nth 1 e)) all)))))
1104 (goto-char (point-min))
1105 (while (re-search-forward opt-re nil t)
1106 (let ((element (org-element-at-point)))
1107 (when (eq (org-element-type element) 'keyword)
1108 (let* ((key (org-element-property :key element))
1109 (val (org-element-property :value element))
1110 (prop (cdr (assoc key alist)))
1111 (behaviour (nth 4 (assq prop all))))
1112 (setq plist
1113 (plist-put
1114 plist prop
1115 ;; Handle value depending on specified BEHAVIOUR.
1116 (case behaviour
1117 (space
1118 (if (not (plist-get plist prop)) (org-trim val)
1119 (concat (plist-get plist prop) " " (org-trim val))))
1120 (newline
1121 (org-trim
1122 (concat (plist-get plist prop) "\n" (org-trim val))))
1123 (split
1124 `(,@(plist-get plist prop) ,@(org-split-string val)))
1125 ('t val)
1126 (otherwise (if (not (plist-member plist prop)) val
1127 (plist-get plist prop))))))))))
1128 ;; Parse keywords specified in `org-element-parsed-keywords'.
1129 (mapc
1130 (lambda (key)
1131 (let* ((prop (cdr (assoc key alist)))
1132 (value (and prop (plist-get plist prop))))
1133 (when (stringp value)
1134 (setq plist
1135 (plist-put
1136 plist prop
1137 (org-element-parse-secondary-string
1138 value (org-element-restriction 'keyword)))))))
1139 org-element-parsed-keywords))
1140 ;; 3. Return final value.
1141 plist)))
1143 (defun org-export-get-buffer-attributes ()
1144 "Return properties related to buffer attributes, as a plist."
1145 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
1146 (list
1147 ;; Store full path of input file name, or nil. For internal use.
1148 :input-file visited-file
1149 :title (or (and visited-file
1150 (file-name-sans-extension
1151 (file-name-nondirectory visited-file)))
1152 (buffer-name (buffer-base-buffer)))
1153 :macro-modification-time
1154 (and visited-file
1155 (file-exists-p visited-file)
1156 (concat "(eval (format-time-string \"$1\" '"
1157 (prin1-to-string (nth 5 (file-attributes visited-file)))
1158 "))"))
1159 ;; Store input file name as a macro.
1160 :macro-input-file (and visited-file (file-name-nondirectory visited-file))
1161 ;; `:macro-date', `:macro-time' and `:macro-property' could as
1162 ;; well be initialized as tree properties, since they don't
1163 ;; depend on buffer properties. Though, it may be more logical
1164 ;; to keep them close to other ":macro-" properties.
1165 :macro-date "(eval (format-time-string \"$1\"))"
1166 :macro-time "(eval (format-time-string \"$1\"))"
1167 :macro-property "(eval (org-entry-get nil \"$1\" 'selective))")))
1169 (defun org-export-get-global-options (&optional backend)
1170 "Return global export options as a plist.
1172 Optional argument BACKEND, if non-nil, is a symbol specifying
1173 which back-end specific export options should also be read in the
1174 process."
1175 (let ((all (append org-export-option-alist
1176 (and backend
1177 (let ((var (intern
1178 (format "org-%s-option-alist" backend))))
1179 (and (boundp var) (eval var))))))
1180 ;; Output value.
1181 plist)
1182 (mapc (lambda (cell)
1183 (setq plist (plist-put plist (car cell) (eval (nth 3 cell)))))
1184 all)
1185 ;; Return value.
1186 plist))
1188 (defun org-export-store-footnote-definitions (info)
1189 "Collect and store footnote definitions from current buffer in INFO.
1191 INFO is a plist containing export options.
1193 Footnotes definitions are stored as a alist whose CAR is
1194 footnote's label, as a string, and CDR the contents, as a parse
1195 tree. This alist will be consed to the value of
1196 `:footnote-definition-alist' in INFO, if any.
1198 The new plist is returned; use
1200 \(setq info (org-export-store-footnote-definitions info))
1202 to be sure to use the new value. INFO is modified by side
1203 effects."
1204 ;; Footnotes definitions must be collected in the original buffer,
1205 ;; as there's no insurance that they will still be in the parse
1206 ;; tree, due to some narrowing.
1207 (plist-put
1208 info :footnote-definition-alist
1209 (let ((alist (plist-get info :footnote-definition-alist)))
1210 (org-with-wide-buffer
1211 (goto-char (point-min))
1212 (while (re-search-forward org-footnote-definition-re nil t)
1213 (let ((def (org-footnote-at-definition-p)))
1214 (when def
1215 (org-skip-whitespace)
1216 (push (cons (car def)
1217 (save-restriction
1218 (narrow-to-region (point) (nth 2 def))
1219 ;; Like `org-element-parse-buffer', but
1220 ;; makes sure the definition doesn't start
1221 ;; with a section element.
1222 (nconc
1223 (list 'org-data nil)
1224 (org-element-parse-elements
1225 (point-min) (point-max) nil nil nil nil nil))))
1226 alist))))
1227 alist))))
1229 (defvar org-export-allow-BIND-local nil)
1230 (defun org-export-confirm-letbind ()
1231 "Can we use #+BIND values during export?
1232 By default this will ask for confirmation by the user, to divert
1233 possible security risks."
1234 (cond
1235 ((not org-export-allow-BIND) nil)
1236 ((eq org-export-allow-BIND t) t)
1237 ((local-variable-p 'org-export-allow-BIND-local) org-export-allow-BIND-local)
1238 (t (org-set-local 'org-export-allow-BIND-local
1239 (yes-or-no-p "Allow BIND values in this buffer? ")))))
1241 (defun org-export-install-letbind-maybe ()
1242 "Install the values from #+BIND lines as local variables.
1243 Variables must be installed before in-buffer options are
1244 retrieved."
1245 (let (letbind pair)
1246 (org-with-wide-buffer
1247 (goto-char (point-min))
1248 (while (re-search-forward (org-make-options-regexp '("BIND")) nil t)
1249 (when (org-export-confirm-letbind)
1250 (push (read (concat "(" (org-match-string-no-properties 2) ")"))
1251 letbind))))
1252 (while (setq pair (pop letbind))
1253 (org-set-local (car pair) (nth 1 pair)))))
1256 ;;;; Tree Properties
1258 ;; Tree properties are infromation extracted from parse tree. They
1259 ;; are initialized at the beginning of the transcoding process by
1260 ;; `org-export-collect-tree-properties'.
1262 ;; Dedicated functions focus on computing the value of specific tree
1263 ;; properties during initialization. Thus,
1264 ;; `org-export-populate-ignore-list' lists elements and objects that
1265 ;; should be skipped during export, `org-export-get-min-level' gets
1266 ;; the minimal exportable level, used as a basis to compute relative
1267 ;; level for headlines. Eventually
1268 ;; `org-export-collect-headline-numbering' builds an alist between
1269 ;; headlines and their numbering.
1271 (defun org-export-collect-tree-properties (data info)
1272 "Extract tree properties from parse tree.
1274 DATA is the parse tree from which information is retrieved. INFO
1275 is a list holding export options.
1277 Following tree properties are set or updated:
1278 `:footnote-definition-alist' List of footnotes definitions in
1279 original buffer and current parse tree.
1281 `:headline-offset' Offset between true level of headlines and
1282 local level. An offset of -1 means an headline
1283 of level 2 should be considered as a level
1284 1 headline in the context.
1286 `:headline-numbering' Alist of all headlines as key an the
1287 associated numbering as value.
1289 `:ignore-list' List of elements that should be ignored during
1290 export.
1292 `:target-list' List of all targets in the parse tree."
1293 ;; Install the parse tree in the communication channel, in order to
1294 ;; use `org-export-get-genealogy' and al.
1295 (setq info (plist-put info :parse-tree data))
1296 ;; Get the list of elements and objects to ignore, and put it into
1297 ;; `:ignore-list'. Do not overwrite any user ignore that might have
1298 ;; been done during parse tree filtering.
1299 (setq info
1300 (plist-put info
1301 :ignore-list
1302 (append (org-export-populate-ignore-list data info)
1303 (plist-get info :ignore-list))))
1304 ;; Compute `:headline-offset' in order to be able to use
1305 ;; `org-export-get-relative-level'.
1306 (setq info
1307 (plist-put info
1308 :headline-offset (- 1 (org-export-get-min-level data info))))
1309 ;; Update footnotes definitions list with definitions in parse tree.
1310 ;; This is required since buffer expansion might have modified
1311 ;; boundaries of footnote definitions contained in the parse tree.
1312 ;; This way, definitions in `footnote-definition-alist' are bound to
1313 ;; match those in the parse tree.
1314 (let ((defs (plist-get info :footnote-definition-alist)))
1315 (org-element-map
1316 data 'footnote-definition
1317 (lambda (fn)
1318 (push (cons (org-element-property :label fn)
1319 `(org-data nil ,@(org-element-contents fn)))
1320 defs)))
1321 (setq info (plist-put info :footnote-definition-alist defs)))
1322 ;; Properties order doesn't matter: get the rest of the tree
1323 ;; properties.
1324 (nconc
1325 `(:target-list
1326 ,(org-element-map
1327 data '(keyword target)
1328 (lambda (blob)
1329 (when (or (eq (org-element-type blob) 'target)
1330 (string= (org-element-property :key blob) "TARGET"))
1331 blob)) info)
1332 :headline-numbering ,(org-export-collect-headline-numbering data info))
1333 info))
1335 (defun org-export-get-min-level (data options)
1336 "Return minimum exportable headline's level in DATA.
1337 DATA is parsed tree as returned by `org-element-parse-buffer'.
1338 OPTIONS is a plist holding export options."
1339 (catch 'exit
1340 (let ((min-level 10000))
1341 (mapc
1342 (lambda (blob)
1343 (when (and (eq (org-element-type blob) 'headline)
1344 (not (member blob (plist-get options :ignore-list))))
1345 (setq min-level
1346 (min (org-element-property :level blob) min-level)))
1347 (when (= min-level 1) (throw 'exit 1)))
1348 (org-element-contents data))
1349 ;; If no headline was found, for the sake of consistency, set
1350 ;; minimum level to 1 nonetheless.
1351 (if (= min-level 10000) 1 min-level))))
1353 (defun org-export-collect-headline-numbering (data options)
1354 "Return numbering of all exportable headlines in a parse tree.
1356 DATA is the parse tree. OPTIONS is the plist holding export
1357 options.
1359 Return an alist whose key is an headline and value is its
1360 associated numbering \(in the shape of a list of numbers\)."
1361 (let ((numbering (make-vector org-export-max-depth 0)))
1362 (org-element-map
1363 data
1364 'headline
1365 (lambda (headline)
1366 (let ((relative-level
1367 (1- (org-export-get-relative-level headline options))))
1368 (cons
1369 headline
1370 (loop for n across numbering
1371 for idx from 0 to org-export-max-depth
1372 when (< idx relative-level) collect n
1373 when (= idx relative-level) collect (aset numbering idx (1+ n))
1374 when (> idx relative-level) do (aset numbering idx 0)))))
1375 options)))
1377 (defun org-export-populate-ignore-list (data options)
1378 "Return list of elements and objects to ignore during export.
1380 DATA is the parse tree to traverse. OPTIONS is the plist holding
1381 export options.
1383 Return elements or objects to ignore as a list."
1384 (let (ignore
1385 (walk-data
1386 (function
1387 (lambda (data options selected)
1388 ;; Collect ignored elements or objects into IGNORE-LIST.
1389 (mapc
1390 (lambda (el)
1391 (if (org-export--skip-p el options selected) (push el ignore)
1392 (let ((type (org-element-type el)))
1393 (if (and (eq (plist-get info :with-archived-trees) 'headline)
1394 (eq (org-element-type el) 'headline)
1395 (org-element-property :archivedp el))
1396 ;; If headline is archived but tree below has
1397 ;; to be skipped, add it to ignore list.
1398 (mapc (lambda (e) (push e ignore))
1399 (org-element-contents el))
1400 ;; Move into recursive objects/elements.
1401 (when (org-element-contents el)
1402 (funcall walk-data el options selected))))))
1403 (org-element-contents data))))))
1404 ;; Main call. First find trees containing a select tag, if any.
1405 (funcall walk-data data options (org-export--selected-trees data options))
1406 ;; Return value.
1407 ignore))
1409 (defun org-export--selected-trees (data info)
1410 "Return list of headlines containing a select tag in their tree.
1411 DATA is parsed data as returned by `org-element-parse-buffer'.
1412 INFO is a plist holding export options."
1413 (let (selected-trees
1414 (walk-data
1415 (function
1416 (lambda (data genealogy)
1417 (case (org-element-type data)
1418 (org-data
1419 (funcall walk-data (org-element-contents data) genealogy))
1420 (headline
1421 (let ((tags (org-element-property :tags headline)))
1422 (if (and tags
1423 (loop for tag in (plist-get info :select-tags)
1424 thereis (string-match
1425 (format ":%s:" tag) tags)))
1426 ;; When a select tag is found, mark as acceptable
1427 ;; full genealogy and every headline within the
1428 ;; tree.
1429 (setq selected-trees
1430 (append
1431 (cons data genealogy)
1432 (org-element-map data 'headline 'identity)
1433 selected-trees))
1434 ;; Else, continue searching in tree, recursively.
1435 (funcall walk-data data (cons data genealogy))))))))))
1436 (funcall walk-data data nil) selected-trees))
1438 (defun org-export--skip-p (blob options select-tags)
1439 "Non-nil when element or object BLOB should be skipped during export.
1440 OPTIONS is the plist holding export options."
1441 (case (org-element-type blob)
1442 ;; Check headline.
1443 (headline
1444 (let ((with-tasks (plist-get options :with-tasks))
1445 (todo (org-element-property :todo-keyword blob))
1446 (todo-type (org-element-property :todo-type blob))
1447 (archived (plist-get options :with-archived-trees))
1448 (tag-list (let ((tags (org-element-property :tags blob)))
1449 (and tags (org-split-string tags ":")))))
1451 ;; Ignore subtrees with an exclude tag.
1452 (loop for k in (plist-get options :exclude-tags)
1453 thereis (member k tag-list))
1454 ;; Ignore subtrees without a select tag, when such tag is
1455 ;; found in the buffer.
1456 (member blob select-tags)
1457 ;; Ignore commented sub-trees.
1458 (org-element-property :commentedp blob)
1459 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
1460 (and (not archived) (org-element-property :archivedp blob))
1461 ;; Ignore tasks, if specified by `:with-tasks' property.
1462 (and todo
1463 (or (not with-tasks)
1464 (and (memq with-tasks '(todo done))
1465 (not (eq todo-type with-tasks)))
1466 (and (consp with-tasks) (not (member todo with-tasks))))))))
1467 ;; Check time-stamp.
1468 (time-stamp (not (plist-get options :with-timestamps)))
1469 ;; Check drawer.
1470 (drawer
1471 (or (not (plist-get options :with-drawers))
1472 (and (consp (plist-get options :with-drawers))
1473 (not (member (org-element-property :drawer-name blob)
1474 (plist-get options :with-drawers))))))
1475 ;; Check table-row.
1476 (table-row (org-export-table-row-is-special-p blob options))
1477 ;; Check table-cell.
1478 (table-cell
1479 (and (org-export-table-has-special-column-p
1480 (nth 1 (org-export-get-genealogy blob options)))
1481 (not (org-export-get-previous-element blob options))))))
1485 ;;; The Transcoder
1487 ;; This function reads Org data (obtained with, i.e.
1488 ;; `org-element-parse-buffer') and transcodes it into a specified
1489 ;; back-end output. It takes care of updating local properties,
1490 ;; filtering out elements or objects according to export options and
1491 ;; organizing the output blank lines and white space are preserved.
1493 ;; Though, this function is inapropriate for secondary strings, which
1494 ;; require a fresh copy of the plist passed as INFO argument. Thus,
1495 ;; `org-export-secondary-string' is provided for that specific task.
1497 ;; Internally, three functions handle the filtering of objects and
1498 ;; elements during the export. In particular,
1499 ;; `org-export-ignore-element' marks an element or object so future
1500 ;; parse tree traversals skip it, `org-export-interpret-p' tells which
1501 ;; elements or objects should be seen as real Org syntax and
1502 ;; `org-export-expand' transforms the others back into their original
1503 ;; shape.
1505 (defun org-export-data (data info)
1506 "Convert DATA into current back-end format.
1508 DATA is a nested list as returned by `org-element-parse-buffer'.
1510 INFO is a plist holding export options and also used as
1511 a communication channel between elements when walking the nested
1512 list.
1514 Return transcoded string."
1515 (mapconcat
1516 ;; BLOB can be an element, an object, a string, or nil.
1517 (lambda (blob)
1518 (cond
1519 ((not blob) nil)
1520 ;; BLOB is a string. Check if the optional transcoder for plain
1521 ;; text exists, and call it in that case. Otherwise, simply
1522 ;; return string. Also update INFO and call
1523 ;; `org-export-filter-plain-text-functions'.
1524 ((stringp blob)
1525 (let ((transcoder (intern (format "org-%s-plain-text"
1526 (plist-get info :back-end)))))
1527 (org-export-filter-apply-functions
1528 (plist-get info :filter-plain-text)
1529 (if (fboundp transcoder) (funcall transcoder blob info) blob)
1530 info)))
1531 ;; BLOB is an element or an object.
1533 (let* ((type (org-element-type blob))
1534 ;; 1. Determine the appropriate TRANSCODER.
1535 (transcoder
1536 (cond
1537 ;; 1.0 A full Org document is inserted.
1538 ((eq type 'org-data) 'identity)
1539 ;; 1.1. BLOB should be ignored.
1540 ((member blob (plist-get info :ignore-list)) nil)
1541 ;; 1.2. BLOB shouldn't be transcoded. Interpret it
1542 ;; back into Org syntax.
1543 ((not (org-export-interpret-p blob info)) 'org-export-expand)
1544 ;; 1.3. Else apply naming convention.
1545 (t (let ((trans (intern (format "org-%s-%s"
1546 (plist-get info :back-end)
1547 type))))
1548 (and (fboundp trans) trans)))))
1549 ;; 2. Compute CONTENTS of BLOB.
1550 (contents
1551 (cond
1552 ;; Case 0. No transcoder or no contents: ignore BLOB.
1553 ((or (not transcoder) (not (org-element-contents blob))) nil)
1554 ;; Case 1. Transparently export an Org document.
1555 ((eq type 'org-data) (org-export-data blob info))
1556 ;; Case 2. For a greater element.
1557 ((memq type org-element-greater-elements)
1558 ;; Ignore contents of an archived tree
1559 ;; when `:with-archived-trees' is `headline'.
1560 (unless (and
1561 (eq type 'headline)
1562 (eq (plist-get info :with-archived-trees) 'headline)
1563 (org-element-property :archivedp blob))
1564 (org-element-normalize-string (org-export-data blob info))))
1565 ;; Case 3. For an element containing objects.
1567 (org-export-data
1568 (org-element-normalize-contents
1569 blob
1570 ;; When normalizing contents of the first paragraph
1571 ;; in an item or a footnote definition, ignore
1572 ;; first line's indentation: there is none and it
1573 ;; might be misleading.
1574 (and (eq type 'paragraph)
1575 (not (org-export-get-previous-element blob info))
1576 (let ((parent (org-export-get-parent blob info)))
1577 (memq (org-element-type parent)
1578 '(footnote-definition item)))))
1579 info))))
1580 ;; 3. Transcode BLOB into RESULTS string.
1581 (results (cond
1582 ((not transcoder) nil)
1583 ((eq transcoder 'org-export-expand)
1584 (org-export-data
1585 `(org-data nil ,(funcall transcoder blob contents))
1586 info))
1587 (t (funcall transcoder blob contents info)))))
1588 ;; 4. Return results.
1589 (cond
1590 ((not results) nil)
1591 ;; No filter for a full document.
1592 ((eq type 'org-data) results)
1593 ;; Otherwise, update INFO, append the same white space
1594 ;; between elements or objects as in the original buffer,
1595 ;; and call appropriate filters.
1597 (let ((results
1598 (org-export-filter-apply-functions
1599 (plist-get info (intern (format ":filter-%s" type)))
1600 (let ((post-blank (org-element-property :post-blank blob)))
1601 (if (memq type org-element-all-elements)
1602 (concat (org-element-normalize-string results)
1603 (make-string post-blank ?\n))
1604 (concat results (make-string post-blank ? ))))
1605 info)))
1606 ;; Eventually return string.
1607 results)))))))
1608 (org-element-contents data) ""))
1610 (defun org-export-secondary-string (secondary info)
1611 "Convert SECONDARY string into current back-end target format.
1613 SECONDARY is a nested list as returned by
1614 `org-element-parse-secondary-string'. INFO is a plist used as
1615 a communication channel.
1617 Return transcoded string."
1618 ;; Make SECONDARY acceptable for `org-export-data'.
1619 (let ((s (if (listp secondary) secondary (list secondary))))
1620 (org-export-data `(org-data nil ,@s) (copy-sequence info))))
1622 (defun org-export-interpret-p (blob info)
1623 "Non-nil if element or object BLOB should be interpreted as Org syntax.
1624 Check is done according to export options INFO, stored as
1625 a plist."
1626 (case (org-element-type blob)
1627 ;; ... entities...
1628 (entity (plist-get info :with-entities))
1629 ;; ... emphasis...
1630 (emphasis (plist-get info :with-emphasize))
1631 ;; ... fixed-width areas.
1632 (fixed-width (plist-get info :with-fixed-width))
1633 ;; ... footnotes...
1634 ((footnote-definition footnote-reference)
1635 (plist-get info :with-footnotes))
1636 ;; ... sub/superscripts...
1637 ((subscript superscript)
1638 (let ((sub/super-p (plist-get info :with-sub-superscript)))
1639 (if (eq sub/super-p '{})
1640 (org-element-property :use-brackets-p blob)
1641 sub/super-p)))
1642 ;; ... tables...
1643 (table (plist-get info :with-tables))
1644 (otherwise t)))
1646 (defsubst org-export-expand (blob contents)
1647 "Expand a parsed element or object to its original state.
1648 BLOB is either an element or an object. CONTENTS is its
1649 contents, as a string or nil."
1650 (funcall (intern (format "org-element-%s-interpreter" (org-element-type blob)))
1651 blob contents))
1653 (defun org-export-ignore-element (element info)
1654 "Add ELEMENT to `:ignore-list' in INFO.
1656 Any element in `:ignore-list' will be skipped when using
1657 `org-element-map'. INFO is modified by side effects."
1658 (plist-put info :ignore-list (cons element (plist-get info :ignore-list))))
1662 ;;; The Filter System
1664 ;; Filters allow end-users to tweak easily the transcoded output.
1665 ;; They are the functional counterpart of hooks, as every filter in
1666 ;; a set is applied to the return value of the previous one.
1668 ;; Every set is back-end agnostic. Although, a filter is always
1669 ;; called, in addition to the string it applies to, with the back-end
1670 ;; used as argument, so it's easy enough for the end-user to add
1671 ;; back-end specific filters in the set. The communication channel,
1672 ;; as a plist, is required as the third argument.
1674 ;; Filters sets are defined below. There are of four types:
1676 ;; - `org-export-filter-parse-tree-functions' applies directly on the
1677 ;; complete parsed tree. It's the only filters set that doesn't
1678 ;; apply to a string.
1679 ;; - `org-export-filter-final-output-functions' applies to the final
1680 ;; transcoded string.
1681 ;; - `org-export-filter-plain-text-functions' applies to any string
1682 ;; not recognized as Org syntax.
1683 ;; - `org-export-filter-TYPE-functions' applies on the string returned
1684 ;; after an element or object of type TYPE has been transcoded.
1686 ;; All filters sets are applied through
1687 ;; `org-export-filter-apply-functions' function. Filters in a set are
1688 ;; applied in a LIFO fashion. It allows developers to be sure that
1689 ;; their filters will be applied first.
1691 ;; Filters properties are installed in communication channel with
1692 ;; `org-export-install-filters' function.
1694 ;; Eventually, a hook (`org-export-before-parsing-hook') is run just
1695 ;; before parsing to allow for heavy structure modifications.
1698 ;;;; Before Parsing Hook
1700 (defvar org-export-before-parsing-hook nil
1701 "Hook run before parsing an export buffer.
1702 This is run after include keywords have been expanded and Babel
1703 code executed, on a copy of original buffer's area being
1704 exported. Visibility is the same as in the original one. Point
1705 is left at the beginning of the new one.")
1708 ;;;; Special Filters
1710 (defvar org-export-filter-parse-tree-functions nil
1711 "List of functions applied to the parsed tree.
1712 Each filter is called with three arguments: the parse tree, as
1713 returned by `org-element-parse-buffer', the back-end, as
1714 a symbol, and the communication channel, as a plist. It must
1715 return the modified parse tree to transcode.")
1717 (defvar org-export-filter-final-output-functions nil
1718 "List of functions applied to the transcoded string.
1719 Each filter is called with three arguments: the full transcoded
1720 string, the back-end, as a symbol, and the communication channel,
1721 as a plist. It must return a string that will be used as the
1722 final export output.")
1724 (defvar org-export-filter-plain-text-functions nil
1725 "List of functions applied to plain text.
1726 Each filter is called with three arguments: a string which
1727 contains no Org syntax, the back-end, as a symbol, and the
1728 communication channel, as a plist. It must return a string or
1729 nil.")
1732 ;;;; Elements Filters
1734 (defvar org-export-filter-center-block-functions nil
1735 "List of functions applied to a transcoded center block.
1736 Each filter is called with three arguments: the transcoded data,
1737 as a string, the back-end, as a symbol, and the communication
1738 channel, as a plist. It must return a string or nil.")
1740 (defvar org-export-filter-drawer-functions nil
1741 "List of functions applied to a transcoded drawer.
1742 Each filter is called with three arguments: the transcoded data,
1743 as a string, the back-end, as a symbol, and the communication
1744 channel, as a plist. It must return a string or nil.")
1746 (defvar org-export-filter-dynamic-block-functions nil
1747 "List of functions applied to a transcoded dynamic-block.
1748 Each filter is called with three arguments: the transcoded data,
1749 as a string, the back-end, as a symbol, and the communication
1750 channel, as a plist. It must return a string or nil.")
1752 (defvar org-export-filter-headline-functions nil
1753 "List of functions applied to a transcoded headline.
1754 Each filter is called with three arguments: the transcoded data,
1755 as a string, the back-end, as a symbol, and the communication
1756 channel, as a plist. It must return a string or nil.")
1758 (defvar org-export-filter-inlinetask-functions nil
1759 "List of functions applied to a transcoded inlinetask.
1760 Each filter is called with three arguments: the transcoded data,
1761 as a string, the back-end, as a symbol, and the communication
1762 channel, as a plist. It must return a string or nil.")
1764 (defvar org-export-filter-plain-list-functions nil
1765 "List of functions applied to a transcoded plain-list.
1766 Each filter is called with three arguments: the transcoded data,
1767 as a string, the back-end, as a symbol, and the communication
1768 channel, as a plist. It must return a string or nil.")
1770 (defvar org-export-filter-item-functions nil
1771 "List of functions applied to a transcoded item.
1772 Each filter is called with three arguments: the transcoded data,
1773 as a string, the back-end, as a symbol, and the communication
1774 channel, as a plist. It must return a string or nil.")
1776 (defvar org-export-filter-comment-functions nil
1777 "List of functions applied to a transcoded comment.
1778 Each filter is called with three arguments: the transcoded data,
1779 as a string, the back-end, as a symbol, and the communication
1780 channel, as a plist. It must return a string or nil.")
1782 (defvar org-export-filter-comment-block-functions nil
1783 "List of functions applied to a transcoded comment-comment.
1784 Each filter is called with three arguments: the transcoded data,
1785 as a string, the back-end, as a symbol, and the communication
1786 channel, as a plist. It must return a string or nil.")
1788 (defvar org-export-filter-example-block-functions nil
1789 "List of functions applied to a transcoded example-block.
1790 Each filter is called with three arguments: the transcoded data,
1791 as a string, the back-end, as a symbol, and the communication
1792 channel, as a plist. It must return a string or nil.")
1794 (defvar org-export-filter-export-block-functions nil
1795 "List of functions applied to a transcoded export-block.
1796 Each filter is called with three arguments: the transcoded data,
1797 as a string, the back-end, as a symbol, and the communication
1798 channel, as a plist. It must return a string or nil.")
1800 (defvar org-export-filter-fixed-width-functions nil
1801 "List of functions applied to a transcoded fixed-width.
1802 Each filter is called with three arguments: the transcoded data,
1803 as a string, the back-end, as a symbol, and the communication
1804 channel, as a plist. It must return a string or nil.")
1806 (defvar org-export-filter-footnote-definition-functions nil
1807 "List of functions applied to a transcoded footnote-definition.
1808 Each filter is called with three arguments: the transcoded data,
1809 as a string, the back-end, as a symbol, and the communication
1810 channel, as a plist. It must return a string or nil.")
1812 (defvar org-export-filter-horizontal-rule-functions nil
1813 "List of functions applied to a transcoded horizontal-rule.
1814 Each filter is called with three arguments: the transcoded data,
1815 as a string, the back-end, as a symbol, and the communication
1816 channel, as a plist. It must return a string or nil.")
1818 (defvar org-export-filter-keyword-functions nil
1819 "List of functions applied to a transcoded keyword.
1820 Each filter is called with three arguments: the transcoded data,
1821 as a string, the back-end, as a symbol, and the communication
1822 channel, as a plist. It must return a string or nil.")
1824 (defvar org-export-filter-latex-environment-functions nil
1825 "List of functions applied to a transcoded latex-environment.
1826 Each filter is called with three arguments: the transcoded data,
1827 as a string, the back-end, as a symbol, and the communication
1828 channel, as a plist. It must return a string or nil.")
1830 (defvar org-export-filter-babel-call-functions nil
1831 "List of functions applied to a transcoded babel-call.
1832 Each filter is called with three arguments: the transcoded data,
1833 as a string, the back-end, as a symbol, and the communication
1834 channel, as a plist. It must return a string or nil.")
1836 (defvar org-export-filter-paragraph-functions nil
1837 "List of functions applied to a transcoded paragraph.
1838 Each filter is called with three arguments: the transcoded data,
1839 as a string, the back-end, as a symbol, and the communication
1840 channel, as a plist. It must return a string or nil.")
1842 (defvar org-export-filter-property-drawer-functions nil
1843 "List of functions applied to a transcoded property-drawer.
1844 Each filter is called with three arguments: the transcoded data,
1845 as a string, the back-end, as a symbol, and the communication
1846 channel, as a plist. It must return a string or nil.")
1848 (defvar org-export-filter-quote-block-functions nil
1849 "List of functions applied to a transcoded quote block.
1850 Each filter is called with three arguments: the transcoded quote
1851 data, 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-quote-section-functions nil
1856 "List of functions applied to a transcoded quote-section.
1857 Each filter is called with three arguments: the transcoded data,
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-section-functions nil
1862 "List of functions applied to a transcoded section.
1863 Each filter is called with three arguments: the transcoded data,
1864 as a string, the back-end, as a symbol, and the communication
1865 channel, as a plist. It must return a string or nil.")
1867 (defvar org-export-filter-special-block-functions nil
1868 "List of functions applied to a transcoded special block.
1869 Each filter is called with three arguments: the transcoded data,
1870 as a string, the back-end, as a symbol, and the communication
1871 channel, as a plist. It must return a string or nil.")
1873 (defvar org-export-filter-src-block-functions nil
1874 "List of functions applied to a transcoded src-block.
1875 Each filter is called with three arguments: the transcoded data,
1876 as a string, the back-end, as a symbol, and the communication
1877 channel, as a plist. It must return a string or nil.")
1879 (defvar org-export-filter-table-functions nil
1880 "List of functions applied to a transcoded table.
1881 Each filter is called with three arguments: the transcoded data,
1882 as a string, the back-end, as a symbol, and the communication
1883 channel, as a plist. It must return a string or nil.")
1885 (defvar org-export-filter-table-cell-functions nil
1886 "List of functions applied to a transcoded table-cell.
1887 Each filter is called with three arguments: the transcoded data,
1888 as a string, the back-end, as a symbol, and the communication
1889 channel, as a plist. It must return a string or nil.")
1891 (defvar org-export-filter-table-row-functions nil
1892 "List of functions applied to a transcoded table-row.
1893 Each filter is called with three arguments: the transcoded data,
1894 as a string, the back-end, as a symbol, and the communication
1895 channel, as a plist. It must return a string or nil.")
1897 (defvar org-export-filter-verse-block-functions nil
1898 "List of functions applied to a transcoded verse block.
1899 Each filter is called with three arguments: the transcoded data,
1900 as a string, the back-end, as a symbol, and the communication
1901 channel, as a plist. It must return a string or nil.")
1904 ;;;; Objects Filters
1906 (defvar org-export-filter-bold-functions nil
1907 "List of functions applied to transcoded bold text.
1908 Each filter is called with three arguments: the transcoded data,
1909 as a string, the back-end, as a symbol, and the communication
1910 channel, as a plist. It must return a string or nil.")
1912 (defvar org-export-filter-code-functions nil
1913 "List of functions applied to transcoded code text.
1914 Each filter is called with three arguments: the transcoded data,
1915 as a string, the back-end, as a symbol, and the communication
1916 channel, as a plist. It must return a string or nil.")
1918 (defvar org-export-filter-entity-functions nil
1919 "List of functions applied to a transcoded entity.
1920 Each filter is called with three arguments: the transcoded data,
1921 as a string, the back-end, as a symbol, and the communication
1922 channel, as a plist. It must return a string or nil.")
1924 (defvar org-export-filter-export-snippet-functions nil
1925 "List of functions applied to a transcoded export-snippet.
1926 Each filter is called with three arguments: the transcoded data,
1927 as a string, the back-end, as a symbol, and the communication
1928 channel, as a plist. It must return a string or nil.")
1930 (defvar org-export-filter-footnote-reference-functions nil
1931 "List of functions applied to a transcoded footnote-reference.
1932 Each filter is called with three arguments: the transcoded data,
1933 as a string, the back-end, as a symbol, and the communication
1934 channel, as a plist. It must return a string or nil.")
1936 (defvar org-export-filter-inline-babel-call-functions nil
1937 "List of functions applied to a transcoded inline-babel-call.
1938 Each filter is called with three arguments: the transcoded data,
1939 as a string, the back-end, as a symbol, and the communication
1940 channel, as a plist. It must return a string or nil.")
1942 (defvar org-export-filter-inline-src-block-functions nil
1943 "List of functions applied to a transcoded inline-src-block.
1944 Each filter is called with three arguments: the transcoded data,
1945 as a string, the back-end, as a symbol, and the communication
1946 channel, as a plist. It must return a string or nil.")
1948 (defvar org-export-filter-italic-functions nil
1949 "List of functions applied to transcoded italic text.
1950 Each filter is called with three arguments: the transcoded data,
1951 as a string, the back-end, as a symbol, and the communication
1952 channel, as a plist. It must return a string or nil.")
1954 (defvar org-export-filter-latex-fragment-functions nil
1955 "List of functions applied to a transcoded latex-fragment.
1956 Each filter is called with three arguments: the transcoded data,
1957 as a string, the back-end, as a symbol, and the communication
1958 channel, as a plist. It must return a string or nil.")
1960 (defvar org-export-filter-line-break-functions nil
1961 "List of functions applied to a transcoded line-break.
1962 Each filter is called with three arguments: the transcoded data,
1963 as a string, the back-end, as a symbol, and the communication
1964 channel, as a plist. It must return a string or nil.")
1966 (defvar org-export-filter-link-functions nil
1967 "List of functions applied to a transcoded link.
1968 Each filter is called with three arguments: the transcoded data,
1969 as a string, the back-end, as a symbol, and the communication
1970 channel, as a plist. It must return a string or nil.")
1972 (defvar org-export-filter-macro-functions nil
1973 "List of functions applied to a transcoded macro.
1974 Each filter is called with three arguments: the transcoded data,
1975 as a string, the back-end, as a symbol, and the communication
1976 channel, as a plist. It must return a string or nil.")
1978 (defvar org-export-filter-radio-target-functions nil
1979 "List of functions applied to a transcoded radio-target.
1980 Each filter is called with three arguments: the transcoded data,
1981 as a string, the back-end, as a symbol, and the communication
1982 channel, as a plist. It must return a string or nil.")
1984 (defvar org-export-filter-statistics-cookie-functions nil
1985 "List of functions applied to a transcoded statistics-cookie.
1986 Each filter is called with three arguments: the transcoded data,
1987 as a string, the back-end, as a symbol, and the communication
1988 channel, as a plist. It must return a string or nil.")
1990 (defvar org-export-filter-strike-through-functions nil
1991 "List of functions applied to transcoded strike-through text.
1992 Each filter is called with three arguments: the transcoded data,
1993 as a string, the back-end, as a symbol, and the communication
1994 channel, as a plist. It must return a string or nil.")
1996 (defvar org-export-filter-subscript-functions nil
1997 "List of functions applied to a transcoded subscript.
1998 Each filter is called with three arguments: the transcoded data,
1999 as a string, the back-end, as a symbol, and the communication
2000 channel, as a plist. It must return a string or nil.")
2002 (defvar org-export-filter-superscript-functions nil
2003 "List of functions applied to a transcoded superscript.
2004 Each filter is called with three arguments: the transcoded data,
2005 as a string, the back-end, as a symbol, and the communication
2006 channel, as a plist. It must return a string or nil.")
2008 (defvar org-export-filter-target-functions nil
2009 "List of functions applied to a transcoded target.
2010 Each filter is called with three arguments: the transcoded data,
2011 as a string, the back-end, as a symbol, and the communication
2012 channel, as a plist. It must return a string or nil.")
2014 (defvar org-export-filter-time-stamp-functions nil
2015 "List of functions applied to a transcoded time-stamp.
2016 Each filter is called with three arguments: the transcoded data,
2017 as a string, the back-end, as a symbol, and the communication
2018 channel, as a plist. It must return a string or nil.")
2020 (defvar org-export-filter-underline-functions nil
2021 "List of functions applied to transcoded underline text.
2022 Each filter is called with three arguments: the transcoded data,
2023 as a string, the back-end, as a symbol, and the communication
2024 channel, as a plist. It must return a string or nil.")
2026 (defvar org-export-filter-verbatim-functions nil
2027 "List of functions applied to transcoded verbatim text.
2028 Each filter is called with three arguments: the transcoded data,
2029 as a string, the back-end, as a symbol, and the communication
2030 channel, as a plist. It must return a string or nil.")
2032 (defun org-export-filter-apply-functions (filters value info)
2033 "Call every function in FILTERS.
2034 Functions are called with arguments VALUE, current export
2035 back-end and INFO. Call is done in a LIFO fashion, to be sure
2036 that developer specified filters, if any, are called first."
2037 (loop for filter in filters
2038 if (not value) return nil else
2039 do (setq value (funcall filter value (plist-get info :back-end) info)))
2040 value)
2042 (defun org-export-install-filters (info)
2043 "Install filters properties in communication channel.
2045 INFO is a plist containing the current communication channel.
2047 Return the updated communication channel."
2048 (let (plist)
2049 ;; Install user defined filters with `org-export-filters-alist'.
2050 (mapc (lambda (p)
2051 (setq plist (plist-put plist (car p) (eval (cdr p)))))
2052 org-export-filters-alist)
2053 ;; Prepend back-end specific filters to that list.
2054 (let ((back-end-filters (intern (format "org-%s-filters-alist"
2055 (plist-get info :back-end)))))
2056 (when (boundp back-end-filters)
2057 (mapc (lambda (p)
2058 ;; Single values get consed, lists are prepended.
2059 (let ((key (car p)) (value (cdr p)))
2060 (when value
2061 (setq plist
2062 (plist-put
2063 plist key
2064 (if (atom value) (cons value (plist-get plist key))
2065 (append value (plist-get plist key))))))))
2066 (eval back-end-filters))))
2067 ;; Return new communication channel.
2068 (org-combine-plists info plist)))
2072 ;;; Core functions
2074 ;; This is the room for the main function, `org-export-as', along with
2075 ;; its derivatives, `org-export-to-buffer' and `org-export-to-file'.
2076 ;; They differ only by the way they output the resulting code.
2078 ;; `org-export-output-file-name' is an auxiliary function meant to be
2079 ;; used with `org-export-to-file'. With a given extension, it tries
2080 ;; to provide a canonical file name to write export output to.
2082 ;; Note that `org-export-as' doesn't really parse the current buffer,
2083 ;; but a copy of it (with the same buffer-local variables and
2084 ;; visibility), where include keywords are expanded and Babel blocks
2085 ;; are executed, if appropriate.
2086 ;; `org-export-with-current-buffer-copy' macro prepares that copy.
2088 ;; File inclusion is taken care of by
2089 ;; `org-export-expand-include-keyword' and
2090 ;; `org-export-prepare-file-contents'. Structure wise, including
2091 ;; a whole Org file in a buffer often makes little sense. For
2092 ;; example, if the file contains an headline and the include keyword
2093 ;; was within an item, the item should contain the headline. That's
2094 ;; why file inclusion should be done before any structure can be
2095 ;; associated to the file, that is before parsing.
2097 (defun org-export-as
2098 (backend &optional subtreep visible-only body-only ext-plist noexpand)
2099 "Transcode current Org buffer into BACKEND code.
2101 If narrowing is active in the current buffer, only transcode its
2102 narrowed part.
2104 If a region is active, transcode that region.
2106 When optional argument SUBTREEP is non-nil, transcode the
2107 sub-tree at point, extracting information from the headline
2108 properties first.
2110 When optional argument VISIBLE-ONLY is non-nil, don't export
2111 contents of hidden elements.
2113 When optional argument BODY-ONLY is non-nil, only return body
2114 code, without preamble nor postamble.
2116 Optional argument EXT-PLIST, when provided, is a property list
2117 with external parameters overriding Org default settings, but
2118 still inferior to file-local settings.
2120 Optional argument NOEXPAND, when non-nil, prevents included files
2121 to be expanded and Babel code to be executed.
2123 Return code as a string."
2124 (save-excursion
2125 (save-restriction
2126 ;; Narrow buffer to an appropriate region or subtree for
2127 ;; parsing. If parsing subtree, be sure to remove main headline
2128 ;; too.
2129 (cond ((org-region-active-p)
2130 (narrow-to-region (region-beginning) (region-end)))
2131 (subtreep
2132 (org-narrow-to-subtree)
2133 (goto-char (point-min))
2134 (forward-line)
2135 (narrow-to-region (point) (point-max))))
2136 ;; 1. Get export environment from original buffer. Store
2137 ;; original footnotes definitions in communication channel as
2138 ;; they might not be accessible anymore in a narrowed parse
2139 ;; tree. Also install user's and developer's filters.
2140 (let ((info (org-export-install-filters
2141 (org-export-store-footnote-definitions
2142 (org-export-get-environment backend subtreep ext-plist))))
2143 ;; 2. Get parse tree. Buffer isn't parsed directly.
2144 ;; Instead, a temporary copy is created, where include
2145 ;; keywords are expanded and code blocks are evaluated.
2146 (tree (let ((buf (or (buffer-file-name (buffer-base-buffer))
2147 (current-buffer))))
2148 (org-export-with-current-buffer-copy
2149 (unless noexpand
2150 (org-export-expand-include-keyword)
2151 ;; Setting `org-current-export-file' is
2152 ;; required by Org Babel to properly resolve
2153 ;; noweb references.
2154 (let ((org-current-export-file buf))
2155 (org-export-blocks-preprocess)))
2156 (goto-char (point-min))
2157 (run-hooks 'org-export-before-parsing-hook)
2158 (org-element-parse-buffer nil visible-only)))))
2159 ;; 3. Call parse-tree filters to get the final tree.
2160 (setq tree
2161 (org-export-filter-apply-functions
2162 (plist-get info :filter-parse-tree) tree info))
2163 ;; 4. Now tree is complete, compute its properties and add
2164 ;; them to communication channel.
2165 (setq info
2166 (org-combine-plists
2167 info (org-export-collect-tree-properties tree info)))
2168 ;; 5. Eventually transcode TREE. Wrap the resulting string
2169 ;; into a template, if required. Eventually call
2170 ;; final-output filter.
2171 (let* ((body (org-element-normalize-string (org-export-data tree info)))
2172 (template (intern (format "org-%s-template" backend)))
2173 (output (org-export-filter-apply-functions
2174 (plist-get info :filter-final-output)
2175 (if (or (not (fboundp template)) body-only) body
2176 (funcall template body info))
2177 info)))
2178 ;; Maybe add final OUTPUT to kill ring, then return it.
2179 (when org-export-copy-to-kill-ring (org-kill-new output))
2180 output)))))
2182 (defun org-export-to-buffer
2183 (backend buffer &optional subtreep visible-only body-only ext-plist noexpand)
2184 "Call `org-export-as' with output to a specified buffer.
2186 BACKEND is the back-end used for transcoding, as a symbol.
2188 BUFFER is the output buffer. If it already exists, it will be
2189 erased first, otherwise, it will be created.
2191 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY, EXT-PLIST
2192 and NOEXPAND are similar to those used in `org-export-as', which
2193 see.
2195 Return buffer."
2196 (let ((out (org-export-as
2197 backend subtreep visible-only body-only ext-plist noexpand))
2198 (buffer (get-buffer-create buffer)))
2199 (with-current-buffer buffer
2200 (erase-buffer)
2201 (insert out)
2202 (goto-char (point-min)))
2203 buffer))
2205 (defun org-export-to-file
2206 (backend file &optional subtreep visible-only body-only ext-plist noexpand)
2207 "Call `org-export-as' with output to a specified file.
2209 BACKEND is the back-end used for transcoding, as a symbol. FILE
2210 is the name of the output file, as a string.
2212 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY, EXT-PLIST
2213 and NOEXPAND are similar to those used in `org-export-as', which
2214 see.
2216 Return output file's name."
2217 ;; Checks for FILE permissions. `write-file' would do the same, but
2218 ;; we'd rather avoid needless transcoding of parse tree.
2219 (unless (file-writable-p file) (error "Output file not writable"))
2220 ;; Insert contents to a temporary buffer and write it to FILE.
2221 (let ((out (org-export-as
2222 backend subtreep visible-only body-only ext-plist noexpand)))
2223 (with-temp-buffer
2224 (insert out)
2225 (let ((coding-system-for-write org-export-coding-system))
2226 (write-file file))))
2227 ;; Return full path.
2228 file)
2230 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
2231 "Return output file's name according to buffer specifications.
2233 EXTENSION is a string representing the output file extension,
2234 with the leading dot.
2236 With a non-nil optional argument SUBTREEP, try to determine
2237 output file's name by looking for \"EXPORT_FILE_NAME\" property
2238 of subtree at point.
2240 When optional argument PUB-DIR is set, use it as the publishing
2241 directory.
2243 Return file name as a string, or nil if it couldn't be
2244 determined."
2245 (let ((base-name
2246 ;; File name may come from EXPORT_FILE_NAME subtree property,
2247 ;; assuming point is at beginning of said sub-tree.
2248 (file-name-sans-extension
2249 (or (and subtreep
2250 (org-entry-get
2251 (save-excursion
2252 (ignore-errors
2253 (org-back-to-heading (not visible-only)) (point)))
2254 "EXPORT_FILE_NAME" t))
2255 ;; File name may be extracted from buffer's associated
2256 ;; file, if any.
2257 (buffer-file-name (buffer-base-buffer))
2258 ;; Can't determine file name on our own: Ask user.
2259 (let ((read-file-name-function
2260 (and org-completion-use-ido 'ido-read-file-name)))
2261 (read-file-name
2262 "Output file: " pub-dir nil nil nil
2263 (lambda (name)
2264 (string= (file-name-extension name t) extension))))))))
2265 ;; Build file name. Enforce EXTENSION over whatever user may have
2266 ;; come up with. PUB-DIR, if defined, always has precedence over
2267 ;; any provided path.
2268 (cond
2269 (pub-dir
2270 (concat (file-name-as-directory pub-dir)
2271 (file-name-nondirectory base-name)
2272 extension))
2273 ((string= (file-name-nondirectory base-name) base-name)
2274 (concat (file-name-as-directory ".") base-name extension))
2275 (t (concat base-name extension)))))
2277 (defmacro org-export-with-current-buffer-copy (&rest body)
2278 "Apply BODY in a copy of the current buffer.
2280 The copy preserves local variables and visibility of the original
2281 buffer.
2283 Point is at buffer's beginning when BODY is applied."
2284 (org-with-gensyms (original-buffer offset buffer-string overlays)
2285 `(let ((,original-buffer ,(current-buffer))
2286 (,offset ,(1- (point-min)))
2287 (,buffer-string ,(buffer-string))
2288 (,overlays (mapcar
2289 'copy-overlay (overlays-in (point-min) (point-max)))))
2290 (with-temp-buffer
2291 (let ((buffer-invisibility-spec nil))
2292 (org-clone-local-variables
2293 ,original-buffer
2294 "^\\(org-\\|orgtbl-\\|major-mode$\\|outline-\\(regexp\\|level\\)$\\)")
2295 (insert ,buffer-string)
2296 (mapc (lambda (ov)
2297 (move-overlay
2299 (- (overlay-start ov) ,offset)
2300 (- (overlay-end ov) ,offset)
2301 (current-buffer)))
2302 ,overlays)
2303 (goto-char (point-min))
2304 (progn ,@body))))))
2305 (def-edebug-spec org-export-with-current-buffer-copy (body))
2307 (defun org-export-expand-include-keyword (&optional included dir)
2308 "Expand every include keyword in buffer.
2309 Optional argument INCLUDED is a list of included file names along
2310 with their line restriction, when appropriate. It is used to
2311 avoid infinite recursion. Optional argument DIR is the current
2312 working directory. It is used to properly resolve relative
2313 paths."
2314 (let ((case-fold-search t))
2315 (goto-char (point-min))
2316 (while (re-search-forward "^[ \t]*#\\+INCLUDE: \\(.*\\)" nil t)
2317 (when (eq (org-element-type (save-match-data (org-element-at-point)))
2318 'keyword)
2319 (beginning-of-line)
2320 ;; Extract arguments from keyword's value.
2321 (let* ((value (match-string 1))
2322 (ind (org-get-indentation))
2323 (file (and (string-match "^\"\\(\\S-+\\)\"" value)
2324 (prog1 (expand-file-name (match-string 1 value) dir)
2325 (setq value (replace-match "" nil nil value)))))
2326 (lines
2327 (and (string-match
2328 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\"" value)
2329 (prog1 (match-string 1 value)
2330 (setq value (replace-match "" nil nil value)))))
2331 (env (cond ((string-match "\\<example\\>" value) 'example)
2332 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
2333 (match-string 1 value))))
2334 ;; Minimal level of included file defaults to the child
2335 ;; level of the current headline, if any, or one. It
2336 ;; only applies is the file is meant to be included as
2337 ;; an Org one.
2338 (minlevel
2339 (and (not env)
2340 (if (string-match ":minlevel +\\([0-9]+\\)" value)
2341 (prog1 (string-to-number (match-string 1 value))
2342 (setq value (replace-match "" nil nil value)))
2343 (let ((cur (org-current-level)))
2344 (if cur (1+ (org-reduced-level cur)) 1))))))
2345 ;; Remove keyword.
2346 (delete-region (point) (progn (forward-line) (point)))
2347 (cond
2348 ((not (file-readable-p file)) (error "Cannot include file %s" file))
2349 ;; Check if files has already been parsed. Look after
2350 ;; inclusion lines too, as different parts of the same file
2351 ;; can be included too.
2352 ((member (list file lines) included)
2353 (error "Recursive file inclusion: %s" file))
2355 (cond
2356 ((eq env 'example)
2357 (insert
2358 (let ((ind-str (make-string ind ? ))
2359 (contents
2360 ;; Protect sensitive contents with commas.
2361 (replace-regexp-in-string
2362 "\\(^\\)\\([*]\\|[ \t]*#\\+\\)" ","
2363 (org-export-prepare-file-contents file lines)
2364 nil nil 1)))
2365 (format "%s#+BEGIN_EXAMPLE\n%s%s#+END_EXAMPLE\n"
2366 ind-str contents ind-str))))
2367 ((stringp env)
2368 (insert
2369 (let ((ind-str (make-string ind ? ))
2370 (contents
2371 ;; Protect sensitive contents with commas.
2372 (replace-regexp-in-string
2373 (if (string= env "org") "\\(^\\)\\(.\\)"
2374 "\\(^\\)\\([*]\\|[ \t]*#\\+\\)") ","
2375 (org-export-prepare-file-contents file lines)
2376 nil nil 1)))
2377 (format "%s#+BEGIN_SRC %s\n%s%s#+END_SRC\n"
2378 ind-str env contents ind-str))))
2380 (insert
2381 (with-temp-buffer
2382 (org-mode)
2383 (insert
2384 (org-export-prepare-file-contents file lines ind minlevel))
2385 (org-export-expand-include-keyword
2386 (cons (list file lines) included)
2387 (file-name-directory file))
2388 (buffer-string))))))))))))
2390 (defun org-export-prepare-file-contents (file &optional lines ind minlevel)
2391 "Prepare the contents of FILE for inclusion and return them as a string.
2393 When optional argument LINES is a string specifying a range of
2394 lines, include only those lines.
2396 Optional argument IND, when non-nil, is an integer specifying the
2397 global indentation of returned contents. Since its purpose is to
2398 allow an included file to stay in the same environment it was
2399 created \(i.e. a list item), it doesn't apply past the first
2400 headline encountered.
2402 Optional argument MINLEVEL, when non-nil, is an integer
2403 specifying the level that any top-level headline in the included
2404 file should have."
2405 (with-temp-buffer
2406 (insert-file-contents file)
2407 (when lines
2408 (let* ((lines (split-string lines "-"))
2409 (lbeg (string-to-number (car lines)))
2410 (lend (string-to-number (cadr lines)))
2411 (beg (if (zerop lbeg) (point-min)
2412 (goto-char (point-min))
2413 (forward-line (1- lbeg))
2414 (point)))
2415 (end (if (zerop lend) (point-max)
2416 (goto-char (point-min))
2417 (forward-line (1- lend))
2418 (point))))
2419 (narrow-to-region beg end)))
2420 ;; Remove blank lines at beginning and end of contents. The logic
2421 ;; behind that removal is that blank lines around include keyword
2422 ;; override blank lines in included file.
2423 (goto-char (point-min))
2424 (org-skip-whitespace)
2425 (beginning-of-line)
2426 (delete-region (point-min) (point))
2427 (goto-char (point-max))
2428 (skip-chars-backward " \r\t\n")
2429 (forward-line)
2430 (delete-region (point) (point-max))
2431 ;; If IND is set, preserve indentation of include keyword until
2432 ;; the first headline encountered.
2433 (when ind
2434 (unless (eq major-mode 'org-mode) (org-mode))
2435 (goto-char (point-min))
2436 (let ((ind-str (make-string ind ? )))
2437 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
2438 ;; Do not move footnote definitions out of column 0.
2439 (unless (and (looking-at org-footnote-definition-re)
2440 (eq (org-element-type (org-element-at-point))
2441 'footnote-definition))
2442 (insert ind-str))
2443 (forward-line))))
2444 ;; When MINLEVEL is specified, compute minimal level for headlines
2445 ;; in the file (CUR-MIN), and remove stars to each headline so
2446 ;; that headlines with minimal level have a level of MINLEVEL.
2447 (when minlevel
2448 (unless (eq major-mode 'org-mode) (org-mode))
2449 (let ((levels (org-map-entries
2450 (lambda () (org-reduced-level (org-current-level))))))
2451 (when levels
2452 (let ((offset (- minlevel (apply 'min levels))))
2453 (unless (zerop offset)
2454 (when org-odd-levels-only (setq offset (* offset 2)))
2455 ;; Only change stars, don't bother moving whole
2456 ;; sections.
2457 (org-map-entries
2458 (lambda () (if (< offset 0) (delete-char (abs offset))
2459 (insert (make-string offset ?*))))))))))
2460 (buffer-string)))
2463 ;;; Tools For Back-Ends
2465 ;; A whole set of tools is available to help build new exporters. Any
2466 ;; function general enough to have its use across many back-ends
2467 ;; should be added here.
2469 ;; As of now, functions operating on footnotes, headlines, links,
2470 ;; macros, references, src-blocks, tables and tables of contents are
2471 ;; implemented.
2473 ;;;; For Export Snippets
2475 ;; Every export snippet is transmitted to the back-end. Though, the
2476 ;; latter will only retain one type of export-snippet, ignoring
2477 ;; others, based on the former's target back-end. The function
2478 ;; `org-export-snippet-backend' returns that back-end for a given
2479 ;; export-snippet.
2481 (defun org-export-snippet-backend (export-snippet)
2482 "Return EXPORT-SNIPPET targeted back-end as a symbol.
2483 Translation, with `org-export-snippet-translation-alist', is
2484 applied."
2485 (let ((back-end (org-element-property :back-end export-snippet)))
2486 (intern
2487 (or (cdr (assoc back-end org-export-snippet-translation-alist))
2488 back-end))))
2491 ;;;; For Footnotes
2493 ;; `org-export-collect-footnote-definitions' is a tool to list
2494 ;; actually used footnotes definitions in the whole parse tree, or in
2495 ;; an headline, in order to add footnote listings throughout the
2496 ;; transcoded data.
2498 ;; `org-export-footnote-first-reference-p' is a predicate used by some
2499 ;; back-ends, when they need to attach the footnote definition only to
2500 ;; the first occurrence of the corresponding label.
2502 ;; `org-export-get-footnote-definition' and
2503 ;; `org-export-get-footnote-number' provide easier access to
2504 ;; additional information relative to a footnote reference.
2506 (defun org-export-collect-footnote-definitions (data info)
2507 "Return an alist between footnote numbers, labels and definitions.
2509 DATA is the parse tree from which definitions are collected.
2510 INFO is the plist used as a communication channel.
2512 Definitions are sorted by order of references. They either
2513 appear as Org data (transcoded with `org-export-data') or as
2514 a secondary string for inlined footnotes (transcoded with
2515 `org-export-secondary-string'). Unreferenced definitions are
2516 ignored."
2517 (let (num-alist
2518 (collect-fn
2519 (function
2520 (lambda (data)
2521 ;; Collect footnote number, label and definition in DATA.
2522 (org-element-map
2523 data 'footnote-reference
2524 (lambda (fn)
2525 (when (org-export-footnote-first-reference-p fn info)
2526 (let ((def (org-export-get-footnote-definition fn info)))
2527 (push
2528 (list (org-export-get-footnote-number fn info)
2529 (org-element-property :label fn)
2530 def)
2531 num-alist)
2532 ;; Also search in definition for nested footnotes.
2533 (when (eq (org-element-property :type fn) 'standard)
2534 (funcall collect-fn def)))))
2535 ;; Don't enter footnote definitions since it will happen
2536 ;; when their first reference is found.
2537 info nil 'footnote-definition)))))
2538 (funcall collect-fn (plist-get info :parse-tree))
2539 (reverse num-alist)))
2541 (defun org-export-footnote-first-reference-p (footnote-reference info)
2542 "Non-nil when a footnote reference is the first one for its label.
2544 FOOTNOTE-REFERENCE is the footnote reference being considered.
2545 INFO is the plist used as a communication channel."
2546 (let ((label (org-element-property :label footnote-reference)))
2547 ;; Anonymous footnotes are always a first reference.
2548 (if (not label) t
2549 ;; Otherwise, return the first footnote with the same LABEL and
2550 ;; test if it is equal to FOOTNOTE-REFERENCE.
2551 (let ((search-refs
2552 (function
2553 (lambda (data)
2554 (org-element-map
2555 data 'footnote-reference
2556 (lambda (fn)
2557 (cond
2558 ((string= (org-element-property :label fn) label)
2559 (throw 'exit fn))
2560 ;; If FN isn't inlined, be sure to traverse its
2561 ;; definition before resuming search. See
2562 ;; comments in `org-export-get-footnote-number'
2563 ;; for more information.
2564 ((eq (org-element-property :type fn) 'standard)
2565 (funcall search-refs
2566 (org-export-get-footnote-definition fn info)))))
2567 ;; Don't enter footnote definitions since it will
2568 ;; happen when their first reference is found.
2569 info 'first-match 'footnote-definition)))))
2570 (equal (catch 'exit (funcall search-refs (plist-get info :parse-tree)))
2571 footnote-reference)))))
2573 (defun org-export-get-footnote-definition (footnote-reference info)
2574 "Return definition of FOOTNOTE-REFERENCE as parsed data.
2575 INFO is the plist used as a communication channel."
2576 (let ((label (org-element-property :label footnote-reference)))
2577 (or (org-element-property :inline-definition footnote-reference)
2578 (cdr (assoc label (plist-get info :footnote-definition-alist))))))
2580 (defun org-export-get-footnote-number (footnote info)
2581 "Return number associated to a footnote.
2583 FOOTNOTE is either a footnote reference or a footnote definition.
2584 INFO is the plist used as a communication channel."
2585 (let ((label (org-element-property :label footnote))
2586 seen-refs
2587 (search-ref
2588 (function
2589 (lambda (data)
2590 ;; Search footnote references through DATA, filling
2591 ;; SEEN-REFS along the way.
2592 (org-element-map
2593 data 'footnote-reference
2594 (lambda (fn)
2595 (let ((fn-lbl (org-element-property :label fn)))
2596 (cond
2597 ;; Anonymous footnote match: return number.
2598 ((and (not fn-lbl) (equal fn footnote))
2599 (throw 'exit (1+ (length seen-refs))))
2600 ;; Labels match: return number.
2601 ((and label (string= label fn-lbl))
2602 (throw 'exit (1+ (length seen-refs))))
2603 ;; Anonymous footnote: it's always a new one. Also,
2604 ;; be sure to return nil from the `cond' so
2605 ;; `first-match' doesn't get us out of the loop.
2606 ((not fn-lbl) (push 'inline seen-refs) nil)
2607 ;; Label not seen so far: add it so SEEN-REFS.
2609 ;; Also search for subsequent references in footnote
2610 ;; definition so numbering following reading logic.
2611 ;; Note that we don't have to care about inline
2612 ;; definitions, since `org-element-map' already
2613 ;; traverse them at the right time.
2615 ;; Once again, return nil to stay in the loop.
2616 ((not (member fn-lbl seen-refs))
2617 (push fn-lbl seen-refs)
2618 (funcall search-ref
2619 (org-export-get-footnote-definition fn info))
2620 nil))))
2621 ;; Don't enter footnote definitions since it will happen
2622 ;; when their first reference is found.
2623 info 'first-match 'footnote-definition)))))
2624 (catch 'exit (funcall search-ref (plist-get info :parse-tree)))))
2627 ;;;; For Headlines
2629 ;; `org-export-get-relative-level' is a shortcut to get headline
2630 ;; level, relatively to the lower headline level in the parsed tree.
2632 ;; `org-export-get-headline-number' returns the section number of an
2633 ;; headline, while `org-export-number-to-roman' allows to convert it
2634 ;; to roman numbers.
2636 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
2637 ;; `org-export-last-sibling-p' are three useful predicates when it
2638 ;; comes to fulfill the `:headline-levels' property.
2640 (defun org-export-get-relative-level (headline info)
2641 "Return HEADLINE relative level within current parsed tree.
2642 INFO is a plist holding contextual information."
2643 (+ (org-element-property :level headline)
2644 (or (plist-get info :headline-offset) 0)))
2646 (defun org-export-low-level-p (headline info)
2647 "Non-nil when HEADLINE is considered as low level.
2649 INFO is a plist used as a communication channel.
2651 A low level headlines has a relative level greater than
2652 `:headline-levels' property value.
2654 Return value is the difference between HEADLINE relative level
2655 and the last level being considered as high enough, or nil."
2656 (let ((limit (plist-get info :headline-levels)))
2657 (when (wholenump limit)
2658 (let ((level (org-export-get-relative-level headline info)))
2659 (and (> level limit) (- level limit))))))
2661 (defun org-export-get-headline-number (headline info)
2662 "Return HEADLINE numbering as a list of numbers.
2663 INFO is a plist holding contextual information."
2664 (cdr (assoc headline (plist-get info :headline-numbering))))
2666 (defun org-export-numbered-headline-p (headline info)
2667 "Return a non-nil value if HEADLINE element should be numbered.
2668 INFO is a plist used as a communication channel."
2669 (let ((sec-num (plist-get info :section-numbers))
2670 (level (org-export-get-relative-level headline info)))
2671 (if (wholenump sec-num) (<= level sec-num) sec-num)))
2673 (defun org-export-number-to-roman (n)
2674 "Convert integer N into a roman numeral."
2675 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
2676 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
2677 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
2678 ( 1 . "I")))
2679 (res ""))
2680 (if (<= n 0)
2681 (number-to-string n)
2682 (while roman
2683 (if (>= n (caar roman))
2684 (setq n (- n (caar roman))
2685 res (concat res (cdar roman)))
2686 (pop roman)))
2687 res)))
2689 (defun org-export-first-sibling-p (headline info)
2690 "Non-nil when HEADLINE is the first sibling in its sub-tree.
2691 INFO is the plist used as a communication channel."
2692 (not (eq (org-element-type (org-export-get-previous-element headline info))
2693 'headline)))
2695 (defun org-export-last-sibling-p (headline info)
2696 "Non-nil when HEADLINE is the last sibling in its sub-tree.
2697 INFO is the plist used as a communication channel."
2698 (not (org-export-get-next-element headline info)))
2701 ;;;; For Links
2703 ;; `org-export-solidify-link-text' turns a string into a safer version
2704 ;; for links, replacing most non-standard characters with hyphens.
2706 ;; `org-export-get-coderef-format' returns an appropriate format
2707 ;; string for coderefs.
2709 ;; `org-export-inline-image-p' returns a non-nil value when the link
2710 ;; provided should be considered as an inline image.
2712 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
2713 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
2714 ;; returns an appropriate unique identifier when found, or nil.
2716 ;; `org-export-resolve-id-link' returns the first headline with
2717 ;; specified id or custom-id in parse tree, or nil when none was
2718 ;; found.
2720 ;; `org-export-resolve-coderef' associates a reference to a line
2721 ;; number in the element it belongs, or returns the reference itself
2722 ;; when the element isn't numbered.
2724 (defun org-export-solidify-link-text (s)
2725 "Take link text S and make a safe target out of it."
2726 (save-match-data
2727 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-]+") "-")))
2729 (defun org-export-get-coderef-format (path desc)
2730 "Return format string for code reference link.
2731 PATH is the link path. DESC is its description."
2732 (save-match-data
2733 (cond ((not desc) "%s")
2734 ((string-match (regexp-quote (concat "(" path ")")) desc)
2735 (replace-match "%s" t t desc))
2736 (t desc))))
2738 (defun org-export-inline-image-p (link &optional rules)
2739 "Non-nil if LINK object points to an inline image.
2741 Optional argument is a set of RULES defining inline images. It
2742 is an alist where associations have the following shape:
2744 \(TYPE . REGEXP)
2746 Applying a rule means apply REGEXP against LINK's path when its
2747 type is TYPE. The function will return a non-nil value if any of
2748 the provided rules is non-nil. The default rule is
2749 `org-export-default-inline-image-rule'.
2751 This only applies to links without a description."
2752 (and (not (org-element-contents link))
2753 (let ((case-fold-search t)
2754 (rules (or rules org-export-default-inline-image-rule)))
2755 (some
2756 (lambda (rule)
2757 (and (string= (org-element-property :type link) (car rule))
2758 (string-match (cdr rule)
2759 (org-element-property :path link))))
2760 rules))))
2762 (defun org-export-resolve-fuzzy-link (link info)
2763 "Return LINK destination.
2765 INFO is a plist holding contextual information.
2767 Return value can be an object, an element, or nil:
2769 - If LINK path matches a target object (i.e. <<path>>) or
2770 element (i.e. \"#+TARGET: path\"), return it.
2772 - If LINK path exactly matches the name affiliated keyword
2773 \(i.e. #+NAME: path) of an element, return that element.
2775 - If LINK path exactly matches any headline name, return that
2776 element. If more than one headline share that name, priority
2777 will be given to the one with the closest common ancestor, if
2778 any, or the first one in the parse tree otherwise.
2780 - Otherwise, return nil.
2782 Assume LINK type is \"fuzzy\"."
2783 (let ((path (org-element-property :path link)))
2784 (cond
2785 ;; First try to find a matching "<<path>>" unless user specified
2786 ;; he was looking for an headline (path starts with a *
2787 ;; character).
2788 ((and (not (eq (substring path 0 1) ?*))
2789 (loop for target in (plist-get info :target-list)
2790 when (string= (org-element-property :value target) path)
2791 return target)))
2792 ;; Then try to find an element with a matching "#+NAME: path"
2793 ;; affiliated keyword.
2794 ((and (not (eq (substring path 0 1) ?*))
2795 (org-element-map
2796 (plist-get info :parse-tree) org-element-all-elements
2797 (lambda (el)
2798 (when (string= (org-element-property :name el) path) el))
2799 info 'first-match)))
2800 ;; Last case: link either points to an headline or to
2801 ;; nothingness. Try to find the source, with priority given to
2802 ;; headlines with the closest common ancestor. If such candidate
2803 ;; is found, return its beginning position as an unique
2804 ;; identifier, otherwise return nil.
2806 (let ((find-headline
2807 (function
2808 ;; Return first headline whose `:raw-value' property
2809 ;; is NAME in parse tree DATA, or nil.
2810 (lambda (name data)
2811 (org-element-map
2812 data 'headline
2813 (lambda (headline)
2814 (when (string=
2815 (org-element-property :raw-value headline)
2816 name)
2817 headline))
2818 info 'first-match)))))
2819 ;; Search among headlines sharing an ancestor with link,
2820 ;; from closest to farthest.
2821 (or (catch 'exit
2822 (mapc
2823 (lambda (parent)
2824 (when (eq (org-element-type parent) 'headline)
2825 (let ((foundp (funcall find-headline path parent)))
2826 (when foundp (throw 'exit foundp)))))
2827 (org-export-get-genealogy link info)) nil)
2828 ;; No match with a common ancestor: try the full parse-tree.
2829 (funcall find-headline path (plist-get info :parse-tree))))))))
2831 (defun org-export-resolve-id-link (link info)
2832 "Return headline referenced as LINK destination.
2834 INFO is a plist used as a communication channel.
2836 Return value can be an headline element or nil. Assume LINK type
2837 is either \"id\" or \"custom-id\"."
2838 (let ((id (org-element-property :path link)))
2839 (org-element-map
2840 (plist-get info :parse-tree) 'headline
2841 (lambda (headline)
2842 (when (or (string= (org-element-property :id headline) id)
2843 (string= (org-element-property :custom-id headline) id))
2844 headline))
2845 info 'first-match)))
2847 (defun org-export-resolve-coderef (ref info)
2848 "Resolve a code reference REF.
2850 INFO is a plist used as a communication channel.
2852 Return associated line number in source code, or REF itself,
2853 depending on src-block or example element's switches."
2854 (org-element-map
2855 (plist-get info :parse-tree) '(example-block src-block)
2856 (lambda (el)
2857 (with-temp-buffer
2858 (insert (org-trim (org-element-property :value el)))
2859 (let* ((label-fmt (regexp-quote
2860 (or (org-element-property :label-fmt el)
2861 org-coderef-label-format)))
2862 (ref-re
2863 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
2864 (replace-regexp-in-string "%s" ref label-fmt nil t))))
2865 ;; Element containing REF is found. Resolve it to either
2866 ;; a label or a line number, as needed.
2867 (when (re-search-backward ref-re nil t)
2868 (cond
2869 ((org-element-property :use-labels el) ref)
2870 ((eq (org-element-property :number-lines el) 'continued)
2871 (+ (org-export-get-loc el info) (line-number-at-pos)))
2872 (t (line-number-at-pos)))))))
2873 info 'first-match))
2876 ;;;; For Macros
2878 ;; `org-export-expand-macro' simply takes care of expanding macros.
2880 (defun org-export-expand-macro (macro info)
2881 "Expand MACRO and return it as a string.
2882 INFO is a plist holding export options."
2883 (let* ((key (org-element-property :key macro))
2884 (args (org-element-property :args macro))
2885 ;; User's macros are stored in the communication channel with
2886 ;; a ":macro-" prefix. If it's a string leave it as-is.
2887 ;; Otherwise, it's a secondary string that needs to be
2888 ;; expanded recursively.
2889 (value
2890 (let ((val (plist-get info (intern (format ":macro-%s" key)))))
2891 (if (stringp val) val (org-export-secondary-string val info)))))
2892 ;; Replace arguments in VALUE.
2893 (let ((s 0) n)
2894 (while (string-match "\\$\\([0-9]+\\)" value s)
2895 (setq s (1+ (match-beginning 0))
2896 n (string-to-number (match-string 1 value)))
2897 (and (>= (length args) n)
2898 (setq value (replace-match (nth (1- n) args) t t value)))))
2899 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
2900 (when (string-match "\\`(eval\\>" value)
2901 (setq value (eval (read value))))
2902 ;; Return string.
2903 (format "%s" (or value ""))))
2906 ;;;; For References
2908 ;; `org-export-get-ordinal' associates a sequence number to any object
2909 ;; or element.
2911 (defun org-export-get-ordinal (element info &optional types predicate)
2912 "Return ordinal number of an element or object.
2914 ELEMENT is the element or object considered. INFO is the plist
2915 used as a communication channel.
2917 Optional argument TYPES, when non-nil, is a list of element or
2918 object types, as symbols, that should also be counted in.
2919 Otherwise, only provided element's type is considered.
2921 Optional argument PREDICATE is a function returning a non-nil
2922 value if the current element or object should be counted in. It
2923 accepts two arguments: the element or object being considered and
2924 the plist used as a communication channel. This allows to count
2925 only a certain type of objects (i.e. inline images).
2927 Return value is a list of numbers if ELEMENT is an headline or an
2928 item. It is nil for keywords. It represents the footnote number
2929 for footnote definitions and footnote references. If ELEMENT is
2930 a target, return the same value as if ELEMENT was the closest
2931 table, item or headline containing the target. In any other
2932 case, return the sequence number of ELEMENT among elements or
2933 objects of the same type."
2934 ;; A target keyword, representing an invisible target, never has
2935 ;; a sequence number.
2936 (unless (eq (org-element-type element) 'keyword)
2937 ;; Ordinal of a target object refer to the ordinal of the closest
2938 ;; table, item, or headline containing the object.
2939 (when (eq (org-element-type element) 'target)
2940 (setq element
2941 (loop for parent in (org-export-get-genealogy element info)
2942 when
2943 (memq
2944 (org-element-type parent)
2945 '(footnote-definition footnote-reference headline item
2946 table))
2947 return parent)))
2948 (case (org-element-type element)
2949 ;; Special case 1: An headline returns its number as a list.
2950 (headline (org-export-get-headline-number element info))
2951 ;; Special case 2: An item returns its number as a list.
2952 (item (let ((struct (org-element-property :structure element)))
2953 (org-list-get-item-number
2954 (org-element-property :begin element)
2955 struct
2956 (org-list-prevs-alist struct)
2957 (org-list-parents-alist struct))))
2958 ((footnote definition footnote-reference)
2959 (org-export-get-footnote-number element info))
2960 (otherwise
2961 (let ((counter 0))
2962 ;; Increment counter until ELEMENT is found again.
2963 (org-element-map
2964 (plist-get info :parse-tree) (or types (org-element-type element))
2965 (lambda (el)
2966 (cond
2967 ((equal element el) (1+ counter))
2968 ((not predicate) (incf counter) nil)
2969 ((funcall predicate el info) (incf counter) nil)))
2970 info 'first-match))))))
2973 ;;;; For Src-Blocks
2975 ;; `org-export-get-loc' counts number of code lines accumulated in
2976 ;; src-block or example-block elements with a "+n" switch until
2977 ;; a given element, excluded. Note: "-n" switches reset that count.
2979 ;; `org-export-unravel-code' extracts source code (along with a code
2980 ;; references alist) from an `element-block' or `src-block' type
2981 ;; element.
2983 ;; `org-export-format-code' applies a formatting function to each line
2984 ;; of code, providing relative line number and code reference when
2985 ;; appropriate. Since it doesn't access the original element from
2986 ;; which the source code is coming, it expects from the code calling
2987 ;; it to know if lines should be numbered and if code references
2988 ;; should appear.
2990 ;; Eventually, `org-export-format-code-default' is a higher-level
2991 ;; function (it makes use of the two previous functions) which handles
2992 ;; line numbering and code references inclusion, and returns source
2993 ;; code in a format suitable for plain text or verbatim output.
2995 (defun org-export-get-loc (element info)
2996 "Return accumulated lines of code up to ELEMENT.
2998 INFO is the plist used as a communication channel.
3000 ELEMENT is excluded from count."
3001 (let ((loc 0))
3002 (org-element-map
3003 (plist-get info :parse-tree)
3004 `(src-block example-block ,(org-element-type element))
3005 (lambda (el)
3006 (cond
3007 ;; ELEMENT is reached: Quit the loop.
3008 ((equal el element) t)
3009 ;; Only count lines from src-block and example-block elements
3010 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
3011 ((not (memq (org-element-type el) '(src-block example-block))) nil)
3012 ((let ((linums (org-element-property :number-lines el)))
3013 (when linums
3014 ;; Accumulate locs or reset them.
3015 (let ((lines (org-count-lines
3016 (org-trim (org-element-property :value el)))))
3017 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
3018 ;; Return nil to stay in the loop.
3019 nil)))
3020 info 'first-match)
3021 ;; Return value.
3022 loc))
3024 (defun org-export-unravel-code (element)
3025 "Clean source code and extract references out of it.
3027 ELEMENT has either a `src-block' an `example-block' type.
3029 Return a cons cell whose CAR is the source code, cleaned from any
3030 reference and protective comma and CDR is an alist between
3031 relative line number (integer) and name of code reference on that
3032 line (string)."
3033 (let* ((line 0) refs
3034 ;; Get code and clean it. Remove blank lines at its
3035 ;; beginning and end. Also remove protective commas.
3036 (code (let ((c (replace-regexp-in-string
3037 "\\`\\([ \t]*\n\\)+" ""
3038 (replace-regexp-in-string
3039 "\\(:?[ \t]*\n\\)*[ \t]*\\'" "\n"
3040 (org-element-property :value element)))))
3041 ;; If appropriate, remove global indentation.
3042 (unless (or org-src-preserve-indentation
3043 (org-element-property :preserve-indent element))
3044 (setq c (org-remove-indentation c)))
3045 ;; Free up the protected lines. Note: Org blocks
3046 ;; have commas at the beginning or every line.
3047 (if (string= (org-element-property :language element) "org")
3048 (replace-regexp-in-string "^," "" c)
3049 (replace-regexp-in-string
3050 "^\\(,\\)\\(:?\\*\\|[ \t]*#\\+\\)" "" c nil nil 1))))
3051 ;; Get format used for references.
3052 (label-fmt (regexp-quote
3053 (or (org-element-property :label-fmt element)
3054 org-coderef-label-format)))
3055 ;; Build a regexp matching a loc with a reference.
3056 (with-ref-re
3057 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
3058 (replace-regexp-in-string
3059 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
3060 ;; Return value.
3061 (cons
3062 ;; Code with references removed.
3063 (org-element-normalize-string
3064 (mapconcat
3065 (lambda (loc)
3066 (incf line)
3067 (if (not (string-match with-ref-re loc)) loc
3068 ;; Ref line: remove ref, and signal its position in REFS.
3069 (push (cons line (match-string 3 loc)) refs)
3070 (replace-match "" nil nil loc 1)))
3071 (org-split-string code "\n") "\n"))
3072 ;; Reference alist.
3073 refs)))
3075 (defun org-export-format-code (code fun &optional num-lines ref-alist)
3076 "Format CODE by applying FUN line-wise and return it.
3078 CODE is a string representing the code to format. FUN is
3079 a function. It must accept three arguments: a line of
3080 code (string), the current line number (integer) or nil and the
3081 reference associated to the current line (string) or nil.
3083 Optional argument NUM-LINES can be an integer representing the
3084 number of code lines accumulated until the current code. Line
3085 numbers passed to FUN will take it into account. If it is nil,
3086 FUN's second argument will always be nil. This number can be
3087 obtained with `org-export-get-loc' function.
3089 Optional argument REF-ALIST can be an alist between relative line
3090 number (i.e. ignoring NUM-LINES) and the name of the code
3091 reference on it. If it is nil, FUN's third argument will always
3092 be nil. It can be obtained through the use of
3093 `org-export-unravel-code' function."
3094 (let ((--locs (org-split-string code "\n"))
3095 (--line 0))
3096 (org-element-normalize-string
3097 (mapconcat
3098 (lambda (--loc)
3099 (incf --line)
3100 (let ((--ref (cdr (assq --line ref-alist))))
3101 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
3102 --locs "\n"))))
3104 (defun org-export-format-code-default (element info)
3105 "Return source code from ELEMENT, formatted in a standard way.
3107 ELEMENT is either a `src-block' or `example-block' element. INFO
3108 is a plist used as a communication channel.
3110 This function takes care of line numbering and code references
3111 inclusion. Line numbers, when applicable, appear at the
3112 beginning of the line, separated from the code by two white
3113 spaces. Code references, on the other hand, appear flushed to
3114 the right, separated by six white spaces from the widest line of
3115 code."
3116 ;; Extract code and references.
3117 (let* ((code-info (org-export-unravel-code element))
3118 (code (car code-info))
3119 (code-lines (org-split-string code "\n"))
3120 (refs (and (org-element-property :retain-labels element)
3121 (cdr code-info)))
3122 ;; Handle line numbering.
3123 (num-start (case (org-element-property :number-lines element)
3124 (continued (org-export-get-loc element info))
3125 (new 0)))
3126 (num-fmt
3127 (and num-start
3128 (format "%%%ds "
3129 (length (number-to-string
3130 (+ (length code-lines) num-start))))))
3131 ;; Prepare references display, if required. Any reference
3132 ;; should start six columns after the widest line of code,
3133 ;; wrapped with parenthesis.
3134 (max-width
3135 (+ (apply 'max (mapcar 'length code-lines))
3136 (if (not num-start) 0 (length (format num-fmt num-start))))))
3137 (org-export-format-code
3138 code
3139 (lambda (loc line-num ref)
3140 (let ((number-str (and num-fmt (format num-fmt line-num))))
3141 (concat
3142 number-str
3144 (and ref
3145 (concat (make-string
3146 (- (+ 6 max-width)
3147 (+ (length loc) (length number-str))) ? )
3148 (format "(%s)" ref))))))
3149 num-start refs)))
3152 ;;;; For Tables
3154 ;; `org-export-table-has-special-column-p' and
3155 ;; `org-export-table-row-is-special-p' are predicates used to look for
3156 ;; meta-information about the table structure.
3158 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
3159 ;; and `org-export-table-cell-borders' extract information from
3160 ;; a table-cell element.
3162 ;; `org-export-table-dimensions' gives the number on rows and columns
3163 ;; in the table, ignoring horizontal rules and special columns.
3164 ;; `org-export-table-cell-address', given a table-cell object, returns
3165 ;; the absolute address of a cell. On the other hand,
3166 ;; `org-export-get-table-cell-at' does the contrary.
3168 (defun org-export-table-has-special-column-p (table)
3169 "Non-nil when TABLE has a special column.
3170 All special columns will be ignored during export."
3171 ;; The table has a special column when every first cell of every row
3172 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
3173 ;; "*" "_" and "^". Though, do not consider a first row containing
3174 ;; only empty cells as special.
3175 (let ((special-column-p 'empty))
3176 (catch 'exit
3177 (mapc
3178 (lambda (row)
3179 (when (eq (org-element-property :type row) 'standard)
3180 (let ((value (org-element-contents
3181 (car (org-element-contents row)))))
3182 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
3183 (setq special-column-p 'special))
3184 ((not value))
3185 (t (throw 'exit nil))))))
3186 (org-element-contents table))
3187 (eq special-column-p 'special))))
3189 (defun org-export-table-has-header-p (table info)
3190 "Non-nil when TABLE has an header.
3192 INFO is a plist used as a communication channel.
3194 A table has an header when it contains at least two row groups."
3195 (let ((rowgroup 1) row-flag)
3196 (org-element-map
3197 table 'table-row
3198 (lambda (row)
3199 (cond
3200 ((> rowgroup 1) t)
3201 ((and row-flag (eq (org-element-property :type row) 'rule))
3202 (incf rowgroup) (setq row-flag nil))
3203 ((and (not row-flag) (eq (org-element-property :type row) 'standard))
3204 (setq row-flag t) nil)))
3205 info)))
3207 (defun org-export-table-row-is-special-p (table-row info)
3208 "Non-nil if TABLE-ROW is considered special.
3210 INFO is a plist used as the communication channel.
3212 All special rows will be ignored during export."
3213 (when (eq (org-element-property :type table-row) 'standard)
3214 (let ((first-cell (org-element-contents
3215 (car (org-element-contents table-row)))))
3216 ;; A row is special either when...
3218 ;; ... it starts with a field only containing "/",
3219 (equal first-cell '("/"))
3220 ;; ... the table contains a special column and the row start
3221 ;; with a marking character among, "^", "_", "$" or "!",
3222 (and (org-export-table-has-special-column-p
3223 (org-export-get-parent table-row info))
3224 (member first-cell '(("^") ("_") ("$") ("!"))))
3225 ;; ... it contains only alignment cookies and empty cells.
3226 (let ((special-row-p 'empty))
3227 (catch 'exit
3228 (mapc
3229 (lambda (cell)
3230 (let ((value (org-element-contents cell)))
3231 (cond ((not value))
3232 ((and (not (cdr value))
3233 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
3234 (car value)))
3235 (setq special-row-p 'cookie))
3236 (t (throw 'exit nil)))))
3237 (org-element-contents table-row))
3238 (eq special-row-p 'cookie)))))))
3240 (defun org-export-table-row-group (table-row info)
3241 "Return TABLE-ROW's group.
3243 INFO is a plist used as the communication channel.
3245 Return value is the group number, as an integer, or nil special
3246 rows and table rules. Group 1 is also table's header."
3247 (unless (or (eq (org-element-property :type table-row) 'rule)
3248 (org-export-table-row-is-special-p table-row info))
3249 (let ((group 0) row-flag)
3250 (catch 'found
3251 (mapc
3252 (lambda (row)
3253 (cond
3254 ((and (eq (org-element-property :type row) 'standard)
3255 (not (org-export-table-row-is-special-p row info)))
3256 (unless row-flag (incf group) (setq row-flag t)))
3257 ((eq (org-element-property :type row) 'rule)
3258 (setq row-flag nil)))
3259 (when (equal table-row row) (throw 'found group)))
3260 (org-element-contents (org-export-get-parent table-row info)))))))
3262 (defun org-export-table-cell-width (table-cell info)
3263 "Return TABLE-CELL contents width.
3265 INFO is a plist used as the communication channel.
3267 Return value is the width given by the last width cookie in the
3268 same column as TABLE-CELL, or nil."
3269 (let* ((genealogy (org-export-get-genealogy table-cell info))
3270 (row (car genealogy))
3271 (column (let ((cells (org-element-contents row)))
3272 (- (length cells) (length (member table-cell cells)))))
3273 (table (nth 1 genealogy))
3274 cookie-width)
3275 (mapc
3276 (lambda (row)
3277 (cond
3278 ;; In a special row, try to find a width cookie at COLUMN.
3279 ((org-export-table-row-is-special-p row info)
3280 (let ((value (org-element-contents
3281 (elt (org-element-contents row) column))))
3282 (cond
3283 ((not value))
3284 ((and (not (cdr value))
3285 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" (car value))
3286 (match-string 1 (car value)))
3287 (setq cookie-width
3288 (string-to-number (match-string 1 (car value))))))))
3289 ;; Ignore table rules.
3290 ((eq (org-element-property :type row) 'rule))))
3291 (org-element-contents table))
3292 ;; Return value.
3293 cookie-width))
3295 (defun org-export-table-cell-alignment (table-cell info)
3296 "Return TABLE-CELL contents alignment.
3298 INFO is a plist used as the communication channel.
3300 Return alignment as specified by the last alignment cookie in the
3301 same column as TABLE-CELL. If no such cookie is found, a default
3302 alignment value will be deduced from fraction of numbers in the
3303 column (see `org-table-number-fraction' for more information).
3304 Possible values are `left', `right' and `center'."
3305 (let* ((genealogy (org-export-get-genealogy table-cell info))
3306 (row (car genealogy))
3307 (column (let ((cells (org-element-contents row)))
3308 (- (length cells) (length (member table-cell cells)))))
3309 (table (nth 1 genealogy))
3310 (number-cells 0)
3311 (total-cells 0)
3312 cookie-align)
3313 (mapc
3314 (lambda (row)
3315 (cond
3316 ;; In a special row, try to find an alignment cookie at
3317 ;; COLUMN.
3318 ((org-export-table-row-is-special-p row info)
3319 (let ((value (org-element-contents
3320 (elt (org-element-contents row) column))))
3321 (cond
3322 ((not value))
3323 ((and (not (cdr value))
3324 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
3325 (car value))
3326 (match-string 1 (car value)))
3327 (setq cookie-align (match-string 1 (car value)))))))
3328 ;; Ignore table rules.
3329 ((eq (org-element-property :type row) 'rule))
3330 ;; In a standard row, check if cell's contents are expressing
3331 ;; some kind of number. Increase NUMBER-CELLS accordingly.
3332 ;; Though, don't bother if an alignment cookie has already
3333 ;; defined cell's alignment.
3334 ((not cookie-align)
3335 (let ((value (org-element-interpret-secondary
3336 (org-element-contents
3337 (elt (org-element-contents row) column)))))
3338 (incf total-cells)
3339 (when (string-match org-table-number-regexp value)
3340 (incf number-cells))))))
3341 (org-element-contents table))
3342 ;; Return value. Alignment specified by cookies has precedence
3343 ;; over alignment deduced from cells contents.
3344 (cond ((equal cookie-align "l") 'left)
3345 ((equal cookie-align "r") 'right)
3346 ((equal cookie-align "c") 'center)
3347 ((>= (/ (float number-cells) total-cells) org-table-number-fraction)
3348 'right)
3349 (t 'left))))
3351 (defun org-export-table-cell-borders (table-cell info)
3352 "Return TABLE-CELL borders.
3354 INFO is a plist used as a communication channel.
3356 Return value is a list of symbols, or nil. Possible values are:
3357 `top', `bottom', `above', `below', `left' and `right'. Note:
3358 `top' (resp. `bottom') only happen for a cell in the first
3359 row (resp. last row) of the table, ignoring table rules, if any.
3361 Returned borders ignore special rows."
3362 (let* ((genealogy (org-export-get-genealogy table-cell info))
3363 (row (car genealogy))
3364 (table (nth 1 genealogy))
3365 borders)
3366 ;; Top/above border? TABLE-CELL has a border above when a rule
3367 ;; used to demarcate row groups can be found above. Hence,
3368 ;; finding a rule isn't sufficient to push `above' in BORDERS:
3369 ;; another regular row has to be found above that rule.
3370 (let (rule-flag)
3371 (catch 'exit
3372 (mapc (lambda (row)
3373 (cond ((eq (org-element-property :type row) 'rule)
3374 (setq rule-flag t))
3375 ((not (org-export-table-row-is-special-p row info))
3376 (if rule-flag (throw 'exit (push 'above borders))
3377 (throw 'exit nil)))))
3378 ;; Look at every row before the current one.
3379 (cdr (member row (reverse (org-element-contents table)))))
3380 ;; No rule above, or rule found starts the table (ignoring any
3381 ;; special row): TABLE-CELL is at the top of the table.
3382 (when rule-flag (push 'above borders))
3383 (push 'top borders)))
3384 ;; Bottom/below border? TABLE-CELL has a border below when next
3385 ;; non-regular row below is a rule.
3386 (let (rule-flag)
3387 (catch 'exit
3388 (mapc (lambda (row)
3389 (cond ((eq (org-element-property :type row) 'rule)
3390 (setq rule-flag t))
3391 ((not (org-export-table-row-is-special-p row info))
3392 (if rule-flag (throw 'exit (push 'below borders))
3393 (throw 'exit nil)))))
3394 ;; Look at every row after the current one.
3395 (cdr (member row (org-element-contents table))))
3396 ;; No rule below, or rule found ends the table (modulo some
3397 ;; special row): TABLE-CELL is at the bottom of the table.
3398 (when rule-flag (push 'below borders))
3399 (push 'bottom borders)))
3400 ;; Right/left borders? They can only be specified by column
3401 ;; groups. Column groups are defined in a row starting with "/".
3402 ;; Also a column groups row only contains "<", "<>", ">" or blank
3403 ;; cells.
3404 (catch 'exit
3405 (let ((column (let ((cells (org-element-contents row)))
3406 (- (length cells) (length (member table-cell cells))))))
3407 (mapc
3408 (lambda (row)
3409 (unless (eq (org-element-property :type row) 'rule)
3410 (when (equal (org-element-contents
3411 (car (org-element-contents row)))
3412 '("/"))
3413 (let ((column-groups
3414 (mapcar
3415 (lambda (cell)
3416 (let ((value (org-element-contents cell)))
3417 (when (member value '(("<") ("<>") (">") nil))
3418 (car value))))
3419 (org-element-contents row))))
3420 ;; There's a left border when previous cell, if
3421 ;; any, ends a group, or current one starts one.
3422 (when (or (and (not (zerop column))
3423 (member (elt column-groups (1- column))
3424 '(">" "<>")))
3425 (member (elt column-groups column) '("<" "<>")))
3426 (push 'left borders))
3427 ;; There's a right border when next cell, if any,
3428 ;; starts a group, or current one ends one.
3429 (when (or (and (/= (1+ column) (length column-groups))
3430 (member (elt column-groups (1+ column))
3431 '("<" "<>")))
3432 (member (elt column-groups column) '(">" "<>")))
3433 (push 'right borders))
3434 (throw 'exit nil)))))
3435 ;; Table rows are read in reverse order so last column groups
3436 ;; row has precedence over any previous one.
3437 (reverse (org-element-contents table)))))
3438 ;; Return value.
3439 borders))
3441 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
3442 "Non-nil when TABLE-CELL is at the beginning of a row group.
3443 INFO is a plist used as a communication channel."
3444 ;; A cell starts a column group either when it is at the beginning
3445 ;; of a row (or after the special column, if any) or when it has
3446 ;; a left border.
3447 (or (equal (org-element-map
3448 (org-export-get-parent table-cell info)
3449 'table-cell 'identity info 'first-match)
3450 table-cell)
3451 (memq 'left (org-export-table-cell-borders table-cell info))))
3453 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
3454 "Non-nil when TABLE-CELL is at the end of a row group.
3455 INFO is a plist used as a communication channel."
3456 ;; A cell ends a column group either when it is at the end of a row
3457 ;; or when it has a right border.
3458 (or (equal (car (last (org-element-contents
3459 (org-export-get-parent table-cell info))))
3460 table-cell)
3461 (memq 'right (org-export-table-cell-borders table-cell info))))
3463 (defun org-export-table-row-starts-rowgroup-p (table-row info)
3464 "Non-nil when TABLE-ROW is at the beginning of a column group.
3465 INFO is a plist used as a communication channel."
3466 (unless (or (eq (org-element-property :type table-row) 'rule)
3467 (org-export-table-row-is-special-p table-row info))
3468 (let ((borders (org-export-table-cell-borders
3469 (car (org-element-contents table-row)) info)))
3470 (or (memq 'top borders) (memq 'above borders)))))
3472 (defun org-export-table-row-ends-rowgroup-p (table-row info)
3473 "Non-nil when TABLE-ROW is at the end of a column group.
3474 INFO is a plist used as a communication channel."
3475 (unless (or (eq (org-element-property :type table-row) 'rule)
3476 (org-export-table-row-is-special-p table-row info))
3477 (let ((borders (org-export-table-cell-borders
3478 (car (org-element-contents table-row)) info)))
3479 (or (memq 'bottom borders) (memq 'below borders)))))
3481 (defun org-export-table-row-starts-header-p (table-row info)
3482 "Non-nil when TABLE-ROW is the first table header's row.
3483 INFO is a plist used as a communication channel."
3484 (and (org-export-table-has-header-p
3485 (org-export-get-parent-table table-row info) info)
3486 (org-export-table-row-starts-rowgroup-p table-row info)
3487 (= (org-export-table-row-group table-row info) 1)))
3489 (defun org-export-table-row-ends-header-p (table-row info)
3490 "Non-nil when TABLE-ROW is the last table header's row.
3491 INFO is a plist used as a communication channel."
3492 (and (org-export-table-has-header-p
3493 (org-export-get-parent-table table-row info) info)
3494 (org-export-table-row-ends-rowgroup-p table-row info)
3495 (= (org-export-table-row-group table-row info) 1)))
3497 (defun org-export-table-dimensions (table info)
3498 "Return TABLE dimensions.
3500 INFO is a plist used as a communication channel.
3502 Return value is a CONS like (ROWS . COLUMNS) where
3503 ROWS (resp. COLUMNS) is the number of exportable
3504 rows (resp. columns)."
3505 (let (first-row (columns 0) (rows 0))
3506 ;; Set number of rows, and extract first one.
3507 (org-element-map
3508 table 'table-row
3509 (lambda (row)
3510 (when (eq (org-element-property :type row) 'standard)
3511 (incf rows)
3512 (unless first-row (setq first-row row)))) info)
3513 ;; Set number of columns.
3514 (org-element-map first-row 'table-cell (lambda (cell) (incf columns)) info)
3515 ;; Return value.
3516 (cons rows columns)))
3518 (defun org-export-table-cell-address (table-cell info)
3519 "Return address of a regular TABLE-CELL object.
3521 TABLE-CELL is the cell considered. INFO is a plist used as
3522 a communication channel.
3524 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
3525 zero-based index. Only exportable cells are considered. The
3526 function returns nil for other cells."
3527 (let* ((table-row (org-export-get-parent table-cell info))
3528 (table (org-export-get-parent-table table-cell info)))
3529 ;; Ignore cells in special rows or in special column.
3530 (unless (or (org-export-table-row-is-special-p table-row info)
3531 (and (org-export-table-has-special-column-p table)
3532 (equal (car (org-element-contents table-row)) table-cell)))
3533 (cons
3534 ;; Row number.
3535 (let ((row-count 0))
3536 (org-element-map
3537 table 'table-row
3538 (lambda (row)
3539 (cond ((eq (org-element-property :type row) 'rule) nil)
3540 ((equal row table-row) row-count)
3541 (t (incf row-count) nil)))
3542 info 'first-match))
3543 ;; Column number.
3544 (let ((col-count 0))
3545 (org-element-map
3546 table-row 'table-cell
3547 (lambda (cell)
3548 (if (equal cell table-cell) col-count
3549 (incf col-count) nil))
3550 info 'first-match))))))
3552 (defun org-export-get-table-cell-at (address table info)
3553 "Return regular table-cell object at ADDRESS in TABLE.
3555 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
3556 zero-based index. TABLE is a table type element. INFO is
3557 a plist used as a communication channel.
3559 If no table-cell, among exportable cells, is found at ADDRESS,
3560 return nil."
3561 (let ((column-pos (cdr address)) (column-count 0))
3562 (org-element-map
3563 ;; Row at (car address) or nil.
3564 (let ((row-pos (car address)) (row-count 0))
3565 (org-element-map
3566 table 'table-row
3567 (lambda (row)
3568 (cond ((eq (org-element-property :type row) 'rule) nil)
3569 ((= row-count row-pos) row)
3570 (t (incf row-count) nil)))
3571 info 'first-match))
3572 'table-cell
3573 (lambda (cell)
3574 (if (= column-count column-pos) cell
3575 (incf column-count) nil))
3576 info 'first-match)))
3579 ;;;; For Tables Of Contents
3581 ;; `org-export-collect-headlines' builds a list of all exportable
3582 ;; headline elements, maybe limited to a certain depth. One can then
3583 ;; easily parse it and transcode it.
3585 ;; Building lists of tables, figures or listings is quite similar.
3586 ;; Once the generic function `org-export-collect-elements' is defined,
3587 ;; `org-export-collect-tables', `org-export-collect-figures' and
3588 ;; `org-export-collect-listings' can be derived from it.
3590 (defun org-export-collect-headlines (info &optional n)
3591 "Collect headlines in order to build a table of contents.
3593 INFO is a plist used as a communication channel.
3595 When non-nil, optional argument N must be an integer. It
3596 specifies the depth of the table of contents.
3598 Return a list of all exportable headlines as parsed elements."
3599 (org-element-map
3600 (plist-get info :parse-tree)
3601 'headline
3602 (lambda (headline)
3603 ;; Strip contents from HEADLINE.
3604 (let ((relative-level (org-export-get-relative-level headline info)))
3605 (unless (and n (> relative-level n)) headline)))
3606 info))
3608 (defun org-export-collect-elements (type info &optional predicate)
3609 "Collect referenceable elements of a determined type.
3611 TYPE can be a symbol or a list of symbols specifying element
3612 types to search. Only elements with a caption or a name are
3613 collected.
3615 INFO is a plist used as a communication channel.
3617 When non-nil, optional argument PREDICATE is a function accepting
3618 one argument, an element of type TYPE. It returns a non-nil
3619 value when that element should be collected.
3621 Return a list of all elements found, in order of appearance."
3622 (org-element-map
3623 (plist-get info :parse-tree) type
3624 (lambda (element)
3625 (and (or (org-element-property :caption element)
3626 (org-element-property :name element))
3627 (or (not predicate) (funcall predicate element))
3628 element)) info))
3630 (defun org-export-collect-tables (info)
3631 "Build a list of tables.
3633 INFO is a plist used as a communication channel.
3635 Return a list of table elements with a caption or a name
3636 affiliated keyword."
3637 (org-export-collect-elements 'table info))
3639 (defun org-export-collect-figures (info predicate)
3640 "Build a list of figures.
3642 INFO is a plist used as a communication channel. PREDICATE is
3643 a function which accepts one argument: a paragraph element and
3644 whose return value is non-nil when that element should be
3645 collected.
3647 A figure is a paragraph type element, with a caption or a name,
3648 verifying PREDICATE. The latter has to be provided since
3649 a \"figure\" is a vague concept that may depend on back-end.
3651 Return a list of elements recognized as figures."
3652 (org-export-collect-elements 'paragraph info predicate))
3654 (defun org-export-collect-listings (info)
3655 "Build a list of src blocks.
3657 INFO is a plist used as a communication channel.
3659 Return a list of src-block elements with a caption or a name
3660 affiliated keyword."
3661 (org-export-collect-elements 'src-block info))
3664 ;;;; Topology
3666 ;; Here are various functions to retrieve information about the
3667 ;; neighbourhood of a given element or object. Neighbours of interest
3668 ;; are direct parent (`org-export-get-parent'), parent headline
3669 ;; (`org-export-get-parent-headline'), parent paragraph
3670 ;; (`org-export-get-parent-paragraph'), previous element or object
3671 ;; (`org-export-get-previous-element') and next element or object
3672 ;; (`org-export-get-next-element').
3674 ;; All of these functions are just a specific use of the more generic
3675 ;; `org-export-get-genealogy', which returns the genealogy relative to
3676 ;; the element or object.
3678 (defun org-export-get-genealogy (blob info)
3679 "Return genealogy relative to a given element or object.
3680 BLOB is the element or object being considered. INFO is a plist
3681 used as a communication channel."
3682 (let* ((type (org-element-type blob))
3683 (end (org-element-property :end blob))
3684 (walk-data
3685 (lambda (data genealogy)
3686 ;; Walk DATA, looking for BLOB. GENEALOGY is the list of
3687 ;; parents of all elements in DATA.
3688 (mapc
3689 (lambda (el)
3690 (cond
3691 ((stringp el) nil)
3692 ((equal el blob) (throw 'exit genealogy))
3693 ((>= (org-element-property :end el) end)
3694 ;; If BLOB is an object and EL contains a secondary
3695 ;; string, be sure to check it.
3696 (when (memq type org-element-all-objects)
3697 (let ((sec-prop
3698 (cdr (assq (org-element-type el)
3699 org-element-secondary-value-alist))))
3700 (when sec-prop
3701 (funcall
3702 walk-data
3703 (cons 'org-data
3704 (cons nil (org-element-property sec-prop el)))
3705 (cons el genealogy)))))
3706 (funcall walk-data el (cons el genealogy)))))
3707 (org-element-contents data)))))
3708 (catch 'exit (funcall walk-data (plist-get info :parse-tree) nil) nil)))
3710 (defun org-export-get-parent (blob info)
3711 "Return BLOB parent or nil.
3712 BLOB is the element or object considered. INFO is a plist used
3713 as a communication channel."
3714 (car (org-export-get-genealogy blob info)))
3716 (defun org-export-get-parent-headline (blob info)
3717 "Return BLOB parent headline or nil.
3718 BLOB is the element or object being considered. INFO is a plist
3719 used as a communication channel."
3720 (catch 'exit
3721 (mapc
3722 (lambda (el) (when (eq (org-element-type el) 'headline) (throw 'exit el)))
3723 (org-export-get-genealogy blob info))
3724 nil))
3726 (defun org-export-get-parent-paragraph (object info)
3727 "Return OBJECT parent paragraph or nil.
3728 OBJECT is the object to consider. INFO is a plist used as
3729 a communication channel."
3730 (catch 'exit
3731 (mapc
3732 (lambda (el) (when (eq (org-element-type el) 'paragraph) (throw 'exit el)))
3733 (org-export-get-genealogy object info))
3734 nil))
3736 (defun org-export-get-parent-table (object info)
3737 "Return OBJECT parent table or nil.
3738 OBJECT is either a `table-cell' or `table-element' type object.
3739 INFO is a plist used as a communication channel."
3740 (catch 'exit
3741 (mapc
3742 (lambda (el) (when (eq (org-element-type el) 'table) (throw 'exit el)))
3743 (org-export-get-genealogy object info))
3744 nil))
3746 (defun org-export-get-previous-element (blob info)
3747 "Return previous element or object.
3749 BLOB is an element or object. INFO is a plist used as
3750 a communication channel.
3752 Return previous element or object, a string, or nil."
3753 (let ((parent (org-export-get-parent blob info)))
3754 (cadr (member blob (reverse (org-element-contents parent))))))
3756 (defun org-export-get-next-element (blob info)
3757 "Return next element or object.
3759 BLOB is an element or object. INFO is a plist used as
3760 a communication channel.
3762 Return next element or object, a string, or nil."
3763 (let ((parent (org-export-get-parent blob info)))
3764 (cadr (member blob (org-element-contents parent)))))
3768 ;;; The Dispatcher
3770 ;; `org-export-dispatch' is the standard interactive way to start an
3771 ;; export process. It uses `org-export-dispatch-ui' as a subroutine
3772 ;; for its interface. Most commons back-ends should have an entry in
3773 ;; it.
3775 (defun org-export-dispatch ()
3776 "Export dispatcher for Org mode.
3778 It provides an access to common export related tasks in a buffer.
3779 Its interface comes in two flavours: standard and expert. While
3780 both share the same set of bindings, only the former displays the
3781 valid keys associations. Set `org-export-dispatch-use-expert-ui'
3782 to switch to one or the other.
3784 Return an error if key pressed has no associated command."
3785 (interactive)
3786 (let* ((input (org-export-dispatch-ui
3787 (if (listp org-export-initial-scope) org-export-initial-scope
3788 (list org-export-initial-scope))
3789 org-export-dispatch-use-expert-ui))
3790 (raw-key (car input))
3791 (optns (cdr input)))
3792 ;; Translate "C-a", "C-b"... into "a", "b"... Then take action
3793 ;; depending on user's key pressed.
3794 (case (if (< raw-key 27) (+ raw-key 96) raw-key)
3795 ;; Allow to quit with "q" key.
3796 (?q nil)
3797 ;; Export with `e-ascii' back-end.
3798 ((?A ?N ?U)
3799 (let ((outbuf
3800 (org-export-to-buffer
3801 'e-ascii "*Org E-ASCII Export*"
3802 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)
3803 `(:ascii-charset
3804 ,(case raw-key (?A 'ascii) (?N 'latin1) (t 'utf-8))))))
3805 (with-current-buffer outbuf (text-mode))
3806 (when org-export-show-temporary-export-buffer
3807 (switch-to-buffer-other-window outbuf))))
3808 ((?a ?n ?u)
3809 (org-e-ascii-export-to-ascii
3810 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)
3811 `(:ascii-charset ,(case raw-key (?a 'ascii) (?n 'latin1) (t 'utf-8)))))
3812 ;; Export with `e-latex' back-end.
3814 (let ((outbuf
3815 (org-export-to-buffer
3816 'e-latex "*Org E-LaTeX Export*"
3817 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
3818 (with-current-buffer outbuf (latex-mode))
3819 (when org-export-show-temporary-export-buffer
3820 (switch-to-buffer-other-window outbuf))))
3821 (?l (org-e-latex-export-to-latex
3822 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
3823 (?p (org-e-latex-export-to-pdf
3824 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
3825 (?d (org-open-file
3826 (org-e-latex-export-to-pdf
3827 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
3828 ;; Export with `e-html' back-end.
3830 (let ((outbuf
3831 (org-export-to-buffer
3832 'e-html "*Org E-HTML Export*"
3833 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
3834 ;; set major mode
3835 (with-current-buffer outbuf
3836 (if (featurep 'nxhtml-mode) (nxhtml-mode) (nxml-mode)))
3837 (when org-export-show-temporary-export-buffer
3838 (switch-to-buffer-other-window outbuf))))
3839 (?h (org-e-html-export-to-html
3840 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
3841 (?b (org-open-file
3842 (org-e-html-export-to-html
3843 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
3844 ;; Export with `e-odt' back-end.
3845 (?o (org-e-odt-export-to-odt
3846 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
3847 (?O (org-open-file
3848 (org-e-odt-export-to-odt
3849 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
3850 ;; Publishing facilities
3851 (?F (org-e-publish-current-file (memq 'force optns)))
3852 (?P (org-e-publish-current-project (memq 'force optns)))
3853 (?X (let ((project
3854 (assoc (org-icompleting-read
3855 "Publish project: " org-e-publish-project-alist nil t)
3856 org-e-publish-project-alist)))
3857 (org-e-publish project (memq 'force optns))))
3858 (?E (org-e-publish-all (memq 'force optns)))
3859 ;; Undefined command.
3860 (t (error "No command associated with key %s"
3861 (char-to-string raw-key))))))
3863 (defun org-export-dispatch-ui (options expertp)
3864 "Handle interface for `org-export-dispatch'.
3866 OPTIONS is a list containing current interactive options set for
3867 export. It can contain any of the following symbols:
3868 `body' toggles a body-only export
3869 `subtree' restricts export to current subtree
3870 `visible' restricts export to visible part of buffer.
3871 `force' force publishing files.
3873 EXPERTP, when non-nil, triggers expert UI. In that case, no help
3874 buffer is provided, but indications about currently active
3875 options are given in the prompt. Moreover, \[?] allows to switch
3876 back to standard interface.
3878 Return value is a list with key pressed as CAR and a list of
3879 final interactive export options as CDR."
3880 (let ((help
3881 (format "---- (Options) -------------------------------------------
3883 \[1] Body only: %s [2] Export scope: %s
3884 \[3] Visible only: %s [4] Force publishing: %s
3887 --- (ASCII/Latin-1/UTF-8 Export) -------------------------
3889 \[a/n/u] to TXT file [A/N/U] to temporary buffer
3891 --- (HTML Export) ----------------------------------------
3893 \[h] to HTML file [b] ... and open it
3894 \[H] to temporary buffer
3896 --- (LaTeX Export) ---------------------------------------
3898 \[l] to TEX file [L] to temporary buffer
3899 \[p] to PDF file [d] ... and open it
3901 --- (ODF Export) -----------------------------------------
3903 \[o] to ODT file [O] ... and open it
3905 --- (Publish) --------------------------------------------
3907 \[F] current file [P] current project
3908 \[X] a project [E] every project"
3909 (if (memq 'body options) "On " "Off")
3910 (if (memq 'subtree options) "Subtree" "Buffer ")
3911 (if (memq 'visible options) "On " "Off")
3912 (if (memq 'force options) "On " "Off")))
3913 (standard-prompt "Export command: ")
3914 (expert-prompt (format "Export command (%s%s%s%s): "
3915 (if (memq 'body options) "b" "-")
3916 (if (memq 'subtree options) "s" "-")
3917 (if (memq 'visible options) "v" "-")
3918 (if (memq 'force options) "f" "-")))
3919 (handle-keypress
3920 (function
3921 ;; Read a character from command input, toggling interactive
3922 ;; options when applicable. PROMPT is the displayed prompt,
3923 ;; as a string.
3924 (lambda (prompt)
3925 (let ((key (read-char-exclusive prompt)))
3926 (cond
3927 ;; Ignore non-standard characters (i.e. "M-a").
3928 ((not (characterp key)) (org-export-dispatch-ui options expertp))
3929 ;; Help key: Switch back to standard interface if
3930 ;; expert UI was active.
3931 ((eq key ??) (org-export-dispatch-ui options nil))
3932 ;; Toggle export options.
3933 ((memq key '(?1 ?2 ?3 ?4))
3934 (org-export-dispatch-ui
3935 (let ((option (case key (?1 'body) (?2 'subtree) (?3 'visible)
3936 (?4 'force))))
3937 (if (memq option options) (remq option options)
3938 (cons option options)))
3939 expertp))
3940 ;; Action selected: Send key and options back to
3941 ;; `org-export-dispatch'.
3942 (t (cons key options))))))))
3943 ;; With expert UI, just read key with a fancy prompt. In standard
3944 ;; UI, display an intrusive help buffer.
3945 (if expertp (funcall handle-keypress expert-prompt)
3946 (save-window-excursion
3947 (delete-other-windows)
3948 (with-output-to-temp-buffer "*Org Export/Publishing Help*" (princ help))
3949 (org-fit-window-to-buffer
3950 (get-buffer-window "*Org Export/Publishing Help*"))
3951 (funcall handle-keypress standard-prompt)))))
3954 (provide 'org-export)
3955 ;;; org-export.el ends here