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