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