org-export: Accept nil :post-blank property
[org-mode.git] / contrib / lisp / org-export.el
blobd85ef2eb6a9c60d6c33f79358369ae8cec48eb73
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. See "The Filter System"
45 ;; section for more information.
47 ;; The core function is `org-export-as'. It returns the transcoded
48 ;; buffer as a string.
50 ;; A back-end is defined through one mandatory variable: his
51 ;; translation table. Its name is always
52 ;; `org-BACKEND-translate-alist' where BACKEND stands for the name
53 ;; chosen for the back-end. Its value is an alist whose keys are
54 ;; elements and objects types and values translator functions.
56 ;; These functions should return a string without any trailing space,
57 ;; or nil. They must accept three arguments: the object or element
58 ;; itself, its contents or nil when it isn't recursive and the
59 ;; property list used as a communication channel.
61 ;; Contents, when not nil, are stripped from any global indentation
62 ;; (although the relative one is preserved). They also always end
63 ;; with a single newline character.
65 ;; If, for a given type, no function is found, that element or object
66 ;; type will simply be ignored, along with any blank line or white
67 ;; space at its end. The same will happen if the function returns the
68 ;; nil value. If that function returns the empty string, the type
69 ;; will be ignored, but the blank lines or white spaces will be kept.
71 ;; In addition to element and object types, one function can be
72 ;; associated to the `template' symbol and another one to the
73 ;; `plain-text' symbol.
75 ;; The former returns the final transcoded string, and can be used to
76 ;; add a preamble and a postamble to document's body. It must accept
77 ;; two arguments: the transcoded string and the property list
78 ;; containing export options.
80 ;; The latter, when defined, is to be called on every text not
81 ;; recognized as an element or an object. It must accept two
82 ;; arguments: the text string and the information channel. It is an
83 ;; appropriate place to protect special chars relative to the
84 ;; back-end.
86 ;; Optionally, a back-end can support specific buffer keywords and
87 ;; OPTION keyword's items by setting `org-BACKEND-filters-alist'
88 ;; variable. Refer to `org-export-options-alist' documentation for
89 ;; more information about its value.
91 ;; If the new back-end shares most properties with another one,
92 ;; `org-export-define-derived-backend' can be used to simplify the
93 ;; process.
95 ;; Any back-end can define its own variables. Among them, those
96 ;; customizables should belong to the `org-export-BACKEND' group.
98 ;; Tools for common tasks across back-ends are implemented in the
99 ;; penultimate part of this file. A dispatcher for standard back-ends
100 ;; is provided in the last one.
102 ;;; Code:
104 (eval-when-compile (require 'cl))
105 (require 'org-element)
107 (declare-function org-e-ascii-export-to-ascii "org-e-ascii"
108 (&optional subtreep visible-only body-only ext-plist pub-dir))
109 (declare-function org-e-html-export-to-html "org-e-html"
110 (&optional subtreep visible-only body-only ext-plist pub-dir))
111 (declare-function org-e-latex-export-to-latex "org-e-latex"
112 (&optional subtreep visible-only body-only ext-plist pub-dir))
113 (declare-function org-e-latex-export-to-pdf "org-e-latex"
114 (&optional subtreep visible-only body-only ext-plist pub-dir))
115 (declare-function org-e-odt-export-to-odt "org-e-odt"
116 (&optional subtreep visible-only body-only ext-plist pub-dir))
117 (declare-function org-e-publish "org-e-publish" (project &optional force))
118 (declare-function org-e-publish-all "org-e-publish" (&optional force))
119 (declare-function org-e-publish-current-file "org-e-publish" (&optional force))
120 (declare-function org-e-publish-current-project "org-e-publish"
121 (&optional force))
122 (declare-function org-export-blocks-preprocess "org-exp-blocks")
124 (defvar org-e-publish-project-alist)
125 (defvar org-table-number-fraction)
126 (defvar org-table-number-regexp)
130 ;;; Internal Variables
132 ;; Among internal variables, the most important is
133 ;; `org-export-options-alist'. This variable define the global export
134 ;; options, shared between every exporter, and how they are acquired.
136 (defconst org-export-max-depth 19
137 "Maximum nesting depth for headlines, counting from 0.")
139 (defconst org-export-options-alist
140 '((:author "AUTHOR" nil user-full-name t)
141 (:creator "CREATOR" nil org-export-creator-string)
142 (:date "DATE" nil nil t)
143 (:description "DESCRIPTION" nil nil newline)
144 (:email "EMAIL" nil user-mail-address t)
145 (:exclude-tags "EXCLUDE_TAGS" nil org-export-exclude-tags split)
146 (:headline-levels nil "H" org-export-headline-levels)
147 (:keywords "KEYWORDS" nil nil space)
148 (:language "LANGUAGE" nil org-export-default-language t)
149 (:preserve-breaks nil "\\n" org-export-preserve-breaks)
150 (:section-numbers nil "num" org-export-with-section-numbers)
151 (:select-tags "SELECT_TAGS" nil org-export-select-tags split)
152 (:time-stamp-file nil "timestamp" org-export-time-stamp-file)
153 (:title "TITLE" nil nil space)
154 (:with-archived-trees nil "arch" org-export-with-archived-trees)
155 (:with-author nil "author" org-export-with-author)
156 (:with-clocks nil "c" org-export-with-clocks)
157 (:with-creator nil "creator" org-export-with-creator)
158 (:with-drawers nil "d" org-export-with-drawers)
159 (:with-email nil "email" org-export-with-email)
160 (:with-emphasize nil "*" org-export-with-emphasize)
161 (:with-entities nil "e" org-export-with-entities)
162 (:with-fixed-width nil ":" org-export-with-fixed-width)
163 (:with-footnotes nil "f" org-export-with-footnotes)
164 (:with-plannings nil "p" org-export-with-planning)
165 (:with-priority nil "pri" org-export-with-priority)
166 (:with-special-strings nil "-" org-export-with-special-strings)
167 (:with-sub-superscript nil "^" org-export-with-sub-superscripts)
168 (:with-toc nil "toc" org-export-with-toc)
169 (:with-tables nil "|" org-export-with-tables)
170 (:with-tags nil "tags" org-export-with-tags)
171 (:with-tasks nil "tasks" org-export-with-tasks)
172 (:with-timestamps nil "<" org-export-with-timestamps)
173 (:with-todo-keywords nil "todo" org-export-with-todo-keywords))
174 "Alist between export properties and ways to set them.
176 The CAR of the alist is the property name, and the CDR is a list
177 like (KEYWORD OPTION DEFAULT BEHAVIOUR) where:
179 KEYWORD is a string representing a buffer keyword, or nil. Each
180 property defined this way can also be set, during subtree
181 export, through an headline property named after the keyword
182 with the \"EXPORT_\" prefix (i.e. DATE keyword and EXPORT_DATE
183 property).
184 OPTION is a string that could be found in an #+OPTIONS: line.
185 DEFAULT is the default value for the property.
186 BEHAVIOUR determine how Org should handle multiple keywords for
187 the same property. It is a symbol among:
188 nil Keep old value and discard the new one.
189 t Replace old value with the new one.
190 `space' Concatenate the values, separating them with a space.
191 `newline' Concatenate the values, separating them with
192 a newline.
193 `split' Split values at white spaces, and cons them to the
194 previous list.
196 KEYWORD and OPTION have precedence over DEFAULT.
198 All these properties should be back-end agnostic. For back-end
199 specific properties, define a similar variable named
200 `org-BACKEND-options-alist', replacing BACKEND with the name of
201 the appropriate back-end. You can also redefine properties
202 there, as they have precedence over these.")
204 (defconst org-export-special-keywords
205 '("SETUP_FILE" "OPTIONS" "MACRO")
206 "List of in-buffer keywords that require special treatment.
207 These keywords are not directly associated to a property. The
208 way they are handled must be hard-coded into
209 `org-export-get-inbuffer-options' function.")
211 (defconst org-export-filters-alist
212 '((:filter-bold . org-export-filter-bold-functions)
213 (:filter-babel-call . org-export-filter-babel-call-functions)
214 (:filter-center-block . org-export-filter-center-block-functions)
215 (:filter-clock . org-export-filter-clock-functions)
216 (:filter-code . org-export-filter-code-functions)
217 (:filter-comment . org-export-filter-comment-functions)
218 (:filter-comment-block . org-export-filter-comment-block-functions)
219 (:filter-drawer . org-export-filter-drawer-functions)
220 (:filter-dynamic-block . org-export-filter-dynamic-block-functions)
221 (:filter-entity . org-export-filter-entity-functions)
222 (:filter-example-block . org-export-filter-example-block-functions)
223 (:filter-export-block . org-export-filter-export-block-functions)
224 (:filter-export-snippet . org-export-filter-export-snippet-functions)
225 (:filter-final-output . org-export-filter-final-output-functions)
226 (:filter-fixed-width . org-export-filter-fixed-width-functions)
227 (:filter-footnote-definition . org-export-filter-footnote-definition-functions)
228 (:filter-footnote-reference . org-export-filter-footnote-reference-functions)
229 (:filter-headline . org-export-filter-headline-functions)
230 (:filter-horizontal-rule . org-export-filter-horizontal-rule-functions)
231 (:filter-inline-babel-call . org-export-filter-inline-babel-call-functions)
232 (:filter-inline-src-block . org-export-filter-inline-src-block-functions)
233 (:filter-inlinetask . org-export-filter-inlinetask-functions)
234 (:filter-italic . org-export-filter-italic-functions)
235 (:filter-item . org-export-filter-item-functions)
236 (:filter-keyword . org-export-filter-keyword-functions)
237 (:filter-latex-environment . org-export-filter-latex-environment-functions)
238 (:filter-latex-fragment . org-export-filter-latex-fragment-functions)
239 (:filter-line-break . org-export-filter-line-break-functions)
240 (:filter-link . org-export-filter-link-functions)
241 (:filter-macro . org-export-filter-macro-functions)
242 (:filter-paragraph . org-export-filter-paragraph-functions)
243 (:filter-parse-tree . org-export-filter-parse-tree-functions)
244 (:filter-plain-list . org-export-filter-plain-list-functions)
245 (:filter-plain-text . org-export-filter-plain-text-functions)
246 (:filter-planning . org-export-filter-planning-functions)
247 (:filter-property-drawer . org-export-filter-property-drawer-functions)
248 (:filter-quote-block . org-export-filter-quote-block-functions)
249 (:filter-quote-section . org-export-filter-quote-section-functions)
250 (:filter-radio-target . org-export-filter-radio-target-functions)
251 (:filter-section . org-export-filter-section-functions)
252 (:filter-special-block . org-export-filter-special-block-functions)
253 (:filter-src-block . org-export-filter-src-block-functions)
254 (:filter-statistics-cookie . org-export-filter-statistics-cookie-functions)
255 (:filter-strike-through . org-export-filter-strike-through-functions)
256 (:filter-subscript . org-export-filter-subscript-functions)
257 (:filter-superscript . org-export-filter-superscript-functions)
258 (:filter-table . org-export-filter-table-functions)
259 (:filter-table-cell . org-export-filter-table-cell-functions)
260 (:filter-table-row . org-export-filter-table-row-functions)
261 (:filter-target . org-export-filter-target-functions)
262 (:filter-timestamp . org-export-filter-timestamp-functions)
263 (:filter-underline . org-export-filter-underline-functions)
264 (:filter-verbatim . org-export-filter-verbatim-functions)
265 (:filter-verse-block . org-export-filter-verse-block-functions))
266 "Alist between filters properties and initial values.
268 The key of each association is a property name accessible through
269 the communication channel. Its value is a configurable global
270 variable defining initial filters.
272 This list is meant to install user specified filters. Back-end
273 developers may install their own filters using
274 `org-BACKEND-filters-alist', where BACKEND is the name of the
275 considered back-end. Filters defined there will always be
276 prepended to the current list, so they always get applied
277 first.")
279 (defconst org-export-default-inline-image-rule
280 `(("file" .
281 ,(format "\\.%s\\'"
282 (regexp-opt
283 '("png" "jpeg" "jpg" "gif" "tiff" "tif" "xbm"
284 "xpm" "pbm" "pgm" "ppm") t))))
285 "Default rule for link matching an inline image.
286 This rule applies to links with no description. By default, it
287 will be considered as an inline image if it targets a local file
288 whose extension is either \"png\", \"jpeg\", \"jpg\", \"gif\",
289 \"tiff\", \"tif\", \"xbm\", \"xpm\", \"pbm\", \"pgm\" or \"ppm\".
290 See `org-export-inline-image-p' for more information about
291 rules.")
295 ;;; User-configurable Variables
297 ;; Configuration for the masses.
299 ;; They should never be accessed directly, as their value is to be
300 ;; stored in a property list (cf. `org-export-options-alist').
301 ;; Back-ends will read their value from there instead.
303 (defgroup org-export nil
304 "Options for exporting Org mode files."
305 :tag "Org Export"
306 :group 'org)
308 (defgroup org-export-general nil
309 "General options for export engine."
310 :tag "Org Export General"
311 :group 'org-export)
313 (defcustom org-export-with-archived-trees 'headline
314 "Whether sub-trees with the ARCHIVE tag should be exported.
316 This can have three different values:
317 nil Do not export, pretend this tree is not present.
318 t Do export the entire tree.
319 `headline' Only export the headline, but skip the tree below it.
321 This option can also be set with the #+OPTIONS line,
322 e.g. \"arch:nil\"."
323 :group 'org-export-general
324 :type '(choice
325 (const :tag "Not at all" nil)
326 (const :tag "Headline only" 'headline)
327 (const :tag "Entirely" t)))
329 (defcustom org-export-with-author t
330 "Non-nil means insert author name into the exported file.
331 This option can also be set with the #+OPTIONS line,
332 e.g. \"author:nil\"."
333 :group 'org-export-general
334 :type 'boolean)
336 (defcustom org-export-with-clocks nil
337 "Non-nil means export CLOCK keywords.
338 This option can also be set with the #+OPTIONS line,
339 e.g. \"c:t\"."
340 :group 'org-export-general
341 :type 'boolean)
343 (defcustom org-export-with-creator 'comment
344 "Non-nil means the postamble should contain a creator sentence.
346 The sentence can be set in `org-export-creator-string' and
347 defaults to \"Generated by Org mode XX in Emacs XXX.\".
349 If the value is `comment' insert it as a comment."
350 :group 'org-export-general
351 :type '(choice
352 (const :tag "No creator sentence" nil)
353 (const :tag "Sentence as a comment" 'comment)
354 (const :tag "Insert the sentence" t)))
356 (defcustom org-export-creator-string
357 (format "Generated by Org mode %s in Emacs %s."
358 (if (fboundp 'org-version) (org-version) "(Unknown)")
359 emacs-version)
360 "String to insert at the end of the generated document."
361 :group 'org-export-general
362 :type '(string :tag "Creator string"))
364 (defcustom org-export-with-drawers t
365 "Non-nil means export contents of standard drawers.
367 When t, all drawers are exported. This may also be a list of
368 drawer names to export. This variable doesn't apply to
369 properties drawers.
371 This option can also be set with the #+OPTIONS line,
372 e.g. \"d:nil\"."
373 :group 'org-export-general
374 :type '(choice
375 (const :tag "All drawers" t)
376 (const :tag "None" nil)
377 (repeat :tag "Selected drawers"
378 (string :tag "Drawer name"))))
380 (defcustom org-export-with-email nil
381 "Non-nil means insert author email into the exported file.
382 This option can also be set with the #+OPTIONS line,
383 e.g. \"email:t\"."
384 :group 'org-export-general
385 :type 'boolean)
387 (defcustom org-export-with-emphasize t
388 "Non-nil means interpret *word*, /word/, and _word_ as emphasized text.
390 If the export target supports emphasizing text, the word will be
391 typeset in bold, italic, or underlined, respectively. Not all
392 export backends support this.
394 This option can also be set with the #+OPTIONS line, e.g. \"*:nil\"."
395 :group 'org-export-general
396 :type 'boolean)
398 (defcustom org-export-exclude-tags '("noexport")
399 "Tags that exclude a tree from export.
401 All trees carrying any of these tags will be excluded from
402 export. This is without condition, so even subtrees inside that
403 carry one of the `org-export-select-tags' will be removed.
405 This option can also be set with the #+EXCLUDE_TAGS: keyword."
406 :group 'org-export-general
407 :type '(repeat (string :tag "Tag")))
409 (defcustom org-export-with-fixed-width t
410 "Non-nil means lines starting with \":\" will be in fixed width font.
412 This can be used to have pre-formatted text, fragments of code
413 etc. For example:
414 : ;; Some Lisp examples
415 : (while (defc cnt)
416 : (ding))
417 will be looking just like this in also HTML. See also the QUOTE
418 keyword. Not all export backends support this.
420 This option can also be set with the #+OPTIONS line, e.g. \"::nil\"."
421 :group 'org-export-translation
422 :type 'boolean)
424 (defcustom org-export-with-footnotes t
425 "Non-nil means Org footnotes should be exported.
426 This option can also be set with the #+OPTIONS line,
427 e.g. \"f:nil\"."
428 :group 'org-export-general
429 :type 'boolean)
431 (defcustom org-export-headline-levels 3
432 "The last level which is still exported as a headline.
434 Inferior levels will produce itemize lists when exported. Note
435 that a numeric prefix argument to an exporter function overrides
436 this setting.
438 This option can also be set with the #+OPTIONS line, e.g. \"H:2\"."
439 :group 'org-export-general
440 :type 'integer)
442 (defcustom org-export-default-language "en"
443 "The default language for export and clocktable translations, as a string.
444 This may have an association in
445 `org-clock-clocktable-language-setup'."
446 :group 'org-export-general
447 :type '(string :tag "Language"))
449 (defcustom org-export-preserve-breaks nil
450 "Non-nil means preserve all line breaks when exporting.
452 Normally, in HTML output paragraphs will be reformatted.
454 This option can also be set with the #+OPTIONS line,
455 e.g. \"\\n:t\"."
456 :group 'org-export-general
457 :type 'boolean)
459 (defcustom org-export-with-entities t
460 "Non-nil means interpret entities when exporting.
462 For example, HTML export converts \\alpha to &alpha; and \\AA to
463 &Aring;.
465 For a list of supported names, see the constant `org-entities'
466 and the user option `org-entities-user'.
468 This option can also be set with the #+OPTIONS line,
469 e.g. \"e:nil\"."
470 :group 'org-export-general
471 :type 'boolean)
473 (defcustom org-export-with-planning nil
474 "Non-nil means include planning info in export.
475 This option can also be set with the #+OPTIONS: line,
476 e.g. \"p:t\"."
477 :group 'org-export-general
478 :type 'boolean)
480 (defcustom org-export-with-priority nil
481 "Non-nil means include priority cookies in export.
483 When nil, remove priority cookies for export.
485 This option can also be set with the #+OPTIONS line,
486 e.g. \"pri:t\"."
487 :group 'org-export-general
488 :type 'boolean)
490 (defcustom org-export-with-section-numbers t
491 "Non-nil means add section numbers to headlines when exporting.
493 When set to an integer n, numbering will only happen for
494 headlines whose relative level is higher or equal to n.
496 This option can also be set with the #+OPTIONS line,
497 e.g. \"num:t\"."
498 :group 'org-export-general
499 :type 'boolean)
501 (defcustom org-export-select-tags '("export")
502 "Tags that select a tree for export.
504 If any such tag is found in a buffer, all trees that do not carry
505 one of these tags will be ignored during export. Inside trees
506 that are selected like this, you can still deselect a subtree by
507 tagging it with one of the `org-export-exclude-tags'.
509 This option can also be set with the #+SELECT_TAGS: keyword."
510 :group 'org-export-general
511 :type '(repeat (string :tag "Tag")))
513 (defcustom org-export-with-special-strings t
514 "Non-nil means interpret \"\-\", \"--\" and \"---\" for export.
516 When this option is turned on, these strings will be exported as:
518 Org HTML LaTeX
519 -----+----------+--------
520 \\- &shy; \\-
521 -- &ndash; --
522 --- &mdash; ---
523 ... &hellip; \ldots
525 This option can also be set with the #+OPTIONS line,
526 e.g. \"-:nil\"."
527 :group 'org-export-general
528 :type 'boolean)
530 (defcustom org-export-with-sub-superscripts t
531 "Non-nil means interpret \"_\" and \"^\" for export.
533 When this option is turned on, you can use TeX-like syntax for
534 sub- and superscripts. Several characters after \"_\" or \"^\"
535 will be considered as a single item - so grouping with {} is
536 normally not needed. For example, the following things will be
537 parsed as single sub- or superscripts.
539 10^24 or 10^tau several digits will be considered 1 item.
540 10^-12 or 10^-tau a leading sign with digits or a word
541 x^2-y^3 will be read as x^2 - y^3, because items are
542 terminated by almost any nonword/nondigit char.
543 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
545 Still, ambiguity is possible - so when in doubt use {} to enclose
546 the sub/superscript. If you set this variable to the symbol
547 `{}', the braces are *required* in order to trigger
548 interpretations as sub/superscript. This can be helpful in
549 documents that need \"_\" frequently in plain text.
551 This option can also be set with the #+OPTIONS line,
552 e.g. \"^:nil\"."
553 :group 'org-export-general
554 :type '(choice
555 (const :tag "Interpret them" t)
556 (const :tag "Curly brackets only" {})
557 (const :tag "Do not interpret them" nil)))
559 (defcustom org-export-with-toc t
560 "Non-nil means create a table of contents in exported files.
562 The TOC contains headlines with levels up
563 to`org-export-headline-levels'. When an integer, include levels
564 up to N in the toc, this may then be different from
565 `org-export-headline-levels', but it will not be allowed to be
566 larger than the number of headline levels. When nil, no table of
567 contents is made.
569 This option can also be set with the #+OPTIONS line,
570 e.g. \"toc:nil\" or \"toc:3\"."
571 :group 'org-export-general
572 :type '(choice
573 (const :tag "No Table of Contents" nil)
574 (const :tag "Full Table of Contents" t)
575 (integer :tag "TOC to level")))
577 (defcustom org-export-with-tables t
578 "If non-nil, lines starting with \"|\" define a table.
579 For example:
581 | Name | Address | Birthday |
582 |-------------+----------+-----------|
583 | Arthur Dent | England | 29.2.2100 |
585 This option can also be set with the #+OPTIONS line, e.g. \"|:nil\"."
586 :group 'org-export-general
587 :type 'boolean)
589 (defcustom org-export-with-tags t
590 "If nil, do not export tags, just remove them from headlines.
592 If this is the symbol `not-in-toc', tags will be removed from
593 table of contents entries, but still be shown in the headlines of
594 the document.
596 This option can also be set with the #+OPTIONS line,
597 e.g. \"tags:nil\"."
598 :group 'org-export-general
599 :type '(choice
600 (const :tag "Off" nil)
601 (const :tag "Not in TOC" not-in-toc)
602 (const :tag "On" t)))
604 (defcustom org-export-with-tasks t
605 "Non-nil means include TODO items for export.
606 This may have the following values:
607 t include tasks independent of state.
608 todo include only tasks that are not yet done.
609 done include only tasks that are already done.
610 nil remove all tasks before export
611 list of keywords keep only tasks with these keywords"
612 :group 'org-export-general
613 :type '(choice
614 (const :tag "All tasks" t)
615 (const :tag "No tasks" nil)
616 (const :tag "Not-done tasks" todo)
617 (const :tag "Only done tasks" done)
618 (repeat :tag "Specific TODO keywords"
619 (string :tag "Keyword"))))
621 (defcustom org-export-time-stamp-file t
622 "Non-nil means insert a time stamp into the exported file.
623 The time stamp shows when the file was created.
625 This option can also be set with the #+OPTIONS line,
626 e.g. \"timestamp:nil\"."
627 :group 'org-export-general
628 :type 'boolean)
630 (defcustom org-export-with-timestamps t
631 "Non nil means allow timestamps in export.
633 It can be set to `active', `inactive', t or nil, in order to
634 export, respectively, only active timestamps, only inactive ones,
635 all of them or none.
637 This option can also be set with the #+OPTIONS line, e.g.
638 \"<:nil\"."
639 :group 'org-export-general
640 :type '(choice
641 (const :tag "All timestamps" t)
642 (const :tag "Only active timestamps" active)
643 (const :tag "Only inactive timestamps" inactive)
644 (const :tag "No timestamp" nil)))
646 (defcustom org-export-with-todo-keywords t
647 "Non-nil means include TODO keywords in export.
648 When nil, remove all these keywords from the export."
649 :group 'org-export-general
650 :type 'boolean)
652 (defcustom org-export-allow-BIND 'confirm
653 "Non-nil means allow #+BIND to define local variable values for export.
654 This is a potential security risk, which is why the user must
655 confirm the use of these lines."
656 :group 'org-export-general
657 :type '(choice
658 (const :tag "Never" nil)
659 (const :tag "Always" t)
660 (const :tag "Ask a confirmation for each file" confirm)))
662 (defcustom org-export-snippet-translation-alist nil
663 "Alist between export snippets back-ends and exporter back-ends.
665 This variable allows to provide shortcuts for export snippets.
667 For example, with a value of '\(\(\"h\" . \"e-html\"\)\), the
668 HTML back-end will recognize the contents of \"@@h:<b>@@\" as
669 HTML code while every other back-end will ignore it."
670 :group 'org-export-general
671 :type '(repeat
672 (cons
673 (string :tag "Shortcut")
674 (string :tag "Back-end"))))
676 (defcustom org-export-coding-system nil
677 "Coding system for the exported file."
678 :group 'org-export-general
679 :type 'coding-system)
681 (defcustom org-export-copy-to-kill-ring t
682 "Non-nil means exported stuff will also be pushed onto the kill ring."
683 :group 'org-export-general
684 :type 'boolean)
686 (defcustom org-export-initial-scope 'buffer
687 "The initial scope when exporting with `org-export-dispatch'.
688 This variable can be either set to `buffer' or `subtree'."
689 :group 'org-export-general
690 :type '(choice
691 (const :tag "Export current buffer" 'buffer)
692 (const :tag "Export current subtree" 'subtree)))
694 (defcustom org-export-show-temporary-export-buffer t
695 "Non-nil means show buffer after exporting to temp buffer.
696 When Org exports to a file, the buffer visiting that file is ever
697 shown, but remains buried. However, when exporting to
698 a temporary buffer, that buffer is popped up in a second window.
699 When this variable is nil, the buffer remains buried also in
700 these cases."
701 :group 'org-export-general
702 :type 'boolean)
704 (defcustom org-export-dispatch-use-expert-ui nil
705 "Non-nil means using a non-intrusive `org-export-dispatch'.
706 In that case, no help buffer is displayed. Though, an indicator
707 for current export scope is added to the prompt \(i.e. \"b\" when
708 output is restricted to body only, \"s\" when it is restricted to
709 the current subtree and \"v\" when only visible elements are
710 considered for export\). Also, \[?] allows to switch back to
711 standard mode."
712 :group 'org-export-general
713 :type 'boolean)
717 ;;; Defining New Back-ends
719 (defmacro org-export-define-derived-backend (child parent &rest body)
720 "Create a new back-end as a variant of an existing one.
722 CHILD is the name of the derived back-end. PARENT is the name of
723 the parent back-end.
725 BODY can start with pre-defined keyword arguments. The following
726 keywords are understood:
728 `:filters-alist'
730 Alist of filters that will overwrite or complete filters
731 defined in PARENT back-end, if any.
733 `:options-alist'
735 Alist of buffer keywords or #+OPTIONS items that will
736 overwrite or complete those defined in PARENT back-end, if
737 any.
739 `:translate-alist'
741 Alist of element and object types and transcoders that will
742 overwrite or complete transcode table from PARENT back-end.
744 As an example, here is how one could define \"my-latex\" back-end
745 as a variant of `e-latex' back-end with a custom template
746 function:
748 \(org-export-define-derived-backend my-latex e-latex
749 :translate-alist ((template . my-latex-template-fun)))
751 The back-end could then be called with, for example:
753 \(org-export-to-buffer 'my-latex \"*Test my-latex\")"
754 (declare (debug (&define name symbolp [&rest keywordp sexp] def-body))
755 (indent 2))
756 (let (filters options translate)
757 (while (keywordp (car body))
758 (case (pop body)
759 (:filters-alist (setq filters (pop body)))
760 (:options-alist (setq options (pop body)))
761 (:translate-alist (setq translate (pop body)))
762 (t (pop body))))
763 `(progn
764 ;; Define filters.
765 ,(let ((parent-filters (intern (format "org-%s-filters-alist" parent))))
766 (when (or (boundp parent-filters) filters)
767 `(defconst ,(intern (format "org-%s-filters-alist" child))
768 ',(append filters
769 (and (boundp parent-filters)
770 (copy-sequence (symbol-value parent-filters))))
771 "Alist between filters keywords and back-end specific filters.
772 See `org-export-filters-alist' for more information.")))
773 ;; Define options.
774 ,(let ((parent-options (intern (format "org-%s-options-alist" parent))))
775 (when (or (boundp parent-options) options)
776 `(defconst ,(intern (format "org-%s-options-alist" child))
777 ',(append options
778 (and (boundp parent-options)
779 (copy-sequence (symbol-value parent-options))))
780 "Alist between LaTeX export properties and ways to set them.
781 See `org-export-options-alist' for more information on the
782 structure of the values.")))
783 ;; Define translators.
784 (defvar ,(intern (format "org-%s-translate-alist" child))
785 ',(append translate
786 (copy-sequence
787 (symbol-value
788 (intern (format "org-%s-translate-alist" parent)))))
789 "Alist between element or object types and translators.")
790 ;; Splice in the body, if any.
791 ,@body)))
795 ;;; The Communication Channel
797 ;; During export process, every function has access to a number of
798 ;; properties. They are of two types:
800 ;; 1. Environment options are collected once at the very beginning of
801 ;; the process, out of the original buffer and configuration.
802 ;; Collecting them is handled by `org-export-get-environment'
803 ;; function.
805 ;; Most environment options are defined through the
806 ;; `org-export-options-alist' variable.
808 ;; 2. Tree properties are extracted directly from the parsed tree,
809 ;; just before export, by `org-export-collect-tree-properties'.
811 ;; Here is the full list of properties available during transcode
812 ;; process, with their category (option, tree or local) and their
813 ;; value type.
815 ;; + `:author' :: Author's name.
816 ;; - category :: option
817 ;; - type :: string
819 ;; + `:back-end' :: Current back-end used for transcoding.
820 ;; - category :: tree
821 ;; - type :: symbol
823 ;; + `:creator' :: String to write as creation information.
824 ;; - category :: option
825 ;; - type :: string
827 ;; + `:date' :: String to use as date.
828 ;; - category :: option
829 ;; - type :: string
831 ;; + `:description' :: Description text for the current data.
832 ;; - category :: option
833 ;; - type :: string
835 ;; + `:email' :: Author's email.
836 ;; - category :: option
837 ;; - type :: string
839 ;; + `:exclude-tags' :: Tags for exclusion of subtrees from export
840 ;; process.
841 ;; - category :: option
842 ;; - type :: list of strings
844 ;; + `:footnote-definition-alist' :: Alist between footnote labels and
845 ;; their definition, as parsed data. Only non-inlined footnotes
846 ;; are represented in this alist. Also, every definition isn't
847 ;; guaranteed to be referenced in the parse tree. The purpose of
848 ;; this property is to preserve definitions from oblivion
849 ;; (i.e. when the parse tree comes from a part of the original
850 ;; buffer), it isn't meant for direct use in a back-end. To
851 ;; retrieve a definition relative to a reference, use
852 ;; `org-export-get-footnote-definition' instead.
853 ;; - category :: option
854 ;; - type :: alist (STRING . LIST)
856 ;; + `:headline-levels' :: Maximum level being exported as an
857 ;; headline. Comparison is done with the relative level of
858 ;; headlines in the parse tree, not necessarily with their
859 ;; actual level.
860 ;; - category :: option
861 ;; - type :: integer
863 ;; + `:headline-offset' :: Difference between relative and real level
864 ;; of headlines in the parse tree. For example, a value of -1
865 ;; means a level 2 headline should be considered as level
866 ;; 1 (cf. `org-export-get-relative-level').
867 ;; - category :: tree
868 ;; - type :: integer
870 ;; + `:headline-numbering' :: Alist between headlines and their
871 ;; numbering, as a list of numbers
872 ;; (cf. `org-export-get-headline-number').
873 ;; - category :: tree
874 ;; - type :: alist (INTEGER . LIST)
876 ;; + `:id-alist' :: Alist between ID strings and destination file's
877 ;; path, relative to current directory. It is used by
878 ;; `org-export-resolve-id-link' to resolve ID links targeting an
879 ;; external file.
880 ;; - category :: option
881 ;; - type :: alist (STRING . STRING)
883 ;; + `:ignore-list' :: List of elements and objects that should be
884 ;; ignored during export.
885 ;; - category :: tree
886 ;; - type :: list of elements and objects
888 ;; + `:input-file' :: Full path to input file, if any.
889 ;; - category :: option
890 ;; - type :: string or nil
892 ;; + `:keywords' :: List of keywords attached to data.
893 ;; - category :: option
894 ;; - type :: string
896 ;; + `:language' :: Default language used for translations.
897 ;; - category :: option
898 ;; - type :: string
900 ;; + `:parse-tree' :: Whole parse tree, available at any time during
901 ;; transcoding.
902 ;; - category :: option
903 ;; - type :: list (as returned by `org-element-parse-buffer')
905 ;; + `:preserve-breaks' :: Non-nil means transcoding should preserve
906 ;; all line breaks.
907 ;; - category :: option
908 ;; - type :: symbol (nil, t)
910 ;; + `:section-numbers' :: Non-nil means transcoding should add
911 ;; section numbers to headlines.
912 ;; - category :: option
913 ;; - type :: symbol (nil, t)
915 ;; + `:select-tags' :: List of tags enforcing inclusion of sub-trees
916 ;; in transcoding. When such a tag is present, subtrees without
917 ;; it are de facto excluded from the process. See
918 ;; `use-select-tags'.
919 ;; - category :: option
920 ;; - type :: list of strings
922 ;; + `:target-list' :: List of targets encountered in the parse tree.
923 ;; This is used to partly resolve "fuzzy" links
924 ;; (cf. `org-export-resolve-fuzzy-link').
925 ;; - category :: tree
926 ;; - type :: list of strings
928 ;; + `:time-stamp-file' :: Non-nil means transcoding should insert
929 ;; a time stamp in the output.
930 ;; - category :: option
931 ;; - type :: symbol (nil, t)
933 ;; + `:translate-alist' :: Alist between element and object types and
934 ;; transcoding functions relative to the current back-end.
935 ;; Special keys `template' and `plain-text' are also possible.
936 ;; - category :: option
937 ;; - type :: alist (SYMBOL . FUNCTION)
939 ;; + `:with-archived-trees' :: Non-nil when archived subtrees should
940 ;; also be transcoded. If it is set to the `headline' symbol,
941 ;; only the archived headline's name is retained.
942 ;; - category :: option
943 ;; - type :: symbol (nil, t, `headline')
945 ;; + `:with-author' :: Non-nil means author's name should be included
946 ;; in the output.
947 ;; - category :: option
948 ;; - type :: symbol (nil, t)
950 ;; + `:with-clocks' :: Non-nild means clock keywords should be exported.
951 ;; - category :: option
952 ;; - type :: symbol (nil, t)
954 ;; + `:with-creator' :: Non-nild means a creation sentence should be
955 ;; inserted at the end of the transcoded string. If the value
956 ;; is `comment', it should be commented.
957 ;; - category :: option
958 ;; - type :: symbol (`comment', nil, t)
960 ;; + `:with-drawers' :: Non-nil means drawers should be exported. If
961 ;; its value is a list of names, only drawers with such names
962 ;; will be transcoded.
963 ;; - category :: option
964 ;; - type :: symbol (nil, t) or list of strings
966 ;; + `:with-email' :: Non-nil means output should contain author's
967 ;; email.
968 ;; - category :: option
969 ;; - type :: symbol (nil, t)
971 ;; + `:with-emphasize' :: Non-nil means emphasized text should be
972 ;; interpreted.
973 ;; - category :: option
974 ;; - type :: symbol (nil, t)
976 ;; + `:with-fixed-width' :: Non-nil if transcoder should interpret
977 ;; strings starting with a colon as a fixed-with (verbatim) area.
978 ;; - category :: option
979 ;; - type :: symbol (nil, t)
981 ;; + `:with-footnotes' :: Non-nil if transcoder should interpret
982 ;; footnotes.
983 ;; - category :: option
984 ;; - type :: symbol (nil, t)
986 ;; + `:with-plannings' :: Non-nil means transcoding should include
987 ;; planning info.
988 ;; - category :: option
989 ;; - type :: symbol (nil, t)
991 ;; + `:with-priority' :: Non-nil means transcoding should include
992 ;; priority cookies.
993 ;; - category :: option
994 ;; - type :: symbol (nil, t)
996 ;; + `:with-special-strings' :: Non-nil means transcoding should
997 ;; interpret special strings in plain text.
998 ;; - category :: option
999 ;; - type :: symbol (nil, t)
1001 ;; + `:with-sub-superscript' :: Non-nil means transcoding should
1002 ;; interpret subscript and superscript. With a value of "{}",
1003 ;; only interpret those using curly brackets.
1004 ;; - category :: option
1005 ;; - type :: symbol (nil, {}, t)
1007 ;; + `:with-tables' :: Non-nil means transcoding should interpret
1008 ;; tables.
1009 ;; - category :: option
1010 ;; - type :: symbol (nil, t)
1012 ;; + `:with-tags' :: Non-nil means transcoding should keep tags in
1013 ;; headlines. A `not-in-toc' value will remove them from the
1014 ;; table of contents, if any, nonetheless.
1015 ;; - category :: option
1016 ;; - type :: symbol (nil, t, `not-in-toc')
1018 ;; + `:with-tasks' :: Non-nil means transcoding should include
1019 ;; headlines with a TODO keyword. A `todo' value will only
1020 ;; include headlines with a todo type keyword while a `done'
1021 ;; value will do the contrary. If a list of strings is provided,
1022 ;; only tasks with keywords belonging to that list will be kept.
1023 ;; - category :: option
1024 ;; - type :: symbol (t, todo, done, nil) or list of strings
1026 ;; + `:with-timestamps' :: Non-nil means transcoding should include
1027 ;; time stamps. Special value `active' (resp. `inactive') ask to
1028 ;; export only active (resp. inactive) timestamps. Otherwise,
1029 ;; completely remove them.
1030 ;; - category :: option
1031 ;; - type :: symbol: (`active', `inactive', t, nil)
1033 ;; + `:with-toc' :: Non-nil means that a table of contents has to be
1034 ;; added to the output. An integer value limits its depth.
1035 ;; - category :: option
1036 ;; - type :: symbol (nil, t or integer)
1038 ;; + `:with-todo-keywords' :: Non-nil means transcoding should
1039 ;; include TODO keywords.
1040 ;; - category :: option
1041 ;; - type :: symbol (nil, t)
1044 ;;;; Environment Options
1046 ;; Environment options encompass all parameters defined outside the
1047 ;; scope of the parsed data. They come from five sources, in
1048 ;; increasing precedence order:
1050 ;; - Global variables,
1051 ;; - Buffer's attributes,
1052 ;; - Options keyword symbols,
1053 ;; - Buffer keywords,
1054 ;; - Subtree properties.
1056 ;; The central internal function with regards to environment options
1057 ;; is `org-export-get-environment'. It updates global variables with
1058 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
1059 ;; the different sources.
1061 ;; The internal functions doing the retrieval are:
1062 ;; `org-export-get-global-options',
1063 ;; `org-export-get-buffer-attributes',
1064 ;; `org-export-parse-option-keyword',
1065 ;; `org-export-get-subtree-options' and
1066 ;; `org-export-get-inbuffer-options'
1068 ;; Also, `org-export-confirm-letbind' and `org-export-install-letbind'
1069 ;; take care of the part relative to "#+BIND:" keywords.
1071 (defun org-export-get-environment (&optional backend subtreep ext-plist)
1072 "Collect export options from the current buffer.
1074 Optional argument BACKEND is a symbol specifying which back-end
1075 specific options to read, if any.
1077 When optional argument SUBTREEP is non-nil, assume the export is
1078 done against the current sub-tree.
1080 Third optional argument EXT-PLIST is a property list with
1081 external parameters overriding Org default settings, but still
1082 inferior to file-local settings."
1083 ;; First install #+BIND variables.
1084 (org-export-install-letbind-maybe)
1085 ;; Get and prioritize export options...
1086 (org-combine-plists
1087 ;; ... from global variables...
1088 (org-export-get-global-options backend)
1089 ;; ... from buffer's attributes...
1090 (org-export-get-buffer-attributes)
1091 ;; ... from an external property list...
1092 ext-plist
1093 ;; ... from in-buffer settings...
1094 (org-export-get-inbuffer-options
1095 backend
1096 (and buffer-file-name (org-remove-double-quotes buffer-file-name)))
1097 ;; ... and from subtree, when appropriate.
1098 (and subtreep (org-export-get-subtree-options backend))
1099 ;; Eventually install back-end symbol and its translation table.
1100 `(:back-end
1101 ,backend
1102 :translate-alist
1103 ,(let ((trans-alist (intern (format "org-%s-translate-alist" backend))))
1104 (when (boundp trans-alist) (symbol-value trans-alist))))))
1106 (defun org-export-parse-option-keyword (options &optional backend)
1107 "Parse an OPTIONS line and return values as a plist.
1108 Optional argument BACKEND is a symbol specifying which back-end
1109 specific items to read, if any."
1110 (let* ((all
1111 (append org-export-options-alist
1112 (and backend
1113 (let ((var (intern
1114 (format "org-%s-options-alist" backend))))
1115 (and (boundp var) (eval var))))))
1116 ;; Build an alist between #+OPTION: item and property-name.
1117 (alist (delq nil
1118 (mapcar (lambda (e)
1119 (when (nth 2 e) (cons (regexp-quote (nth 2 e))
1120 (car e))))
1121 all)))
1122 plist)
1123 (mapc (lambda (e)
1124 (when (string-match (concat "\\(\\`\\|[ \t]\\)"
1125 (car e)
1126 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
1127 options)
1128 (setq plist (plist-put plist
1129 (cdr e)
1130 (car (read-from-string
1131 (match-string 2 options)))))))
1132 alist)
1133 plist))
1135 (defun org-export-get-subtree-options (&optional backend)
1136 "Get export options in subtree at point.
1137 Optional argument BACKEND is a symbol specifying back-end used
1138 for export. Return options as a plist."
1139 ;; For each buffer keyword, create an headline property setting the
1140 ;; same property in communication channel. The name for the property
1141 ;; is the keyword with "EXPORT_" appended to it.
1142 (org-with-wide-buffer
1143 (let (prop plist)
1144 ;; Make sure point is at an heading.
1145 (unless (org-at-heading-p) (org-back-to-heading t))
1146 ;; Take care of EXPORT_TITLE. If it isn't defined, use headline's
1147 ;; title as its fallback value.
1148 (when (setq prop (progn (looking-at org-todo-line-regexp)
1149 (or (save-match-data
1150 (org-entry-get (point) "EXPORT_TITLE"))
1151 (org-match-string-no-properties 3))))
1152 (setq plist
1153 (plist-put
1154 plist :title
1155 (org-element-parse-secondary-string
1156 prop (org-element-restriction 'keyword)))))
1157 ;; EXPORT_OPTIONS are parsed in a non-standard way.
1158 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
1159 (setq plist
1160 (nconc plist (org-export-parse-option-keyword prop backend))))
1161 ;; Handle other keywords.
1162 (let ((seen '("TITLE")))
1163 (mapc
1164 (lambda (option)
1165 (let ((property (nth 1 option)))
1166 (when (and property (not (member property seen)))
1167 (let* ((subtree-prop (concat "EXPORT_" property))
1168 (value (org-entry-get (point) subtree-prop)))
1169 (push property seen)
1170 (when value
1171 (setq plist
1172 (plist-put
1173 plist
1174 (car option)
1175 ;; Parse VALUE if required.
1176 (if (member property org-element-parsed-keywords)
1177 (org-element-parse-secondary-string
1178 value (org-element-restriction 'keyword))
1179 value))))))))
1180 ;; Also look for both general keywords and back-end specific
1181 ;; options if BACKEND is provided.
1182 (append (and backend
1183 (let ((var (intern
1184 (format "org-%s-options-alist" backend))))
1185 (and (boundp var) (symbol-value var))))
1186 org-export-options-alist)))
1187 ;; Return value.
1188 plist)))
1190 (defun org-export-get-inbuffer-options (&optional backend files)
1191 "Return current buffer export options, as a plist.
1193 Optional argument BACKEND, when non-nil, is a symbol specifying
1194 which back-end specific options should also be read in the
1195 process.
1197 Optional argument FILES is a list of setup files names read so
1198 far, used to avoid circular dependencies.
1200 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1201 (org-with-wide-buffer
1202 (goto-char (point-min))
1203 (let ((case-fold-search t) plist)
1204 ;; 1. Special keywords, as in `org-export-special-keywords'.
1205 (let ((special-re (org-make-options-regexp org-export-special-keywords)))
1206 (while (re-search-forward special-re nil t)
1207 (let ((element (org-element-at-point)))
1208 (when (eq (org-element-type element) 'keyword)
1209 (let* ((key (org-element-property :key element))
1210 (val (org-element-property :value element))
1211 (prop
1212 (cond
1213 ((string= key "SETUP_FILE")
1214 (let ((file
1215 (expand-file-name
1216 (org-remove-double-quotes (org-trim val)))))
1217 ;; Avoid circular dependencies.
1218 (unless (member file files)
1219 (with-temp-buffer
1220 (insert (org-file-contents file 'noerror))
1221 (org-mode)
1222 (org-export-get-inbuffer-options
1223 backend (cons file files))))))
1224 ((string= key "OPTIONS")
1225 (org-export-parse-option-keyword val backend))
1226 ((string= key "MACRO")
1227 (when (string-match
1228 "^\\([-a-zA-Z0-9_]+\\)\\(?:[ \t]+\\(.*?\\)[ \t]*$\\)?"
1229 val)
1230 (let ((key
1231 (intern
1232 (concat ":macro-"
1233 (downcase (match-string 1 val)))))
1234 (value (org-match-string-no-properties 2 val)))
1235 (cond
1236 ((not value) nil)
1237 ;; Value will be evaled: do not parse it.
1238 ((string-match "\\`(eval\\>" value)
1239 (list key (list value)))
1240 ;; Value has to be parsed for nested
1241 ;; macros.
1243 (list
1245 (let ((restr (org-element-restriction 'macro)))
1246 (org-element-parse-secondary-string
1247 ;; If user explicitly asks for
1248 ;; a newline, be sure to preserve it
1249 ;; from further filling with
1250 ;; `hard-newline'. Also replace
1251 ;; "\\n" with "\n", "\\\n" with "\\n"
1252 ;; and so on...
1253 (replace-regexp-in-string
1254 "\\(\\\\\\\\\\)n" "\\\\"
1255 (replace-regexp-in-string
1256 "\\(?:^\\|[^\\\\]\\)\\(\\\\n\\)"
1257 hard-newline value nil nil 1)
1258 nil nil 1)
1259 restr)))))))))))
1260 (setq plist (org-combine-plists plist prop)))))))
1261 ;; 2. Standard options, as in `org-export-options-alist'.
1262 (let* ((all (append org-export-options-alist
1263 ;; Also look for back-end specific options
1264 ;; if BACKEND is defined.
1265 (and backend
1266 (let ((var
1267 (intern
1268 (format "org-%s-options-alist" backend))))
1269 (and (boundp var) (eval var))))))
1270 ;; Build alist between keyword name and property name.
1271 (alist
1272 (delq nil (mapcar
1273 (lambda (e) (when (nth 1 e) (cons (nth 1 e) (car e))))
1274 all)))
1275 ;; Build regexp matching all keywords associated to export
1276 ;; options. Note: the search is case insensitive.
1277 (opt-re (org-make-options-regexp
1278 (delq nil (mapcar (lambda (e) (nth 1 e)) all)))))
1279 (goto-char (point-min))
1280 (while (re-search-forward opt-re nil t)
1281 (let ((element (org-element-at-point)))
1282 (when (eq (org-element-type element) 'keyword)
1283 (let* ((key (org-element-property :key element))
1284 (val (org-element-property :value element))
1285 (prop (cdr (assoc key alist)))
1286 (behaviour (nth 4 (assq prop all))))
1287 (setq plist
1288 (plist-put
1289 plist prop
1290 ;; Handle value depending on specified BEHAVIOUR.
1291 (case behaviour
1292 (space
1293 (if (not (plist-get plist prop)) (org-trim val)
1294 (concat (plist-get plist prop) " " (org-trim val))))
1295 (newline
1296 (org-trim
1297 (concat (plist-get plist prop) "\n" (org-trim val))))
1298 (split
1299 `(,@(plist-get plist prop) ,@(org-split-string val)))
1300 ('t val)
1301 (otherwise (if (not (plist-member plist prop)) val
1302 (plist-get plist prop))))))))))
1303 ;; Parse keywords specified in `org-element-parsed-keywords'.
1304 (mapc
1305 (lambda (key)
1306 (let* ((prop (cdr (assoc key alist)))
1307 (value (and prop (plist-get plist prop))))
1308 (when (stringp value)
1309 (setq plist
1310 (plist-put
1311 plist prop
1312 (org-element-parse-secondary-string
1313 value (org-element-restriction 'keyword)))))))
1314 org-element-parsed-keywords))
1315 ;; 3. Return final value.
1316 plist)))
1318 (defun org-export-get-buffer-attributes ()
1319 "Return properties related to buffer attributes, as a plist."
1320 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
1321 (list
1322 ;; Store full path of input file name, or nil. For internal use.
1323 :input-file visited-file
1324 :title (or (and visited-file
1325 (file-name-sans-extension
1326 (file-name-nondirectory visited-file)))
1327 (buffer-name (buffer-base-buffer)))
1328 :footnote-definition-alist
1329 ;; Footnotes definitions must be collected in the original
1330 ;; buffer, as there's no insurance that they will still be in the
1331 ;; parse tree, due to possible narrowing.
1332 (let (alist)
1333 (org-with-wide-buffer
1334 (goto-char (point-min))
1335 (while (re-search-forward org-footnote-definition-re nil t)
1336 (let ((def (org-footnote-at-definition-p)))
1337 (when def
1338 (org-skip-whitespace)
1339 (push (cons (car def)
1340 (save-restriction
1341 (narrow-to-region (point) (nth 2 def))
1342 ;; Like `org-element-parse-buffer', but
1343 ;; makes sure the definition doesn't start
1344 ;; with a section element.
1345 (org-element-parse-elements
1346 (point-min) (point-max) nil nil nil nil
1347 (list 'org-data nil))))
1348 alist))))
1349 alist))
1350 :id-alist
1351 ;; Collect id references.
1352 (let (alist)
1353 (org-with-wide-buffer
1354 (goto-char (point-min))
1355 (while (re-search-forward
1356 "\\[\\[id:\\(\\S-+?\\)\\]\\(?:\\[.*?\\]\\)?\\]" nil t)
1357 (let* ((id (org-match-string-no-properties 1))
1358 (file (org-id-find-id-file id)))
1359 (when file (push (cons id (file-relative-name file)) alist)))))
1360 alist)
1361 :macro-modification-time
1362 (and visited-file
1363 (file-exists-p visited-file)
1364 (concat "(eval (format-time-string \"$1\" '"
1365 (prin1-to-string (nth 5 (file-attributes visited-file)))
1366 "))"))
1367 ;; Store input file name as a macro.
1368 :macro-input-file (and visited-file (file-name-nondirectory visited-file))
1369 ;; `:macro-date', `:macro-time' and `:macro-property' could as
1370 ;; well be initialized as tree properties, since they don't
1371 ;; depend on buffer properties. Though, it may be more logical
1372 ;; to keep them close to other ":macro-" properties.
1373 :macro-date "(eval (format-time-string \"$1\"))"
1374 :macro-time "(eval (format-time-string \"$1\"))"
1375 :macro-property "(eval (org-entry-get nil \"$1\" 'selective))")))
1377 (defun org-export-get-global-options (&optional backend)
1378 "Return global export options as a plist.
1380 Optional argument BACKEND, if non-nil, is a symbol specifying
1381 which back-end specific export options should also be read in the
1382 process."
1383 (let ((all (append org-export-options-alist
1384 (and backend
1385 (let ((var (intern
1386 (format "org-%s-options-alist" backend))))
1387 (and (boundp var) (symbol-value var))))))
1388 ;; Output value.
1389 plist)
1390 (mapc
1391 (lambda (cell)
1392 (setq plist
1393 (plist-put
1394 plist
1395 (car cell)
1396 ;; Eval default value provided. If keyword is a member
1397 ;; of `org-element-parsed-keywords', parse it as
1398 ;; a secondary string before storing it.
1399 (let ((value (eval (nth 3 cell))))
1400 (if (not (stringp value)) value
1401 (let ((keyword (nth 1 cell)))
1402 (if (not (member keyword org-element-parsed-keywords)) value
1403 (org-element-parse-secondary-string
1404 value (org-element-restriction 'keyword)))))))))
1405 all)
1406 ;; Return value.
1407 plist))
1409 (defvar org-export-allow-BIND-local nil)
1410 (defun org-export-confirm-letbind ()
1411 "Can we use #+BIND values during export?
1412 By default this will ask for confirmation by the user, to divert
1413 possible security risks."
1414 (cond
1415 ((not org-export-allow-BIND) nil)
1416 ((eq org-export-allow-BIND t) t)
1417 ((local-variable-p 'org-export-allow-BIND-local) org-export-allow-BIND-local)
1418 (t (org-set-local 'org-export-allow-BIND-local
1419 (yes-or-no-p "Allow BIND values in this buffer? ")))))
1421 (defun org-export-install-letbind-maybe ()
1422 "Install the values from #+BIND lines as local variables.
1423 Variables must be installed before in-buffer options are
1424 retrieved."
1425 (let (letbind pair)
1426 (org-with-wide-buffer
1427 (goto-char (point-min))
1428 (while (re-search-forward (org-make-options-regexp '("BIND")) nil t)
1429 (when (org-export-confirm-letbind)
1430 (push (read (concat "(" (org-match-string-no-properties 2) ")"))
1431 letbind))))
1432 (while (setq pair (pop letbind))
1433 (org-set-local (car pair) (nth 1 pair)))))
1436 ;;;; Tree Properties
1438 ;; Tree properties are infromation extracted from parse tree. They
1439 ;; are initialized at the beginning of the transcoding process by
1440 ;; `org-export-collect-tree-properties'.
1442 ;; Dedicated functions focus on computing the value of specific tree
1443 ;; properties during initialization. Thus,
1444 ;; `org-export-populate-ignore-list' lists elements and objects that
1445 ;; should be skipped during export, `org-export-get-min-level' gets
1446 ;; the minimal exportable level, used as a basis to compute relative
1447 ;; level for headlines. Eventually
1448 ;; `org-export-collect-headline-numbering' builds an alist between
1449 ;; headlines and their numbering.
1451 (defun org-export-collect-tree-properties (data info)
1452 "Extract tree properties from parse tree.
1454 DATA is the parse tree from which information is retrieved. INFO
1455 is a list holding export options.
1457 Following tree properties are set or updated:
1458 `:footnote-definition-alist' List of footnotes definitions in
1459 original buffer and current parse tree.
1461 `:headline-offset' Offset between true level of headlines and
1462 local level. An offset of -1 means an headline
1463 of level 2 should be considered as a level
1464 1 headline in the context.
1466 `:headline-numbering' Alist of all headlines as key an the
1467 associated numbering as value.
1469 `:ignore-list' List of elements that should be ignored during
1470 export.
1472 `:target-list' List of all targets in the parse tree.
1474 Return updated plist."
1475 ;; Install the parse tree in the communication channel, in order to
1476 ;; use `org-export-get-genealogy' and al.
1477 (setq info (plist-put info :parse-tree data))
1478 ;; Get the list of elements and objects to ignore, and put it into
1479 ;; `:ignore-list'. Do not overwrite any user ignore that might have
1480 ;; been done during parse tree filtering.
1481 (setq info
1482 (plist-put info
1483 :ignore-list
1484 (append (org-export-populate-ignore-list data info)
1485 (plist-get info :ignore-list))))
1486 ;; Compute `:headline-offset' in order to be able to use
1487 ;; `org-export-get-relative-level'.
1488 (setq info
1489 (plist-put info
1490 :headline-offset (- 1 (org-export-get-min-level data info))))
1491 ;; Update footnotes definitions list with definitions in parse tree.
1492 ;; This is required since buffer expansion might have modified
1493 ;; boundaries of footnote definitions contained in the parse tree.
1494 ;; This way, definitions in `footnote-definition-alist' are bound to
1495 ;; match those in the parse tree.
1496 (let ((defs (plist-get info :footnote-definition-alist)))
1497 (org-element-map
1498 data 'footnote-definition
1499 (lambda (fn)
1500 (push (cons (org-element-property :label fn)
1501 `(org-data nil ,@(org-element-contents fn)))
1502 defs)))
1503 (setq info (plist-put info :footnote-definition-alist defs)))
1504 ;; Properties order doesn't matter: get the rest of the tree
1505 ;; properties.
1506 (nconc
1507 `(:target-list
1508 ,(org-element-map
1509 data '(keyword target)
1510 (lambda (blob)
1511 (when (or (eq (org-element-type blob) 'target)
1512 (string= (org-element-property :key blob) "TARGET"))
1513 blob)) info)
1514 :headline-numbering ,(org-export-collect-headline-numbering data info))
1515 info))
1517 (defun org-export-get-min-level (data options)
1518 "Return minimum exportable headline's level in DATA.
1519 DATA is parsed tree as returned by `org-element-parse-buffer'.
1520 OPTIONS is a plist holding export options."
1521 (catch 'exit
1522 (let ((min-level 10000))
1523 (mapc
1524 (lambda (blob)
1525 (when (and (eq (org-element-type blob) 'headline)
1526 (not (member blob (plist-get options :ignore-list))))
1527 (setq min-level
1528 (min (org-element-property :level blob) min-level)))
1529 (when (= min-level 1) (throw 'exit 1)))
1530 (org-element-contents data))
1531 ;; If no headline was found, for the sake of consistency, set
1532 ;; minimum level to 1 nonetheless.
1533 (if (= min-level 10000) 1 min-level))))
1535 (defun org-export-collect-headline-numbering (data options)
1536 "Return numbering of all exportable headlines in a parse tree.
1538 DATA is the parse tree. OPTIONS is the plist holding export
1539 options.
1541 Return an alist whose key is an headline and value is its
1542 associated numbering \(in the shape of a list of numbers\)."
1543 (let ((numbering (make-vector org-export-max-depth 0)))
1544 (org-element-map
1545 data
1546 'headline
1547 (lambda (headline)
1548 (let ((relative-level
1549 (1- (org-export-get-relative-level headline options))))
1550 (cons
1551 headline
1552 (loop for n across numbering
1553 for idx from 0 to org-export-max-depth
1554 when (< idx relative-level) collect n
1555 when (= idx relative-level) collect (aset numbering idx (1+ n))
1556 when (> idx relative-level) do (aset numbering idx 0)))))
1557 options)))
1559 (defun org-export-populate-ignore-list (data options)
1560 "Return list of elements and objects to ignore during export.
1561 DATA is the parse tree to traverse. OPTIONS is the plist holding
1562 export options."
1563 (let* (ignore
1564 walk-data ; for byte-compiler.
1565 (walk-data
1566 (function
1567 (lambda (data options selected)
1568 ;; Collect ignored elements or objects into IGNORE-LIST.
1569 (mapc
1570 (lambda (el)
1571 (if (org-export--skip-p el options selected) (push el ignore)
1572 (let ((type (org-element-type el)))
1573 (if (and (eq (plist-get options :with-archived-trees)
1574 'headline)
1575 (eq (org-element-type el) 'headline)
1576 (org-element-property :archivedp el))
1577 ;; If headline is archived but tree below has
1578 ;; to be skipped, add it to ignore list.
1579 (mapc (lambda (e) (push e ignore))
1580 (org-element-contents el))
1581 ;; Move into recursive objects/elements.
1582 (when (org-element-contents el)
1583 (funcall walk-data el options selected))))))
1584 (org-element-contents data))))))
1585 ;; Main call. First find trees containing a select tag, if any.
1586 (funcall walk-data data options (org-export--selected-trees data options))
1587 ;; Return value.
1588 ignore))
1590 (defun org-export--selected-trees (data info)
1591 "Return list of headlines containing a select tag in their tree.
1592 DATA is parsed data as returned by `org-element-parse-buffer'.
1593 INFO is a plist holding export options."
1594 (let* (selected-trees
1595 walk-data ; for byte-compiler.
1596 (walk-data
1597 (function
1598 (lambda (data genealogy)
1599 (case (org-element-type data)
1600 (org-data (mapc (lambda (el) (funcall walk-data el genealogy))
1601 (org-element-contents data)))
1602 (headline
1603 (let ((tags (org-element-property :tags data)))
1604 (if (loop for tag in (plist-get info :select-tags)
1605 thereis (member tag tags))
1606 ;; When a select tag is found, mark full
1607 ;; genealogy and every headline within the tree
1608 ;; as acceptable.
1609 (setq selected-trees
1610 (append
1611 genealogy
1612 (org-element-map data 'headline 'identity)
1613 selected-trees))
1614 ;; Else, continue searching in tree, recursively.
1615 (mapc
1616 (lambda (el) (funcall walk-data el (cons data genealogy)))
1617 (org-element-contents data))))))))))
1618 (funcall walk-data data nil) selected-trees))
1620 (defun org-export--skip-p (blob options selected)
1621 "Non-nil when element or object BLOB should be skipped during export.
1622 OPTIONS is the plist holding export options. SELECTED, when
1623 non-nil, is a list of headlines belonging to a tree with a select
1624 tag."
1625 (case (org-element-type blob)
1626 ;; Check headline.
1627 (headline
1628 (let ((with-tasks (plist-get options :with-tasks))
1629 (todo (org-element-property :todo-keyword blob))
1630 (todo-type (org-element-property :todo-type blob))
1631 (archived (plist-get options :with-archived-trees))
1632 (tags (org-element-property :tags blob)))
1634 ;; Ignore subtrees with an exclude tag.
1635 (loop for k in (plist-get options :exclude-tags)
1636 thereis (member k tags))
1637 ;; When a select tag is present in the buffer, ignore any tree
1638 ;; without it.
1639 (and selected (not (member blob selected)))
1640 ;; Ignore commented sub-trees.
1641 (org-element-property :commentedp blob)
1642 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
1643 (and (not archived) (org-element-property :archivedp blob))
1644 ;; Ignore tasks, if specified by `:with-tasks' property.
1645 (and todo
1646 (or (not with-tasks)
1647 (and (memq with-tasks '(todo done))
1648 (not (eq todo-type with-tasks)))
1649 (and (consp with-tasks) (not (member todo with-tasks))))))))
1650 ;; Check timestamp.
1651 (timestamp
1652 (case (plist-get options :with-timestamps)
1653 ;; No timestamp allowed.
1654 ('nil t)
1655 ;; Only active timestamps allowed and the current one isn't
1656 ;; active.
1657 (active
1658 (not (memq (org-element-property :type blob)
1659 '(active active-range))))
1660 ;; Only inactive timestamps allowed and the current one isn't
1661 ;; inactive.
1662 (inactive
1663 (not (memq (org-element-property :type blob)
1664 '(inactive inactive-range))))))
1665 ;; Check drawer.
1666 (drawer
1667 (or (not (plist-get options :with-drawers))
1668 (and (consp (plist-get options :with-drawers))
1669 (not (member (org-element-property :drawer-name blob)
1670 (plist-get options :with-drawers))))))
1671 ;; Check table-row.
1672 (table-row (org-export-table-row-is-special-p blob options))
1673 ;; Check table-cell.
1674 (table-cell
1675 (and (org-export-table-has-special-column-p
1676 (org-export-get-parent-table blob))
1677 (not (org-export-get-previous-element blob))))
1678 ;; Check clock.
1679 (clock (not (plist-get options :with-clocks)))
1680 ;; Check planning.
1681 (planning (not (plist-get options :with-plannings)))))
1685 ;;; The Transcoder
1687 ;; `org-export-data' reads a parse tree (obtained with, i.e.
1688 ;; `org-element-parse-buffer') and transcodes it into a specified
1689 ;; back-end output. It takes care of filtering out elements or
1690 ;; objects according to export options and organizing the output blank
1691 ;; lines and white space are preserved.
1693 ;; Internally, three functions handle the filtering of objects and
1694 ;; elements during the export. In particular,
1695 ;; `org-export-ignore-element' marks an element or object so future
1696 ;; parse tree traversals skip it, `org-export-interpret-p' tells which
1697 ;; elements or objects should be seen as real Org syntax and
1698 ;; `org-export-expand' transforms the others back into their original
1699 ;; shape
1701 ;; `org-export-transcoder' is an accessor returning appropriate
1702 ;; translator function for a given element or object.
1704 (defun org-export-transcoder (blob info)
1705 "Return appropriate transcoder for BLOB.
1706 INFO is a plist containing export directives."
1707 (let ((type (org-element-type blob)))
1708 ;; Return contents only for complete parse trees.
1709 (if (eq type 'org-data) (lambda (blob contents info) contents)
1710 (let ((transcoder (cdr (assq type (plist-get info :translate-alist)))))
1711 (and (fboundp transcoder) transcoder)))))
1713 (defun org-export-data (data info)
1714 "Convert DATA into current back-end format.
1716 DATA is a parse tree, an element or an object or a secondary
1717 string. INFO is a plist holding export options.
1719 Return transcoded string."
1720 (let* ((type (org-element-type data))
1721 (results
1722 (cond
1723 ;; Ignored element/object.
1724 ((member data (plist-get info :ignore-list)) nil)
1725 ;; Plain text.
1726 ((eq type 'plain-text)
1727 (org-export-filter-apply-functions
1728 (plist-get info :filter-plain-text)
1729 (let ((transcoder (org-export-transcoder data info)))
1730 (if transcoder (funcall transcoder data info) data))
1731 info))
1732 ;; Uninterpreted element/object: change it back to Org
1733 ;; syntax and export again resulting raw string.
1734 ((not (org-export-interpret-p data info))
1735 (org-export-data
1736 (org-export-expand
1737 data
1738 (mapconcat (lambda (blob) (org-export-data blob info))
1739 (org-element-contents data)
1740 ""))
1741 info))
1742 ;; Secondary string.
1743 ((not type)
1744 (mapconcat (lambda (obj) (org-export-data obj info)) data ""))
1745 ;; Element/Object without contents or, as a special case,
1746 ;; headline with archive tag and archived trees restricted
1747 ;; to title only.
1748 ((or (not (org-element-contents data))
1749 (and (eq type 'headline)
1750 (eq (plist-get info :with-archived-trees) 'headline)
1751 (org-element-property :archivedp data)))
1752 (let ((transcoder (org-export-transcoder data info)))
1753 (and (fboundp transcoder) (funcall transcoder data nil info))))
1754 ;; Element/Object with contents.
1756 (let ((transcoder (org-export-transcoder data info)))
1757 (when transcoder
1758 (let* ((greaterp (memq type org-element-greater-elements))
1759 (objectp (and (not greaterp)
1760 (memq type org-element-recursive-objects)))
1761 (contents
1762 (mapconcat
1763 (lambda (element) (org-export-data element info))
1764 (org-element-contents
1765 (if (or greaterp objectp) data
1766 ;; Elements directly containing objects
1767 ;; must have their indentation normalized
1768 ;; first.
1769 (org-element-normalize-contents
1770 data
1771 ;; When normalizing contents of the first
1772 ;; paragraph in an item or a footnote
1773 ;; definition, ignore first line's
1774 ;; indentation: there is none and it
1775 ;; might be misleading.
1776 (when (eq type 'paragraph)
1777 (let ((parent (org-export-get-parent data)))
1778 (and (equal (car (org-element-contents parent))
1779 data)
1780 (memq (org-element-type parent)
1781 '(footnote-definition item))))))))
1782 "")))
1783 (funcall transcoder data
1784 (if greaterp (org-element-normalize-string contents)
1785 contents)
1786 info))))))))
1787 (cond
1788 ((not results) nil)
1789 ((memq type '(org-data plain-text nil)) results)
1790 ;; Append the same white space between elements or objects as in
1791 ;; the original buffer, and call appropriate filters.
1793 (let ((results
1794 (org-export-filter-apply-functions
1795 (plist-get info (intern (format ":filter-%s" type)))
1796 (let ((post-blank (or (org-element-property :post-blank data) 0)))
1797 (if (memq type org-element-all-elements)
1798 (concat (org-element-normalize-string results)
1799 (make-string post-blank ?\n))
1800 (concat results (make-string post-blank ? ))))
1801 info)))
1802 ;; Eventually return string.
1803 results)))))
1805 (defun org-export-interpret-p (blob info)
1806 "Non-nil if element or object BLOB should be interpreted as Org syntax.
1807 Check is done according to export options INFO, stored as
1808 a plist."
1809 (case (org-element-type blob)
1810 ;; ... entities...
1811 (entity (plist-get info :with-entities))
1812 ;; ... emphasis...
1813 (emphasis (plist-get info :with-emphasize))
1814 ;; ... fixed-width areas.
1815 (fixed-width (plist-get info :with-fixed-width))
1816 ;; ... footnotes...
1817 ((footnote-definition footnote-reference)
1818 (plist-get info :with-footnotes))
1819 ;; ... sub/superscripts...
1820 ((subscript superscript)
1821 (let ((sub/super-p (plist-get info :with-sub-superscript)))
1822 (if (eq sub/super-p '{})
1823 (org-element-property :use-brackets-p blob)
1824 sub/super-p)))
1825 ;; ... tables...
1826 (table (plist-get info :with-tables))
1827 (otherwise t)))
1829 (defun org-export-expand (blob contents)
1830 "Expand a parsed element or object to its original state.
1831 BLOB is either an element or an object. CONTENTS is its
1832 contents, as a string or nil."
1833 (funcall
1834 (intern (format "org-element-%s-interpreter" (org-element-type blob)))
1835 blob contents))
1837 (defun org-export-ignore-element (element info)
1838 "Add ELEMENT to `:ignore-list' in INFO.
1840 Any element in `:ignore-list' will be skipped when using
1841 `org-element-map'. INFO is modified by side effects."
1842 (plist-put info :ignore-list (cons element (plist-get info :ignore-list))))
1846 ;;; The Filter System
1848 ;; Filters allow end-users to tweak easily the transcoded output.
1849 ;; They are the functional counterpart of hooks, as every filter in
1850 ;; a set is applied to the return value of the previous one.
1852 ;; Every set is back-end agnostic. Although, a filter is always
1853 ;; called, in addition to the string it applies to, with the back-end
1854 ;; used as argument, so it's easy for the end-user to add back-end
1855 ;; specific filters in the set. The communication channel, as
1856 ;; a plist, is required as the third argument.
1858 ;; From the developer side, filters sets can be installed in the
1859 ;; process with the help of `org-BACKEND-filters-alist' variable.
1860 ;; Each association has a key among the following symbols and
1861 ;; a function or a list of functions as value.
1863 ;; - `:filter-parse-tree' applies directly on the complete parsed
1864 ;; tree. It's the only filters set that doesn't apply to a string.
1865 ;; Users can set it through `org-export-filter-parse-tree-functions'
1866 ;; variable.
1868 ;; - `:filter-final-output' applies to the final transcoded string.
1869 ;; Users can set it with `org-export-filter-final-output-functions'
1870 ;; variable
1872 ;; - `:filter-plain-text' applies to any string not recognized as Org
1873 ;; syntax. `org-export-filter-plain-text-functions' allows users to
1874 ;; configure it.
1876 ;; - `:filter-TYPE' applies on the string returned after an element or
1877 ;; object of type TYPE has been transcoded. An user can modify
1878 ;; `org-export-filter-TYPE-functions'
1880 ;; All filters sets are applied with
1881 ;; `org-export-filter-apply-functions' function. Filters in a set are
1882 ;; applied in a LIFO fashion. It allows developers to be sure that
1883 ;; their filters will be applied first.
1885 ;; Filters properties are installed in communication channel with
1886 ;; `org-export-install-filters' function.
1888 ;; Eventually, a hook (`org-export-before-parsing-hook') is run just
1889 ;; before parsing to allow for heavy structure modifications.
1892 ;;;; Before Parsing Hook
1894 (defvar org-export-before-parsing-hook nil
1895 "Hook run before parsing an export buffer.
1896 This is run after include keywords have been expanded and Babel
1897 code executed, on a copy of original buffer's area being
1898 exported. Visibility is the same as in the original one. Point
1899 is left at the beginning of the new one.")
1902 ;;;; Special Filters
1904 (defvar org-export-filter-parse-tree-functions nil
1905 "List of functions applied to the parsed tree.
1906 Each filter is called with three arguments: the parse tree, as
1907 returned by `org-element-parse-buffer', the back-end, as
1908 a symbol, and the communication channel, as a plist. It must
1909 return the modified parse tree to transcode.")
1911 (defvar org-export-filter-final-output-functions nil
1912 "List of functions applied to the transcoded string.
1913 Each filter is called with three arguments: the full transcoded
1914 string, the back-end, as a symbol, and the communication channel,
1915 as a plist. It must return a string that will be used as the
1916 final export output.")
1918 (defvar org-export-filter-plain-text-functions nil
1919 "List of functions applied to plain text.
1920 Each filter is called with three arguments: a string which
1921 contains no Org syntax, the back-end, as a symbol, and the
1922 communication channel, as a plist. It must return a string or
1923 nil.")
1926 ;;;; Elements Filters
1928 (defvar org-export-filter-center-block-functions nil
1929 "List of functions applied to a transcoded center block.
1930 Each filter is called with three arguments: the transcoded data,
1931 as a string, the back-end, as a symbol, and the communication
1932 channel, as a plist. It must return a string or nil.")
1934 (defvar org-export-filter-clock-functions nil
1935 "List of functions applied to a transcoded clock.
1936 Each filter is called with three arguments: the transcoded data,
1937 as a string, the back-end, as a symbol, and the communication
1938 channel, as a plist. It must return a string or nil.")
1940 (defvar org-export-filter-drawer-functions nil
1941 "List of functions applied to a transcoded drawer.
1942 Each filter is called with three arguments: the transcoded data,
1943 as a string, the back-end, as a symbol, and the communication
1944 channel, as a plist. It must return a string or nil.")
1946 (defvar org-export-filter-dynamic-block-functions nil
1947 "List of functions applied to a transcoded dynamic-block.
1948 Each filter is called with three arguments: the transcoded data,
1949 as a string, the back-end, as a symbol, and the communication
1950 channel, as a plist. It must return a string or nil.")
1952 (defvar org-export-filter-headline-functions nil
1953 "List of functions applied to a transcoded headline.
1954 Each filter is called with three arguments: the transcoded data,
1955 as a string, the back-end, as a symbol, and the communication
1956 channel, as a plist. It must return a string or nil.")
1958 (defvar org-export-filter-inlinetask-functions nil
1959 "List of functions applied to a transcoded inlinetask.
1960 Each filter is called with three arguments: the transcoded data,
1961 as a string, the back-end, as a symbol, and the communication
1962 channel, as a plist. It must return a string or nil.")
1964 (defvar org-export-filter-plain-list-functions nil
1965 "List of functions applied to a transcoded plain-list.
1966 Each filter is called with three arguments: the transcoded data,
1967 as a string, the back-end, as a symbol, and the communication
1968 channel, as a plist. It must return a string or nil.")
1970 (defvar org-export-filter-item-functions nil
1971 "List of functions applied to a transcoded item.
1972 Each filter is called with three arguments: the transcoded data,
1973 as a string, the back-end, as a symbol, and the communication
1974 channel, as a plist. It must return a string or nil.")
1976 (defvar org-export-filter-comment-functions nil
1977 "List of functions applied to a transcoded comment.
1978 Each filter is called with three arguments: the transcoded data,
1979 as a string, the back-end, as a symbol, and the communication
1980 channel, as a plist. It must return a string or nil.")
1982 (defvar org-export-filter-comment-block-functions nil
1983 "List of functions applied to a transcoded comment-comment.
1984 Each filter is called with three arguments: the transcoded data,
1985 as a string, the back-end, as a symbol, and the communication
1986 channel, as a plist. It must return a string or nil.")
1988 (defvar org-export-filter-example-block-functions nil
1989 "List of functions applied to a transcoded example-block.
1990 Each filter is called with three arguments: the transcoded data,
1991 as a string, the back-end, as a symbol, and the communication
1992 channel, as a plist. It must return a string or nil.")
1994 (defvar org-export-filter-export-block-functions nil
1995 "List of functions applied to a transcoded export-block.
1996 Each filter is called with three arguments: the transcoded data,
1997 as a string, the back-end, as a symbol, and the communication
1998 channel, as a plist. It must return a string or nil.")
2000 (defvar org-export-filter-fixed-width-functions nil
2001 "List of functions applied to a transcoded fixed-width.
2002 Each filter is called with three arguments: the transcoded data,
2003 as a string, the back-end, as a symbol, and the communication
2004 channel, as a plist. It must return a string or nil.")
2006 (defvar org-export-filter-footnote-definition-functions nil
2007 "List of functions applied to a transcoded footnote-definition.
2008 Each filter is called with three arguments: the transcoded data,
2009 as a string, the back-end, as a symbol, and the communication
2010 channel, as a plist. It must return a string or nil.")
2012 (defvar org-export-filter-horizontal-rule-functions nil
2013 "List of functions applied to a transcoded horizontal-rule.
2014 Each filter is called with three arguments: the transcoded data,
2015 as a string, the back-end, as a symbol, and the communication
2016 channel, as a plist. It must return a string or nil.")
2018 (defvar org-export-filter-keyword-functions nil
2019 "List of functions applied to a transcoded keyword.
2020 Each filter is called with three arguments: the transcoded data,
2021 as a string, the back-end, as a symbol, and the communication
2022 channel, as a plist. It must return a string or nil.")
2024 (defvar org-export-filter-latex-environment-functions nil
2025 "List of functions applied to a transcoded latex-environment.
2026 Each filter is called with three arguments: the transcoded data,
2027 as a string, the back-end, as a symbol, and the communication
2028 channel, as a plist. It must return a string or nil.")
2030 (defvar org-export-filter-babel-call-functions nil
2031 "List of functions applied to a transcoded babel-call.
2032 Each filter is called with three arguments: the transcoded data,
2033 as a string, the back-end, as a symbol, and the communication
2034 channel, as a plist. It must return a string or nil.")
2036 (defvar org-export-filter-paragraph-functions nil
2037 "List of functions applied to a transcoded paragraph.
2038 Each filter is called with three arguments: the transcoded data,
2039 as a string, the back-end, as a symbol, and the communication
2040 channel, as a plist. It must return a string or nil.")
2042 (defvar org-export-filter-planning-functions nil
2043 "List of functions applied to a transcoded planning.
2044 Each filter is called with three arguments: the transcoded data,
2045 as a string, the back-end, as a symbol, and the communication
2046 channel, as a plist. It must return a string or nil.")
2048 (defvar org-export-filter-property-drawer-functions nil
2049 "List of functions applied to a transcoded property-drawer.
2050 Each filter is called with three arguments: the transcoded data,
2051 as a string, the back-end, as a symbol, and the communication
2052 channel, as a plist. It must return a string or nil.")
2054 (defvar org-export-filter-quote-block-functions nil
2055 "List of functions applied to a transcoded quote block.
2056 Each filter is called with three arguments: the transcoded quote
2057 data, as a string, the back-end, as a symbol, and the
2058 communication channel, as a plist. It must return a string or
2059 nil.")
2061 (defvar org-export-filter-quote-section-functions nil
2062 "List of functions applied to a transcoded quote-section.
2063 Each filter is called with three arguments: the transcoded data,
2064 as a string, the back-end, as a symbol, and the communication
2065 channel, as a plist. It must return a string or nil.")
2067 (defvar org-export-filter-section-functions nil
2068 "List of functions applied to a transcoded section.
2069 Each filter is called with three arguments: the transcoded data,
2070 as a string, the back-end, as a symbol, and the communication
2071 channel, as a plist. It must return a string or nil.")
2073 (defvar org-export-filter-special-block-functions nil
2074 "List of functions applied to a transcoded special block.
2075 Each filter is called with three arguments: the transcoded data,
2076 as a string, the back-end, as a symbol, and the communication
2077 channel, as a plist. It must return a string or nil.")
2079 (defvar org-export-filter-src-block-functions nil
2080 "List of functions applied to a transcoded src-block.
2081 Each filter is called with three arguments: the transcoded data,
2082 as a string, the back-end, as a symbol, and the communication
2083 channel, as a plist. It must return a string or nil.")
2085 (defvar org-export-filter-table-functions nil
2086 "List of functions applied to a transcoded table.
2087 Each filter is called with three arguments: the transcoded data,
2088 as a string, the back-end, as a symbol, and the communication
2089 channel, as a plist. It must return a string or nil.")
2091 (defvar org-export-filter-table-cell-functions nil
2092 "List of functions applied to a transcoded table-cell.
2093 Each filter is called with three arguments: the transcoded data,
2094 as a string, the back-end, as a symbol, and the communication
2095 channel, as a plist. It must return a string or nil.")
2097 (defvar org-export-filter-table-row-functions nil
2098 "List of functions applied to a transcoded table-row.
2099 Each filter is called with three arguments: the transcoded data,
2100 as a string, the back-end, as a symbol, and the communication
2101 channel, as a plist. It must return a string or nil.")
2103 (defvar org-export-filter-verse-block-functions nil
2104 "List of functions applied to a transcoded verse block.
2105 Each filter is called with three arguments: the transcoded data,
2106 as a string, the back-end, as a symbol, and the communication
2107 channel, as a plist. It must return a string or nil.")
2110 ;;;; Objects Filters
2112 (defvar org-export-filter-bold-functions nil
2113 "List of functions applied to transcoded bold text.
2114 Each filter is called with three arguments: the transcoded data,
2115 as a string, the back-end, as a symbol, and the communication
2116 channel, as a plist. It must return a string or nil.")
2118 (defvar org-export-filter-code-functions nil
2119 "List of functions applied to transcoded code text.
2120 Each filter is called with three arguments: the transcoded data,
2121 as a string, the back-end, as a symbol, and the communication
2122 channel, as a plist. It must return a string or nil.")
2124 (defvar org-export-filter-entity-functions nil
2125 "List of functions applied to a transcoded entity.
2126 Each filter is called with three arguments: the transcoded data,
2127 as a string, the back-end, as a symbol, and the communication
2128 channel, as a plist. It must return a string or nil.")
2130 (defvar org-export-filter-export-snippet-functions nil
2131 "List of functions applied to a transcoded export-snippet.
2132 Each filter is called with three arguments: the transcoded data,
2133 as a string, the back-end, as a symbol, and the communication
2134 channel, as a plist. It must return a string or nil.")
2136 (defvar org-export-filter-footnote-reference-functions nil
2137 "List of functions applied to a transcoded footnote-reference.
2138 Each filter is called with three arguments: the transcoded data,
2139 as a string, the back-end, as a symbol, and the communication
2140 channel, as a plist. It must return a string or nil.")
2142 (defvar org-export-filter-inline-babel-call-functions nil
2143 "List of functions applied to a transcoded inline-babel-call.
2144 Each filter is called with three arguments: the transcoded data,
2145 as a string, the back-end, as a symbol, and the communication
2146 channel, as a plist. It must return a string or nil.")
2148 (defvar org-export-filter-inline-src-block-functions nil
2149 "List of functions applied to a transcoded inline-src-block.
2150 Each filter is called with three arguments: the transcoded data,
2151 as a string, the back-end, as a symbol, and the communication
2152 channel, as a plist. It must return a string or nil.")
2154 (defvar org-export-filter-italic-functions nil
2155 "List of functions applied to transcoded italic text.
2156 Each filter is called with three arguments: the transcoded data,
2157 as a string, the back-end, as a symbol, and the communication
2158 channel, as a plist. It must return a string or nil.")
2160 (defvar org-export-filter-latex-fragment-functions nil
2161 "List of functions applied to a transcoded latex-fragment.
2162 Each filter is called with three arguments: the transcoded data,
2163 as a string, the back-end, as a symbol, and the communication
2164 channel, as a plist. It must return a string or nil.")
2166 (defvar org-export-filter-line-break-functions nil
2167 "List of functions applied to a transcoded line-break.
2168 Each filter is called with three arguments: the transcoded data,
2169 as a string, the back-end, as a symbol, and the communication
2170 channel, as a plist. It must return a string or nil.")
2172 (defvar org-export-filter-link-functions nil
2173 "List of functions applied to a transcoded link.
2174 Each filter is called with three arguments: the transcoded data,
2175 as a string, the back-end, as a symbol, and the communication
2176 channel, as a plist. It must return a string or nil.")
2178 (defvar org-export-filter-macro-functions nil
2179 "List of functions applied to a transcoded macro.
2180 Each filter is called with three arguments: the transcoded data,
2181 as a string, the back-end, as a symbol, and the communication
2182 channel, as a plist. It must return a string or nil.")
2184 (defvar org-export-filter-radio-target-functions nil
2185 "List of functions applied to a transcoded radio-target.
2186 Each filter is called with three arguments: the transcoded data,
2187 as a string, the back-end, as a symbol, and the communication
2188 channel, as a plist. It must return a string or nil.")
2190 (defvar org-export-filter-statistics-cookie-functions nil
2191 "List of functions applied to a transcoded statistics-cookie.
2192 Each filter is called with three arguments: the transcoded data,
2193 as a string, the back-end, as a symbol, and the communication
2194 channel, as a plist. It must return a string or nil.")
2196 (defvar org-export-filter-strike-through-functions nil
2197 "List of functions applied to transcoded strike-through text.
2198 Each filter is called with three arguments: the transcoded data,
2199 as a string, the back-end, as a symbol, and the communication
2200 channel, as a plist. It must return a string or nil.")
2202 (defvar org-export-filter-subscript-functions nil
2203 "List of functions applied to a transcoded subscript.
2204 Each filter is called with three arguments: the transcoded data,
2205 as a string, the back-end, as a symbol, and the communication
2206 channel, as a plist. It must return a string or nil.")
2208 (defvar org-export-filter-superscript-functions nil
2209 "List of functions applied to a transcoded superscript.
2210 Each filter is called with three arguments: the transcoded data,
2211 as a string, the back-end, as a symbol, and the communication
2212 channel, as a plist. It must return a string or nil.")
2214 (defvar org-export-filter-target-functions nil
2215 "List of functions applied to a transcoded target.
2216 Each filter is called with three arguments: the transcoded data,
2217 as a string, the back-end, as a symbol, and the communication
2218 channel, as a plist. It must return a string or nil.")
2220 (defvar org-export-filter-timestamp-functions nil
2221 "List of functions applied to a transcoded timestamp.
2222 Each filter is called with three arguments: the transcoded data,
2223 as a string, the back-end, as a symbol, and the communication
2224 channel, as a plist. It must return a string or nil.")
2226 (defvar org-export-filter-underline-functions nil
2227 "List of functions applied to transcoded underline text.
2228 Each filter is called with three arguments: the transcoded data,
2229 as a string, the back-end, as a symbol, and the communication
2230 channel, as a plist. It must return a string or nil.")
2232 (defvar org-export-filter-verbatim-functions nil
2233 "List of functions applied to transcoded verbatim text.
2234 Each filter is called with three arguments: the transcoded data,
2235 as a string, the back-end, as a symbol, and the communication
2236 channel, as a plist. It must return a string or nil.")
2239 ;;;; Filters Tools
2241 ;; Internal function `org-export-install-filters' installs filters
2242 ;; hard-coded in back-ends (developer filters) and filters from global
2243 ;; variables (user filters) in the communication channel.
2245 ;; Internal function `org-export-filter-apply-functions' takes care
2246 ;; about applying each filter in order to a given data. It stops
2247 ;; whenever a filter returns a nil value.
2249 ;; User-oriented function `org-export-set-element' replaces one
2250 ;; element or object in the parse tree with another one. It is meant
2251 ;; to be used as a tool for parse tree filters.
2253 (defun org-export-filter-apply-functions (filters value info)
2254 "Call every function in FILTERS.
2255 Functions are called with arguments VALUE, current export
2256 back-end and INFO. Call is done in a LIFO fashion, to be sure
2257 that developer specified filters, if any, are called first."
2258 (loop for filter in filters
2259 if (not value) return nil else
2260 do (setq value (funcall filter value (plist-get info :back-end) info)))
2261 value)
2263 (defun org-export-install-filters (info)
2264 "Install filters properties in communication channel.
2266 INFO is a plist containing the current communication channel.
2268 Return the updated communication channel."
2269 (let (plist)
2270 ;; Install user defined filters with `org-export-filters-alist'.
2271 (mapc (lambda (p)
2272 (setq plist (plist-put plist (car p) (eval (cdr p)))))
2273 org-export-filters-alist)
2274 ;; Prepend back-end specific filters to that list.
2275 (let ((back-end-filters (intern (format "org-%s-filters-alist"
2276 (plist-get info :back-end)))))
2277 (when (boundp back-end-filters)
2278 (mapc (lambda (p)
2279 ;; Single values get consed, lists are prepended.
2280 (let ((key (car p)) (value (cdr p)))
2281 (when value
2282 (setq plist
2283 (plist-put
2284 plist key
2285 (if (atom value) (cons value (plist-get plist key))
2286 (append value (plist-get plist key))))))))
2287 (eval back-end-filters))))
2288 ;; Return new communication channel.
2289 (org-combine-plists info plist)))
2291 (defun org-export-set-element (old new)
2292 "Replace element or object OLD with element or object NEW.
2293 The function takes care of setting `:parent' property for NEW."
2294 ;; OLD can belong to the contents of PARENT or to its secondary
2295 ;; string.
2296 (let* ((parent (org-element-property :parent old))
2297 (sec-loc (cdr (assq (org-element-type parent)
2298 org-element-secondary-value-alist)))
2299 (sec-value (and sec-loc (org-element-property sec-loc parent)))
2300 (place (or (member old sec-value) (member old parent))))
2301 ;; Ensure NEW has correct parent. Then replace OLD with NEW.
2302 (let ((props (nth 1 new)))
2303 (if props (plist-put props :parent parent)
2304 (setcar (cdr new) `(:parent ,parent))))
2305 (setcar place new)))
2309 ;;; Core functions
2311 ;; This is the room for the main function, `org-export-as', along with
2312 ;; its derivatives, `org-export-to-buffer' and `org-export-to-file'.
2313 ;; They differ only by the way they output the resulting code.
2315 ;; `org-export-output-file-name' is an auxiliary function meant to be
2316 ;; used with `org-export-to-file'. With a given extension, it tries
2317 ;; to provide a canonical file name to write export output to.
2319 ;; Note that `org-export-as' doesn't really parse the current buffer,
2320 ;; but a copy of it (with the same buffer-local variables and
2321 ;; visibility), where include keywords are expanded and Babel blocks
2322 ;; are executed, if appropriate.
2323 ;; `org-export-with-current-buffer-copy' macro prepares that copy.
2325 ;; File inclusion is taken care of by
2326 ;; `org-export-expand-include-keyword' and
2327 ;; `org-export-prepare-file-contents'. Structure wise, including
2328 ;; a whole Org file in a buffer often makes little sense. For
2329 ;; example, if the file contains an headline and the include keyword
2330 ;; was within an item, the item should contain the headline. That's
2331 ;; why file inclusion should be done before any structure can be
2332 ;; associated to the file, that is before parsing.
2334 (defvar org-current-export-file) ; Dynamically scoped
2335 (defvar org-export-current-backend) ; Dynamically scoped
2336 (defun org-export-as
2337 (backend &optional subtreep visible-only body-only ext-plist noexpand)
2338 "Transcode current Org buffer into BACKEND code.
2340 If narrowing is active in the current buffer, only transcode its
2341 narrowed part.
2343 If a region is active, transcode that region.
2345 When optional argument SUBTREEP is non-nil, transcode the
2346 sub-tree at point, extracting information from the headline
2347 properties first.
2349 When optional argument VISIBLE-ONLY is non-nil, don't export
2350 contents of hidden elements.
2352 When optional argument BODY-ONLY is non-nil, only return body
2353 code, without preamble nor postamble.
2355 Optional argument EXT-PLIST, when provided, is a property list
2356 with external parameters overriding Org default settings, but
2357 still inferior to file-local settings.
2359 Optional argument NOEXPAND, when non-nil, prevents included files
2360 to be expanded and Babel code to be executed.
2362 Return code as a string."
2363 (save-excursion
2364 (save-restriction
2365 ;; Narrow buffer to an appropriate region or subtree for
2366 ;; parsing. If parsing subtree, be sure to remove main headline
2367 ;; too.
2368 (cond ((org-region-active-p)
2369 (narrow-to-region (region-beginning) (region-end)))
2370 (subtreep
2371 (org-narrow-to-subtree)
2372 (goto-char (point-min))
2373 (forward-line)
2374 (narrow-to-region (point) (point-max))))
2375 ;; 1. Get export environment from original buffer. Also install
2376 ;; user's and developer's filters.
2377 (let ((info (org-export-install-filters
2378 (org-export-get-environment backend subtreep ext-plist)))
2379 ;; 2. Get parse tree. Buffer isn't parsed directly.
2380 ;; Instead, a temporary copy is created, where include
2381 ;; keywords are expanded and code blocks are evaluated.
2382 (tree (let ((buf (or (buffer-file-name (buffer-base-buffer))
2383 (current-buffer))))
2384 (org-export-with-current-buffer-copy
2385 (unless noexpand
2386 (org-export-expand-include-keyword)
2387 ;; Setting `org-current-export-file' is
2388 ;; required by Org Babel to properly resolve
2389 ;; noweb references.
2390 (let ((org-current-export-file buf))
2391 (org-export-blocks-preprocess)))
2392 (goto-char (point-min))
2393 ;; Run hook with `org-export-current-backend' set
2394 ;; to BACKEND.
2395 (let ((org-export-current-backend backend))
2396 (run-hooks 'org-export-before-parsing-hook))
2397 ;; Eventually parse buffer.
2398 (org-element-parse-buffer nil visible-only)))))
2399 ;; 3. Call parse-tree filters to get the final tree.
2400 (setq tree
2401 (org-export-filter-apply-functions
2402 (plist-get info :filter-parse-tree) tree info))
2403 ;; 4. Now tree is complete, compute its properties and add
2404 ;; them to communication channel.
2405 (setq info
2406 (org-combine-plists
2407 info (org-export-collect-tree-properties tree info)))
2408 ;; 5. Eventually transcode TREE. Wrap the resulting string
2409 ;; into a template, if required. Eventually call
2410 ;; final-output filter.
2411 (let* ((body (org-element-normalize-string (org-export-data tree info)))
2412 (template (cdr (assq 'template
2413 (plist-get info :translate-alist))))
2414 (output (org-export-filter-apply-functions
2415 (plist-get info :filter-final-output)
2416 (if (or (not (fboundp template)) body-only) body
2417 (funcall template body info))
2418 info)))
2419 ;; Maybe add final OUTPUT to kill ring, then return it.
2420 (when org-export-copy-to-kill-ring (org-kill-new output))
2421 output)))))
2423 (defun org-export-to-buffer
2424 (backend buffer &optional subtreep visible-only body-only ext-plist noexpand)
2425 "Call `org-export-as' with output to a specified buffer.
2427 BACKEND is the back-end used for transcoding, as a symbol.
2429 BUFFER is the output buffer. If it already exists, it will be
2430 erased first, otherwise, it will be created.
2432 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY, EXT-PLIST
2433 and NOEXPAND are similar to those used in `org-export-as', which
2434 see.
2436 Return buffer."
2437 (let ((out (org-export-as
2438 backend subtreep visible-only body-only ext-plist noexpand))
2439 (buffer (get-buffer-create buffer)))
2440 (with-current-buffer buffer
2441 (erase-buffer)
2442 (insert out)
2443 (goto-char (point-min)))
2444 buffer))
2446 (defun org-export-to-file
2447 (backend file &optional subtreep visible-only body-only ext-plist noexpand)
2448 "Call `org-export-as' with output to a specified file.
2450 BACKEND is the back-end used for transcoding, as a symbol. FILE
2451 is the name of the output file, as a string.
2453 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY, EXT-PLIST
2454 and NOEXPAND are similar to those used in `org-export-as', which
2455 see.
2457 Return output file's name."
2458 ;; Checks for FILE permissions. `write-file' would do the same, but
2459 ;; we'd rather avoid needless transcoding of parse tree.
2460 (unless (file-writable-p file) (error "Output file not writable"))
2461 ;; Insert contents to a temporary buffer and write it to FILE.
2462 (let ((out (org-export-as
2463 backend subtreep visible-only body-only ext-plist noexpand)))
2464 (with-temp-buffer
2465 (insert out)
2466 (let ((coding-system-for-write org-export-coding-system))
2467 (write-file file))))
2468 ;; Return full path.
2469 file)
2471 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
2472 "Return output file's name according to buffer specifications.
2474 EXTENSION is a string representing the output file extension,
2475 with the leading dot.
2477 With a non-nil optional argument SUBTREEP, try to determine
2478 output file's name by looking for \"EXPORT_FILE_NAME\" property
2479 of subtree at point.
2481 When optional argument PUB-DIR is set, use it as the publishing
2482 directory.
2484 When optional argument VISIBLE-ONLY is non-nil, don't export
2485 contents of hidden elements.
2487 Return file name as a string, or nil if it couldn't be
2488 determined."
2489 (let ((base-name
2490 ;; File name may come from EXPORT_FILE_NAME subtree property,
2491 ;; assuming point is at beginning of said sub-tree.
2492 (file-name-sans-extension
2493 (or (and subtreep
2494 (org-entry-get
2495 (save-excursion
2496 (ignore-errors (org-back-to-heading) (point)))
2497 "EXPORT_FILE_NAME" t))
2498 ;; File name may be extracted from buffer's associated
2499 ;; file, if any.
2500 (buffer-file-name (buffer-base-buffer))
2501 ;; Can't determine file name on our own: Ask user.
2502 (let ((read-file-name-function
2503 (and org-completion-use-ido 'ido-read-file-name)))
2504 (read-file-name
2505 "Output file: " pub-dir nil nil nil
2506 (lambda (name)
2507 (string= (file-name-extension name t) extension))))))))
2508 ;; Build file name. Enforce EXTENSION over whatever user may have
2509 ;; come up with. PUB-DIR, if defined, always has precedence over
2510 ;; any provided path.
2511 (cond
2512 (pub-dir
2513 (concat (file-name-as-directory pub-dir)
2514 (file-name-nondirectory base-name)
2515 extension))
2516 ((string= (file-name-nondirectory base-name) base-name)
2517 (concat (file-name-as-directory ".") base-name extension))
2518 (t (concat base-name extension)))))
2520 (defmacro org-export-with-current-buffer-copy (&rest body)
2521 "Apply BODY in a copy of the current buffer.
2523 The copy preserves local variables and visibility of the original
2524 buffer.
2526 Point is at buffer's beginning when BODY is applied."
2527 (org-with-gensyms (original-buffer offset buffer-string overlays)
2528 `(let ((,original-buffer (current-buffer))
2529 (,offset (1- (point-min)))
2530 (,buffer-string (buffer-string))
2531 (,overlays (mapcar
2532 'copy-overlay (overlays-in (point-min) (point-max)))))
2533 (with-temp-buffer
2534 (let ((buffer-invisibility-spec nil))
2535 (org-clone-local-variables
2536 ,original-buffer
2537 "^\\(org-\\|orgtbl-\\|major-mode$\\|outline-\\(regexp\\|level\\)$\\)")
2538 (insert ,buffer-string)
2539 (mapc (lambda (ov)
2540 (move-overlay
2542 (- (overlay-start ov) ,offset)
2543 (- (overlay-end ov) ,offset)
2544 (current-buffer)))
2545 ,overlays)
2546 (goto-char (point-min))
2547 (progn ,@body))))))
2548 (def-edebug-spec org-export-with-current-buffer-copy (body))
2550 (defun org-export-expand-include-keyword (&optional included dir)
2551 "Expand every include keyword in buffer.
2552 Optional argument INCLUDED is a list of included file names along
2553 with their line restriction, when appropriate. It is used to
2554 avoid infinite recursion. Optional argument DIR is the current
2555 working directory. It is used to properly resolve relative
2556 paths."
2557 (let ((case-fold-search t))
2558 (goto-char (point-min))
2559 (while (re-search-forward "^[ \t]*#\\+INCLUDE: \\(.*\\)" nil t)
2560 (when (eq (org-element-type (save-match-data (org-element-at-point)))
2561 'keyword)
2562 (beginning-of-line)
2563 ;; Extract arguments from keyword's value.
2564 (let* ((value (match-string 1))
2565 (ind (org-get-indentation))
2566 (file (and (string-match "^\"\\(\\S-+\\)\"" value)
2567 (prog1 (expand-file-name (match-string 1 value) dir)
2568 (setq value (replace-match "" nil nil value)))))
2569 (lines
2570 (and (string-match
2571 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\"" value)
2572 (prog1 (match-string 1 value)
2573 (setq value (replace-match "" nil nil value)))))
2574 (env (cond ((string-match "\\<example\\>" value) 'example)
2575 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
2576 (match-string 1 value))))
2577 ;; Minimal level of included file defaults to the child
2578 ;; level of the current headline, if any, or one. It
2579 ;; only applies is the file is meant to be included as
2580 ;; an Org one.
2581 (minlevel
2582 (and (not env)
2583 (if (string-match ":minlevel +\\([0-9]+\\)" value)
2584 (prog1 (string-to-number (match-string 1 value))
2585 (setq value (replace-match "" nil nil value)))
2586 (let ((cur (org-current-level)))
2587 (if cur (1+ (org-reduced-level cur)) 1))))))
2588 ;; Remove keyword.
2589 (delete-region (point) (progn (forward-line) (point)))
2590 (cond
2591 ((not (file-readable-p file)) (error "Cannot include file %s" file))
2592 ;; Check if files has already been parsed. Look after
2593 ;; inclusion lines too, as different parts of the same file
2594 ;; can be included too.
2595 ((member (list file lines) included)
2596 (error "Recursive file inclusion: %s" file))
2598 (cond
2599 ((eq env 'example)
2600 (insert
2601 (let ((ind-str (make-string ind ? ))
2602 (contents
2603 ;; Protect sensitive contents with commas.
2604 (replace-regexp-in-string
2605 "\\(^\\)\\([*]\\|[ \t]*#\\+\\)" ","
2606 (org-export-prepare-file-contents file lines)
2607 nil nil 1)))
2608 (format "%s#+BEGIN_EXAMPLE\n%s%s#+END_EXAMPLE\n"
2609 ind-str contents ind-str))))
2610 ((stringp env)
2611 (insert
2612 (let ((ind-str (make-string ind ? ))
2613 (contents
2614 ;; Protect sensitive contents with commas.
2615 (replace-regexp-in-string
2616 (if (string= env "org") "\\(^\\)\\(.\\)"
2617 "\\(^\\)\\([*]\\|[ \t]*#\\+\\)") ","
2618 (org-export-prepare-file-contents file lines)
2619 nil nil 1)))
2620 (format "%s#+BEGIN_SRC %s\n%s%s#+END_SRC\n"
2621 ind-str env contents ind-str))))
2623 (insert
2624 (with-temp-buffer
2625 (org-mode)
2626 (insert
2627 (org-export-prepare-file-contents file lines ind minlevel))
2628 (org-export-expand-include-keyword
2629 (cons (list file lines) included)
2630 (file-name-directory file))
2631 (buffer-string))))))))))))
2633 (defun org-export-prepare-file-contents (file &optional lines ind minlevel)
2634 "Prepare the contents of FILE for inclusion and return them as a string.
2636 When optional argument LINES is a string specifying a range of
2637 lines, include only those lines.
2639 Optional argument IND, when non-nil, is an integer specifying the
2640 global indentation of returned contents. Since its purpose is to
2641 allow an included file to stay in the same environment it was
2642 created \(i.e. a list item), it doesn't apply past the first
2643 headline encountered.
2645 Optional argument MINLEVEL, when non-nil, is an integer
2646 specifying the level that any top-level headline in the included
2647 file should have."
2648 (with-temp-buffer
2649 (insert-file-contents file)
2650 (when lines
2651 (let* ((lines (split-string lines "-"))
2652 (lbeg (string-to-number (car lines)))
2653 (lend (string-to-number (cadr lines)))
2654 (beg (if (zerop lbeg) (point-min)
2655 (goto-char (point-min))
2656 (forward-line (1- lbeg))
2657 (point)))
2658 (end (if (zerop lend) (point-max)
2659 (goto-char (point-min))
2660 (forward-line (1- lend))
2661 (point))))
2662 (narrow-to-region beg end)))
2663 ;; Remove blank lines at beginning and end of contents. The logic
2664 ;; behind that removal is that blank lines around include keyword
2665 ;; override blank lines in included file.
2666 (goto-char (point-min))
2667 (org-skip-whitespace)
2668 (beginning-of-line)
2669 (delete-region (point-min) (point))
2670 (goto-char (point-max))
2671 (skip-chars-backward " \r\t\n")
2672 (forward-line)
2673 (delete-region (point) (point-max))
2674 ;; If IND is set, preserve indentation of include keyword until
2675 ;; the first headline encountered.
2676 (when ind
2677 (unless (eq major-mode 'org-mode) (org-mode))
2678 (goto-char (point-min))
2679 (let ((ind-str (make-string ind ? )))
2680 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
2681 ;; Do not move footnote definitions out of column 0.
2682 (unless (and (looking-at org-footnote-definition-re)
2683 (eq (org-element-type (org-element-at-point))
2684 'footnote-definition))
2685 (insert ind-str))
2686 (forward-line))))
2687 ;; When MINLEVEL is specified, compute minimal level for headlines
2688 ;; in the file (CUR-MIN), and remove stars to each headline so
2689 ;; that headlines with minimal level have a level of MINLEVEL.
2690 (when minlevel
2691 (unless (eq major-mode 'org-mode) (org-mode))
2692 (let ((levels (org-map-entries
2693 (lambda () (org-reduced-level (org-current-level))))))
2694 (when levels
2695 (let ((offset (- minlevel (apply 'min levels))))
2696 (unless (zerop offset)
2697 (when org-odd-levels-only (setq offset (* offset 2)))
2698 ;; Only change stars, don't bother moving whole
2699 ;; sections.
2700 (org-map-entries
2701 (lambda () (if (< offset 0) (delete-char (abs offset))
2702 (insert (make-string offset ?*))))))))))
2703 (buffer-string)))
2706 ;;; Tools For Back-Ends
2708 ;; A whole set of tools is available to help build new exporters. Any
2709 ;; function general enough to have its use across many back-ends
2710 ;; should be added here.
2712 ;; As of now, functions operating on footnotes, headlines, links,
2713 ;; macros, references, src-blocks, tables and tables of contents are
2714 ;; implemented.
2716 ;;;; For Affiliated Keywords
2718 ;; `org-export-read-attribute' reads a property from a given element
2719 ;; as a plist. It can be used to normalize affiliated keywords'
2720 ;; syntax.
2722 (defun org-export-read-attribute (attribute element)
2723 "Turn ATTRIBUTE property from ELEMENT into a plist.
2724 This function assumes attributes are defined as \":keyword
2725 value\" pairs. It is appropriate for `:attr_html' like
2726 properties."
2727 (let ((value (org-element-property attribute element)))
2728 (and value
2729 (read (format "(%s)" (mapconcat 'identity value " "))))))
2732 ;;;; For Export Snippets
2734 ;; Every export snippet is transmitted to the back-end. Though, the
2735 ;; latter will only retain one type of export-snippet, ignoring
2736 ;; others, based on the former's target back-end. The function
2737 ;; `org-export-snippet-backend' returns that back-end for a given
2738 ;; export-snippet.
2740 (defun org-export-snippet-backend (export-snippet)
2741 "Return EXPORT-SNIPPET targeted back-end as a symbol.
2742 Translation, with `org-export-snippet-translation-alist', is
2743 applied."
2744 (let ((back-end (org-element-property :back-end export-snippet)))
2745 (intern
2746 (or (cdr (assoc back-end org-export-snippet-translation-alist))
2747 back-end))))
2750 ;;;; For Footnotes
2752 ;; `org-export-collect-footnote-definitions' is a tool to list
2753 ;; actually used footnotes definitions in the whole parse tree, or in
2754 ;; an headline, in order to add footnote listings throughout the
2755 ;; transcoded data.
2757 ;; `org-export-footnote-first-reference-p' is a predicate used by some
2758 ;; back-ends, when they need to attach the footnote definition only to
2759 ;; the first occurrence of the corresponding label.
2761 ;; `org-export-get-footnote-definition' and
2762 ;; `org-export-get-footnote-number' provide easier access to
2763 ;; additional information relative to a footnote reference.
2765 (defun org-export-collect-footnote-definitions (data info)
2766 "Return an alist between footnote numbers, labels and definitions.
2768 DATA is the parse tree from which definitions are collected.
2769 INFO is the plist used as a communication channel.
2771 Definitions are sorted by order of references. They either
2772 appear as Org data or as a secondary string for inlined
2773 footnotes. Unreferenced definitions are ignored."
2774 (let* (num-alist
2775 collect-fn ; for byte-compiler.
2776 (collect-fn
2777 (function
2778 (lambda (data)
2779 ;; Collect footnote number, label and definition in DATA.
2780 (org-element-map
2781 data 'footnote-reference
2782 (lambda (fn)
2783 (when (org-export-footnote-first-reference-p fn info)
2784 (let ((def (org-export-get-footnote-definition fn info)))
2785 (push
2786 (list (org-export-get-footnote-number fn info)
2787 (org-element-property :label fn)
2788 def)
2789 num-alist)
2790 ;; Also search in definition for nested footnotes.
2791 (when (eq (org-element-property :type fn) 'standard)
2792 (funcall collect-fn def)))))
2793 ;; Don't enter footnote definitions since it will happen
2794 ;; when their first reference is found.
2795 info nil 'footnote-definition)))))
2796 (funcall collect-fn (plist-get info :parse-tree))
2797 (reverse num-alist)))
2799 (defun org-export-footnote-first-reference-p (footnote-reference info)
2800 "Non-nil when a footnote reference is the first one for its label.
2802 FOOTNOTE-REFERENCE is the footnote reference being considered.
2803 INFO is the plist used as a communication channel."
2804 (let ((label (org-element-property :label footnote-reference)))
2805 ;; Anonymous footnotes are always a first reference.
2806 (if (not label) t
2807 ;; Otherwise, return the first footnote with the same LABEL and
2808 ;; test if it is equal to FOOTNOTE-REFERENCE.
2809 (let* (search-refs ; for byte-compiler.
2810 (search-refs
2811 (function
2812 (lambda (data)
2813 (org-element-map
2814 data 'footnote-reference
2815 (lambda (fn)
2816 (cond
2817 ((string= (org-element-property :label fn) label)
2818 (throw 'exit fn))
2819 ;; If FN isn't inlined, be sure to traverse its
2820 ;; definition before resuming search. See
2821 ;; comments in `org-export-get-footnote-number'
2822 ;; for more information.
2823 ((eq (org-element-property :type fn) 'standard)
2824 (funcall search-refs
2825 (org-export-get-footnote-definition fn info)))))
2826 ;; Don't enter footnote definitions since it will
2827 ;; happen when their first reference is found.
2828 info 'first-match 'footnote-definition)))))
2829 (equal (catch 'exit (funcall search-refs (plist-get info :parse-tree)))
2830 footnote-reference)))))
2832 (defun org-export-get-footnote-definition (footnote-reference info)
2833 "Return definition of FOOTNOTE-REFERENCE as parsed data.
2834 INFO is the plist used as a communication channel."
2835 (let ((label (org-element-property :label footnote-reference)))
2836 (or (org-element-property :inline-definition footnote-reference)
2837 (cdr (assoc label (plist-get info :footnote-definition-alist))))))
2839 (defun org-export-get-footnote-number (footnote info)
2840 "Return number associated to a footnote.
2842 FOOTNOTE is either a footnote reference or a footnote definition.
2843 INFO is the plist used as a communication channel."
2844 (let* ((label (org-element-property :label footnote))
2845 seen-refs
2846 search-ref ; for byte-compiler.
2847 (search-ref
2848 (function
2849 (lambda (data)
2850 ;; Search footnote references through DATA, filling
2851 ;; SEEN-REFS along the way.
2852 (org-element-map
2853 data 'footnote-reference
2854 (lambda (fn)
2855 (let ((fn-lbl (org-element-property :label fn)))
2856 (cond
2857 ;; Anonymous footnote match: return number.
2858 ((and (not fn-lbl) (equal fn footnote))
2859 (throw 'exit (1+ (length seen-refs))))
2860 ;; Labels match: return number.
2861 ((and label (string= label fn-lbl))
2862 (throw 'exit (1+ (length seen-refs))))
2863 ;; Anonymous footnote: it's always a new one. Also,
2864 ;; be sure to return nil from the `cond' so
2865 ;; `first-match' doesn't get us out of the loop.
2866 ((not fn-lbl) (push 'inline seen-refs) nil)
2867 ;; Label not seen so far: add it so SEEN-REFS.
2869 ;; Also search for subsequent references in footnote
2870 ;; definition so numbering following reading logic.
2871 ;; Note that we don't have to care about inline
2872 ;; definitions, since `org-element-map' already
2873 ;; traverse them at the right time.
2875 ;; Once again, return nil to stay in the loop.
2876 ((not (member fn-lbl seen-refs))
2877 (push fn-lbl seen-refs)
2878 (funcall search-ref
2879 (org-export-get-footnote-definition fn info))
2880 nil))))
2881 ;; Don't enter footnote definitions since it will happen
2882 ;; when their first reference is found.
2883 info 'first-match 'footnote-definition)))))
2884 (catch 'exit (funcall search-ref (plist-get info :parse-tree)))))
2887 ;;;; For Headlines
2889 ;; `org-export-get-relative-level' is a shortcut to get headline
2890 ;; level, relatively to the lower headline level in the parsed tree.
2892 ;; `org-export-get-headline-number' returns the section number of an
2893 ;; headline, while `org-export-number-to-roman' allows to convert it
2894 ;; to roman numbers.
2896 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
2897 ;; `org-export-last-sibling-p' are three useful predicates when it
2898 ;; comes to fulfill the `:headline-levels' property.
2900 (defun org-export-get-relative-level (headline info)
2901 "Return HEADLINE relative level within current parsed tree.
2902 INFO is a plist holding contextual information."
2903 (+ (org-element-property :level headline)
2904 (or (plist-get info :headline-offset) 0)))
2906 (defun org-export-low-level-p (headline info)
2907 "Non-nil when HEADLINE is considered as low level.
2909 INFO is a plist used as a communication channel.
2911 A low level headlines has a relative level greater than
2912 `:headline-levels' property value.
2914 Return value is the difference between HEADLINE relative level
2915 and the last level being considered as high enough, or nil."
2916 (let ((limit (plist-get info :headline-levels)))
2917 (when (wholenump limit)
2918 (let ((level (org-export-get-relative-level headline info)))
2919 (and (> level limit) (- level limit))))))
2921 (defun org-export-get-headline-number (headline info)
2922 "Return HEADLINE numbering as a list of numbers.
2923 INFO is a plist holding contextual information."
2924 (cdr (assoc headline (plist-get info :headline-numbering))))
2926 (defun org-export-numbered-headline-p (headline info)
2927 "Return a non-nil value if HEADLINE element should be numbered.
2928 INFO is a plist used as a communication channel."
2929 (let ((sec-num (plist-get info :section-numbers))
2930 (level (org-export-get-relative-level headline info)))
2931 (if (wholenump sec-num) (<= level sec-num) sec-num)))
2933 (defun org-export-number-to-roman (n)
2934 "Convert integer N into a roman numeral."
2935 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
2936 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
2937 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
2938 ( 1 . "I")))
2939 (res ""))
2940 (if (<= n 0)
2941 (number-to-string n)
2942 (while roman
2943 (if (>= n (caar roman))
2944 (setq n (- n (caar roman))
2945 res (concat res (cdar roman)))
2946 (pop roman)))
2947 res)))
2949 (defun org-export-get-tags (element info &optional tags)
2950 "Return list of tags associated to ELEMENT.
2952 ELEMENT has either an `headline' or an `inlinetask' type. INFO
2953 is a plist used as a communication channel.
2955 Select tags (see `org-export-select-tags') and exclude tags (see
2956 `org-export-exclude-tags') are removed from the list.
2958 When non-nil, optional argument TAGS should be a list of strings.
2959 Any tag belonging to this list will also be removed."
2960 (org-remove-if (lambda (tag) (or (member tag (plist-get info :select-tags))
2961 (member tag (plist-get info :exclude-tags))
2962 (member tag tags)))
2963 (org-element-property :tags element)))
2965 (defun org-export-first-sibling-p (headline)
2966 "Non-nil when HEADLINE is the first sibling in its sub-tree."
2967 (not (eq (org-element-type (org-export-get-previous-element headline))
2968 'headline)))
2970 (defun org-export-last-sibling-p (headline)
2971 "Non-nil when HEADLINE is the last sibling in its sub-tree."
2972 (not (org-export-get-next-element headline)))
2975 ;;;; For Links
2977 ;; `org-export-solidify-link-text' turns a string into a safer version
2978 ;; for links, replacing most non-standard characters with hyphens.
2980 ;; `org-export-get-coderef-format' returns an appropriate format
2981 ;; string for coderefs.
2983 ;; `org-export-inline-image-p' returns a non-nil value when the link
2984 ;; provided should be considered as an inline image.
2986 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
2987 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
2988 ;; returns an appropriate unique identifier when found, or nil.
2990 ;; `org-export-resolve-id-link' returns the first headline with
2991 ;; specified id or custom-id in parse tree, the path to the external
2992 ;; file with the id or nil when neither was found.
2994 ;; `org-export-resolve-coderef' associates a reference to a line
2995 ;; number in the element it belongs, or returns the reference itself
2996 ;; when the element isn't numbered.
2998 (defun org-export-solidify-link-text (s)
2999 "Take link text S and make a safe target out of it."
3000 (save-match-data
3001 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-]+") "-")))
3003 (defun org-export-get-coderef-format (path desc)
3004 "Return format string for code reference link.
3005 PATH is the link path. DESC is its description."
3006 (save-match-data
3007 (cond ((not desc) "%s")
3008 ((string-match (regexp-quote (concat "(" path ")")) desc)
3009 (replace-match "%s" t t desc))
3010 (t desc))))
3012 (defun org-export-inline-image-p (link &optional rules)
3013 "Non-nil if LINK object points to an inline image.
3015 Optional argument is a set of RULES defining inline images. It
3016 is an alist where associations have the following shape:
3018 \(TYPE . REGEXP)
3020 Applying a rule means apply REGEXP against LINK's path when its
3021 type is TYPE. The function will return a non-nil value if any of
3022 the provided rules is non-nil. The default rule is
3023 `org-export-default-inline-image-rule'.
3025 This only applies to links without a description."
3026 (and (not (org-element-contents link))
3027 (let ((case-fold-search t)
3028 (rules (or rules org-export-default-inline-image-rule)))
3029 (catch 'exit
3030 (mapc
3031 (lambda (rule)
3032 (and (string= (org-element-property :type link) (car rule))
3033 (string-match (cdr rule)
3034 (org-element-property :path link))
3035 (throw 'exit t)))
3036 rules)
3037 ;; Return nil if no rule matched.
3038 nil))))
3040 (defun org-export-resolve-coderef (ref info)
3041 "Resolve a code reference REF.
3043 INFO is a plist used as a communication channel.
3045 Return associated line number in source code, or REF itself,
3046 depending on src-block or example element's switches."
3047 (org-element-map
3048 (plist-get info :parse-tree) '(example-block src-block)
3049 (lambda (el)
3050 (with-temp-buffer
3051 (insert (org-trim (org-element-property :value el)))
3052 (let* ((label-fmt (regexp-quote
3053 (or (org-element-property :label-fmt el)
3054 org-coderef-label-format)))
3055 (ref-re
3056 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
3057 (replace-regexp-in-string "%s" ref label-fmt nil t))))
3058 ;; Element containing REF is found. Resolve it to either
3059 ;; a label or a line number, as needed.
3060 (when (re-search-backward ref-re nil t)
3061 (cond
3062 ((org-element-property :use-labels el) ref)
3063 ((eq (org-element-property :number-lines el) 'continued)
3064 (+ (org-export-get-loc el info) (line-number-at-pos)))
3065 (t (line-number-at-pos)))))))
3066 info 'first-match))
3068 (defun org-export-resolve-fuzzy-link (link info)
3069 "Return LINK destination.
3071 INFO is a plist holding contextual information.
3073 Return value can be an object, an element, or nil:
3075 - If LINK path matches a target object (i.e. <<path>>) or
3076 element (i.e. \"#+TARGET: path\"), return it.
3078 - If LINK path exactly matches the name affiliated keyword
3079 \(i.e. #+NAME: path) of an element, return that element.
3081 - If LINK path exactly matches any headline name, return that
3082 element. If more than one headline share that name, priority
3083 will be given to the one with the closest common ancestor, if
3084 any, or the first one in the parse tree otherwise.
3086 - Otherwise, return nil.
3088 Assume LINK type is \"fuzzy\"."
3089 (let* ((path (org-element-property :path link))
3090 (match-title-p (eq (aref path 0) ?*)))
3091 (cond
3092 ;; First try to find a matching "<<path>>" unless user specified
3093 ;; he was looking for an headline (path starts with a *
3094 ;; character).
3095 ((and (not match-title-p)
3096 (loop for target in (plist-get info :target-list)
3097 when (string= (org-element-property :value target) path)
3098 return target)))
3099 ;; Then try to find an element with a matching "#+NAME: path"
3100 ;; affiliated keyword.
3101 ((and (not match-title-p)
3102 (org-element-map
3103 (plist-get info :parse-tree) org-element-all-elements
3104 (lambda (el)
3105 (when (string= (org-element-property :name el) path) el))
3106 info 'first-match)))
3107 ;; Last case: link either points to an headline or to
3108 ;; nothingness. Try to find the source, with priority given to
3109 ;; headlines with the closest common ancestor. If such candidate
3110 ;; is found, return it, otherwise return nil.
3112 (let ((find-headline
3113 (function
3114 ;; Return first headline whose `:raw-value' property
3115 ;; is NAME in parse tree DATA, or nil.
3116 (lambda (name data)
3117 (org-element-map
3118 data 'headline
3119 (lambda (headline)
3120 (when (string=
3121 (org-element-property :raw-value headline)
3122 name)
3123 headline))
3124 info 'first-match)))))
3125 ;; Search among headlines sharing an ancestor with link,
3126 ;; from closest to farthest.
3127 (or (catch 'exit
3128 (mapc
3129 (lambda (parent)
3130 (when (eq (org-element-type parent) 'headline)
3131 (let ((foundp (funcall find-headline path parent)))
3132 (when foundp (throw 'exit foundp)))))
3133 (org-export-get-genealogy link)) nil)
3134 ;; No match with a common ancestor: try the full parse-tree.
3135 (funcall find-headline
3136 (if match-title-p (substring path 1) path)
3137 (plist-get info :parse-tree))))))))
3139 (defun org-export-resolve-id-link (link info)
3140 "Return headline referenced as LINK destination.
3142 INFO is a plist used as a communication channel.
3144 Return value can be the headline element matched in current parse
3145 tree, a file name or nil. Assume LINK type is either \"id\" or
3146 \"custom-id\"."
3147 (let ((id (org-element-property :path link)))
3148 ;; First check if id is within the current parse tree.
3149 (or (org-element-map
3150 (plist-get info :parse-tree) 'headline
3151 (lambda (headline)
3152 (when (or (string= (org-element-property :id headline) id)
3153 (string= (org-element-property :custom-id headline) id))
3154 headline))
3155 info 'first-match)
3156 ;; Otherwise, look for external files.
3157 (cdr (assoc id (plist-get info :id-alist))))))
3159 (defun org-export-resolve-radio-link (link info)
3160 "Return radio-target object referenced as LINK destination.
3162 INFO is a plist used as a communication channel.
3164 Return value can be a radio-target object or nil. Assume LINK
3165 has type \"radio\"."
3166 (let ((path (org-element-property :path link)))
3167 (org-element-map
3168 (plist-get info :parse-tree) 'radio-target
3169 (lambda (radio)
3170 (when (equal (org-element-property :value radio) path) radio))
3171 info 'first-match)))
3174 ;;;; For Macros
3176 ;; `org-export-expand-macro' simply takes care of expanding macros.
3178 (defun org-export-expand-macro (macro info)
3179 "Expand MACRO and return it as a string.
3180 INFO is a plist holding export options."
3181 (let* ((key (org-element-property :key macro))
3182 (args (org-element-property :args macro))
3183 ;; User's macros are stored in the communication channel with
3184 ;; a ":macro-" prefix. Replace arguments in VALUE. Also
3185 ;; expand recursively macros within.
3186 (value (org-export-data
3187 (mapcar
3188 (lambda (obj)
3189 (if (not (stringp obj)) (org-export-data obj info)
3190 (replace-regexp-in-string
3191 "\\$[0-9]+"
3192 (lambda (arg)
3193 (nth (1- (string-to-number (substring arg 1))) args))
3194 obj)))
3195 (plist-get info (intern (format ":macro-%s" key))))
3196 info)))
3197 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
3198 (when (string-match "\\`(eval\\>" value) (setq value (eval (read value))))
3199 ;; Return string.
3200 (format "%s" (or value ""))))
3203 ;;;; For References
3205 ;; `org-export-get-ordinal' associates a sequence number to any object
3206 ;; or element.
3208 (defun org-export-get-ordinal (element info &optional types predicate)
3209 "Return ordinal number of an element or object.
3211 ELEMENT is the element or object considered. INFO is the plist
3212 used as a communication channel.
3214 Optional argument TYPES, when non-nil, is a list of element or
3215 object types, as symbols, that should also be counted in.
3216 Otherwise, only provided element's type is considered.
3218 Optional argument PREDICATE is a function returning a non-nil
3219 value if the current element or object should be counted in. It
3220 accepts two arguments: the element or object being considered and
3221 the plist used as a communication channel. This allows to count
3222 only a certain type of objects (i.e. inline images).
3224 Return value is a list of numbers if ELEMENT is an headline or an
3225 item. It is nil for keywords. It represents the footnote number
3226 for footnote definitions and footnote references. If ELEMENT is
3227 a target, return the same value as if ELEMENT was the closest
3228 table, item or headline containing the target. In any other
3229 case, return the sequence number of ELEMENT among elements or
3230 objects of the same type."
3231 ;; A target keyword, representing an invisible target, never has
3232 ;; a sequence number.
3233 (unless (eq (org-element-type element) 'keyword)
3234 ;; Ordinal of a target object refer to the ordinal of the closest
3235 ;; table, item, or headline containing the object.
3236 (when (eq (org-element-type element) 'target)
3237 (setq element
3238 (loop for parent in (org-export-get-genealogy element)
3239 when
3240 (memq
3241 (org-element-type parent)
3242 '(footnote-definition footnote-reference headline item
3243 table))
3244 return parent)))
3245 (case (org-element-type element)
3246 ;; Special case 1: An headline returns its number as a list.
3247 (headline (org-export-get-headline-number element info))
3248 ;; Special case 2: An item returns its number as a list.
3249 (item (let ((struct (org-element-property :structure element)))
3250 (org-list-get-item-number
3251 (org-element-property :begin element)
3252 struct
3253 (org-list-prevs-alist struct)
3254 (org-list-parents-alist struct))))
3255 ((footnote-definition footnote-reference)
3256 (org-export-get-footnote-number element info))
3257 (otherwise
3258 (let ((counter 0))
3259 ;; Increment counter until ELEMENT is found again.
3260 (org-element-map
3261 (plist-get info :parse-tree) (or types (org-element-type element))
3262 (lambda (el)
3263 (cond
3264 ((equal element el) (1+ counter))
3265 ((not predicate) (incf counter) nil)
3266 ((funcall predicate el info) (incf counter) nil)))
3267 info 'first-match))))))
3270 ;;;; For Src-Blocks
3272 ;; `org-export-get-loc' counts number of code lines accumulated in
3273 ;; src-block or example-block elements with a "+n" switch until
3274 ;; a given element, excluded. Note: "-n" switches reset that count.
3276 ;; `org-export-unravel-code' extracts source code (along with a code
3277 ;; references alist) from an `element-block' or `src-block' type
3278 ;; element.
3280 ;; `org-export-format-code' applies a formatting function to each line
3281 ;; of code, providing relative line number and code reference when
3282 ;; appropriate. Since it doesn't access the original element from
3283 ;; which the source code is coming, it expects from the code calling
3284 ;; it to know if lines should be numbered and if code references
3285 ;; should appear.
3287 ;; Eventually, `org-export-format-code-default' is a higher-level
3288 ;; function (it makes use of the two previous functions) which handles
3289 ;; line numbering and code references inclusion, and returns source
3290 ;; code in a format suitable for plain text or verbatim output.
3292 (defun org-export-get-loc (element info)
3293 "Return accumulated lines of code up to ELEMENT.
3295 INFO is the plist used as a communication channel.
3297 ELEMENT is excluded from count."
3298 (let ((loc 0))
3299 (org-element-map
3300 (plist-get info :parse-tree)
3301 `(src-block example-block ,(org-element-type element))
3302 (lambda (el)
3303 (cond
3304 ;; ELEMENT is reached: Quit the loop.
3305 ((equal el element) t)
3306 ;; Only count lines from src-block and example-block elements
3307 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
3308 ((not (memq (org-element-type el) '(src-block example-block))) nil)
3309 ((let ((linums (org-element-property :number-lines el)))
3310 (when linums
3311 ;; Accumulate locs or reset them.
3312 (let ((lines (org-count-lines
3313 (org-trim (org-element-property :value el)))))
3314 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
3315 ;; Return nil to stay in the loop.
3316 nil)))
3317 info 'first-match)
3318 ;; Return value.
3319 loc))
3321 (defun org-export-unravel-code (element)
3322 "Clean source code and extract references out of it.
3324 ELEMENT has either a `src-block' an `example-block' type.
3326 Return a cons cell whose CAR is the source code, cleaned from any
3327 reference and protective comma and CDR is an alist between
3328 relative line number (integer) and name of code reference on that
3329 line (string)."
3330 (let* ((line 0) refs
3331 ;; Get code and clean it. Remove blank lines at its
3332 ;; beginning and end. Also remove protective commas.
3333 (code (let ((c (replace-regexp-in-string
3334 "\\`\\([ \t]*\n\\)+" ""
3335 (replace-regexp-in-string
3336 "\\(:?[ \t]*\n\\)*[ \t]*\\'" "\n"
3337 (org-element-property :value element)))))
3338 ;; If appropriate, remove global indentation.
3339 (unless (or org-src-preserve-indentation
3340 (org-element-property :preserve-indent element))
3341 (setq c (org-remove-indentation c)))
3342 ;; Free up the protected lines. Note: Org blocks
3343 ;; have commas at the beginning or every line.
3344 (if (string= (org-element-property :language element) "org")
3345 (replace-regexp-in-string "^," "" c)
3346 (replace-regexp-in-string
3347 "^\\(,\\)\\(:?\\*\\|[ \t]*#\\+\\)" "" c nil nil 1))))
3348 ;; Get format used for references.
3349 (label-fmt (regexp-quote
3350 (or (org-element-property :label-fmt element)
3351 org-coderef-label-format)))
3352 ;; Build a regexp matching a loc with a reference.
3353 (with-ref-re
3354 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
3355 (replace-regexp-in-string
3356 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
3357 ;; Return value.
3358 (cons
3359 ;; Code with references removed.
3360 (org-element-normalize-string
3361 (mapconcat
3362 (lambda (loc)
3363 (incf line)
3364 (if (not (string-match with-ref-re loc)) loc
3365 ;; Ref line: remove ref, and signal its position in REFS.
3366 (push (cons line (match-string 3 loc)) refs)
3367 (replace-match "" nil nil loc 1)))
3368 (org-split-string code "\n") "\n"))
3369 ;; Reference alist.
3370 refs)))
3372 (defun org-export-format-code (code fun &optional num-lines ref-alist)
3373 "Format CODE by applying FUN line-wise and return it.
3375 CODE is a string representing the code to format. FUN is
3376 a function. It must accept three arguments: a line of
3377 code (string), the current line number (integer) or nil and the
3378 reference associated to the current line (string) or nil.
3380 Optional argument NUM-LINES can be an integer representing the
3381 number of code lines accumulated until the current code. Line
3382 numbers passed to FUN will take it into account. If it is nil,
3383 FUN's second argument will always be nil. This number can be
3384 obtained with `org-export-get-loc' function.
3386 Optional argument REF-ALIST can be an alist between relative line
3387 number (i.e. ignoring NUM-LINES) and the name of the code
3388 reference on it. If it is nil, FUN's third argument will always
3389 be nil. It can be obtained through the use of
3390 `org-export-unravel-code' function."
3391 (let ((--locs (org-split-string code "\n"))
3392 (--line 0))
3393 (org-element-normalize-string
3394 (mapconcat
3395 (lambda (--loc)
3396 (incf --line)
3397 (let ((--ref (cdr (assq --line ref-alist))))
3398 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
3399 --locs "\n"))))
3401 (defun org-export-format-code-default (element info)
3402 "Return source code from ELEMENT, formatted in a standard way.
3404 ELEMENT is either a `src-block' or `example-block' element. INFO
3405 is a plist used as a communication channel.
3407 This function takes care of line numbering and code references
3408 inclusion. Line numbers, when applicable, appear at the
3409 beginning of the line, separated from the code by two white
3410 spaces. Code references, on the other hand, appear flushed to
3411 the right, separated by six white spaces from the widest line of
3412 code."
3413 ;; Extract code and references.
3414 (let* ((code-info (org-export-unravel-code element))
3415 (code (car code-info))
3416 (code-lines (org-split-string code "\n"))
3417 (refs (and (org-element-property :retain-labels element)
3418 (cdr code-info)))
3419 ;; Handle line numbering.
3420 (num-start (case (org-element-property :number-lines element)
3421 (continued (org-export-get-loc element info))
3422 (new 0)))
3423 (num-fmt
3424 (and num-start
3425 (format "%%%ds "
3426 (length (number-to-string
3427 (+ (length code-lines) num-start))))))
3428 ;; Prepare references display, if required. Any reference
3429 ;; should start six columns after the widest line of code,
3430 ;; wrapped with parenthesis.
3431 (max-width
3432 (+ (apply 'max (mapcar 'length code-lines))
3433 (if (not num-start) 0 (length (format num-fmt num-start))))))
3434 (org-export-format-code
3435 code
3436 (lambda (loc line-num ref)
3437 (let ((number-str (and num-fmt (format num-fmt line-num))))
3438 (concat
3439 number-str
3441 (and ref
3442 (concat (make-string
3443 (- (+ 6 max-width)
3444 (+ (length loc) (length number-str))) ? )
3445 (format "(%s)" ref))))))
3446 num-start refs)))
3449 ;;;; For Tables
3451 ;; `org-export-table-has-special-column-p' and and
3452 ;; `org-export-table-row-is-special-p' are predicates used to look for
3453 ;; meta-information about the table structure.
3455 ;; `org-table-has-header-p' tells when the rows before the first rule
3456 ;; should be considered as table's header.
3458 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
3459 ;; and `org-export-table-cell-borders' extract information from
3460 ;; a table-cell element.
3462 ;; `org-export-table-dimensions' gives the number on rows and columns
3463 ;; in the table, ignoring horizontal rules and special columns.
3464 ;; `org-export-table-cell-address', given a table-cell object, returns
3465 ;; the absolute address of a cell. On the other hand,
3466 ;; `org-export-get-table-cell-at' does the contrary.
3468 ;; `org-export-table-cell-starts-colgroup-p',
3469 ;; `org-export-table-cell-ends-colgroup-p',
3470 ;; `org-export-table-row-starts-rowgroup-p',
3471 ;; `org-export-table-row-ends-rowgroup-p',
3472 ;; `org-export-table-row-starts-header-p' and
3473 ;; `org-export-table-row-ends-header-p' indicate position of current
3474 ;; row or cell within the table.
3476 (defun org-export-table-has-special-column-p (table)
3477 "Non-nil when TABLE has a special column.
3478 All special columns will be ignored during export."
3479 ;; The table has a special column when every first cell of every row
3480 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
3481 ;; "*" "_" and "^". Though, do not consider a first row containing
3482 ;; only empty cells as special.
3483 (let ((special-column-p 'empty))
3484 (catch 'exit
3485 (mapc
3486 (lambda (row)
3487 (when (eq (org-element-property :type row) 'standard)
3488 (let ((value (org-element-contents
3489 (car (org-element-contents row)))))
3490 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
3491 (setq special-column-p 'special))
3492 ((not value))
3493 (t (throw 'exit nil))))))
3494 (org-element-contents table))
3495 (eq special-column-p 'special))))
3497 (defun org-export-table-has-header-p (table info)
3498 "Non-nil when TABLE has an header.
3500 INFO is a plist used as a communication channel.
3502 A table has an header when it contains at least two row groups."
3503 (let ((rowgroup 1) row-flag)
3504 (org-element-map
3505 table 'table-row
3506 (lambda (row)
3507 (cond
3508 ((> rowgroup 1) t)
3509 ((and row-flag (eq (org-element-property :type row) 'rule))
3510 (incf rowgroup) (setq row-flag nil))
3511 ((and (not row-flag) (eq (org-element-property :type row) 'standard))
3512 (setq row-flag t) nil)))
3513 info)))
3515 (defun org-export-table-row-is-special-p (table-row info)
3516 "Non-nil if TABLE-ROW is considered special.
3518 INFO is a plist used as the communication channel.
3520 All special rows will be ignored during export."
3521 (when (eq (org-element-property :type table-row) 'standard)
3522 (let ((first-cell (org-element-contents
3523 (car (org-element-contents table-row)))))
3524 ;; A row is special either when...
3526 ;; ... it starts with a field only containing "/",
3527 (equal first-cell '("/"))
3528 ;; ... the table contains a special column and the row start
3529 ;; with a marking character among, "^", "_", "$" or "!",
3530 (and (org-export-table-has-special-column-p
3531 (org-export-get-parent table-row))
3532 (member first-cell '(("^") ("_") ("$") ("!"))))
3533 ;; ... it contains only alignment cookies and empty cells.
3534 (let ((special-row-p 'empty))
3535 (catch 'exit
3536 (mapc
3537 (lambda (cell)
3538 (let ((value (org-element-contents cell)))
3539 ;; Since VALUE is a secondary string, the following
3540 ;; checks avoid expanding it with `org-export-data'.
3541 (cond ((not value))
3542 ((and (not (cdr value))
3543 (stringp (car value))
3544 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
3545 (car value)))
3546 (setq special-row-p 'cookie))
3547 (t (throw 'exit nil)))))
3548 (org-element-contents table-row))
3549 (eq special-row-p 'cookie)))))))
3551 (defun org-export-table-row-group (table-row info)
3552 "Return TABLE-ROW's group.
3554 INFO is a plist used as the communication channel.
3556 Return value is the group number, as an integer, or nil special
3557 rows and table rules. Group 1 is also table's header."
3558 (unless (or (eq (org-element-property :type table-row) 'rule)
3559 (org-export-table-row-is-special-p table-row info))
3560 (let ((group 0) row-flag)
3561 (catch 'found
3562 (mapc
3563 (lambda (row)
3564 (cond
3565 ((and (eq (org-element-property :type row) 'standard)
3566 (not (org-export-table-row-is-special-p row info)))
3567 (unless row-flag (incf group) (setq row-flag t)))
3568 ((eq (org-element-property :type row) 'rule)
3569 (setq row-flag nil)))
3570 (when (equal table-row row) (throw 'found group)))
3571 (org-element-contents (org-export-get-parent table-row)))))))
3573 (defun org-export-table-cell-width (table-cell info)
3574 "Return TABLE-CELL contents width.
3576 INFO is a plist used as the communication channel.
3578 Return value is the width given by the last width cookie in the
3579 same column as TABLE-CELL, or nil."
3580 (let* ((row (org-export-get-parent table-cell))
3581 (column (let ((cells (org-element-contents row)))
3582 (- (length cells) (length (member table-cell cells)))))
3583 (table (org-export-get-parent-table table-cell))
3584 cookie-width)
3585 (mapc
3586 (lambda (row)
3587 (cond
3588 ;; In a special row, try to find a width cookie at COLUMN.
3589 ((org-export-table-row-is-special-p row info)
3590 (let ((value (org-element-contents
3591 (elt (org-element-contents row) column))))
3592 ;; The following checks avoid expanding unnecessarily the
3593 ;; cell with `org-export-data'
3594 (when (and value
3595 (not (cdr value))
3596 (stringp (car value))
3597 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" (car value))
3598 (match-string 1 (car value)))
3599 (setq cookie-width
3600 (string-to-number (match-string 1 (car value)))))))
3601 ;; Ignore table rules.
3602 ((eq (org-element-property :type row) 'rule))))
3603 (org-element-contents table))
3604 ;; Return value.
3605 cookie-width))
3607 (defun org-export-table-cell-alignment (table-cell info)
3608 "Return TABLE-CELL contents alignment.
3610 INFO is a plist used as the communication channel.
3612 Return alignment as specified by the last alignment cookie in the
3613 same column as TABLE-CELL. If no such cookie is found, a default
3614 alignment value will be deduced from fraction of numbers in the
3615 column (see `org-table-number-fraction' for more information).
3616 Possible values are `left', `right' and `center'."
3617 (let* ((row (org-export-get-parent table-cell))
3618 (column (let ((cells (org-element-contents row)))
3619 (- (length cells) (length (member table-cell cells)))))
3620 (table (org-export-get-parent-table table-cell))
3621 (number-cells 0)
3622 (total-cells 0)
3623 cookie-align)
3624 (mapc
3625 (lambda (row)
3626 (cond
3627 ;; In a special row, try to find an alignment cookie at
3628 ;; COLUMN.
3629 ((org-export-table-row-is-special-p row info)
3630 (let ((value (org-element-contents
3631 (elt (org-element-contents row) column))))
3632 ;; Since VALUE is a secondary string, the following checks
3633 ;; avoid useless expansion through `org-export-data'.
3634 (when (and value
3635 (not (cdr value))
3636 (stringp (car value))
3637 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
3638 (car value))
3639 (match-string 1 (car value)))
3640 (setq cookie-align (match-string 1 (car value))))))
3641 ;; Ignore table rules.
3642 ((eq (org-element-property :type row) 'rule))
3643 ;; In a standard row, check if cell's contents are expressing
3644 ;; some kind of number. Increase NUMBER-CELLS accordingly.
3645 ;; Though, don't bother if an alignment cookie has already
3646 ;; defined cell's alignment.
3647 ((not cookie-align)
3648 (let ((value (org-export-data
3649 (org-element-contents
3650 (elt (org-element-contents row) column))
3651 info)))
3652 (incf total-cells)
3653 (when (string-match org-table-number-regexp value)
3654 (incf number-cells))))))
3655 (org-element-contents table))
3656 ;; Return value. Alignment specified by cookies has precedence
3657 ;; over alignment deduced from cells contents.
3658 (cond ((equal cookie-align "l") 'left)
3659 ((equal cookie-align "r") 'right)
3660 ((equal cookie-align "c") 'center)
3661 ((>= (/ (float number-cells) total-cells) org-table-number-fraction)
3662 'right)
3663 (t 'left))))
3665 (defun org-export-table-cell-borders (table-cell info)
3666 "Return TABLE-CELL borders.
3668 INFO is a plist used as a communication channel.
3670 Return value is a list of symbols, or nil. Possible values are:
3671 `top', `bottom', `above', `below', `left' and `right'. Note:
3672 `top' (resp. `bottom') only happen for a cell in the first
3673 row (resp. last row) of the table, ignoring table rules, if any.
3675 Returned borders ignore special rows."
3676 (let* ((row (org-export-get-parent table-cell))
3677 (table (org-export-get-parent-table table-cell))
3678 borders)
3679 ;; Top/above border? TABLE-CELL has a border above when a rule
3680 ;; used to demarcate row groups can be found above. Hence,
3681 ;; finding a rule isn't sufficient to push `above' in BORDERS:
3682 ;; another regular row has to be found above that rule.
3683 (let (rule-flag)
3684 (catch 'exit
3685 (mapc (lambda (row)
3686 (cond ((eq (org-element-property :type row) 'rule)
3687 (setq rule-flag t))
3688 ((not (org-export-table-row-is-special-p row info))
3689 (if rule-flag (throw 'exit (push 'above borders))
3690 (throw 'exit nil)))))
3691 ;; Look at every row before the current one.
3692 (cdr (member row (reverse (org-element-contents table)))))
3693 ;; No rule above, or rule found starts the table (ignoring any
3694 ;; special row): TABLE-CELL is at the top of the table.
3695 (when rule-flag (push 'above borders))
3696 (push 'top borders)))
3697 ;; Bottom/below border? TABLE-CELL has a border below when next
3698 ;; non-regular row below is a rule.
3699 (let (rule-flag)
3700 (catch 'exit
3701 (mapc (lambda (row)
3702 (cond ((eq (org-element-property :type row) 'rule)
3703 (setq rule-flag t))
3704 ((not (org-export-table-row-is-special-p row info))
3705 (if rule-flag (throw 'exit (push 'below borders))
3706 (throw 'exit nil)))))
3707 ;; Look at every row after the current one.
3708 (cdr (member row (org-element-contents table))))
3709 ;; No rule below, or rule found ends the table (modulo some
3710 ;; special row): TABLE-CELL is at the bottom of the table.
3711 (when rule-flag (push 'below borders))
3712 (push 'bottom borders)))
3713 ;; Right/left borders? They can only be specified by column
3714 ;; groups. Column groups are defined in a row starting with "/".
3715 ;; Also a column groups row only contains "<", "<>", ">" or blank
3716 ;; cells.
3717 (catch 'exit
3718 (let ((column (let ((cells (org-element-contents row)))
3719 (- (length cells) (length (member table-cell cells))))))
3720 (mapc
3721 (lambda (row)
3722 (unless (eq (org-element-property :type row) 'rule)
3723 (when (equal (org-element-contents
3724 (car (org-element-contents row)))
3725 '("/"))
3726 (let ((column-groups
3727 (mapcar
3728 (lambda (cell)
3729 (let ((value (org-element-contents cell)))
3730 (when (member value '(("<") ("<>") (">") nil))
3731 (car value))))
3732 (org-element-contents row))))
3733 ;; There's a left border when previous cell, if
3734 ;; any, ends a group, or current one starts one.
3735 (when (or (and (not (zerop column))
3736 (member (elt column-groups (1- column))
3737 '(">" "<>")))
3738 (member (elt column-groups column) '("<" "<>")))
3739 (push 'left borders))
3740 ;; There's a right border when next cell, if any,
3741 ;; starts a group, or current one ends one.
3742 (when (or (and (/= (1+ column) (length column-groups))
3743 (member (elt column-groups (1+ column))
3744 '("<" "<>")))
3745 (member (elt column-groups column) '(">" "<>")))
3746 (push 'right borders))
3747 (throw 'exit nil)))))
3748 ;; Table rows are read in reverse order so last column groups
3749 ;; row has precedence over any previous one.
3750 (reverse (org-element-contents table)))))
3751 ;; Return value.
3752 borders))
3754 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
3755 "Non-nil when TABLE-CELL is at the beginning of a row group.
3756 INFO is a plist used as a communication channel."
3757 ;; A cell starts a column group either when it is at the beginning
3758 ;; of a row (or after the special column, if any) or when it has
3759 ;; a left border.
3760 (or (equal (org-element-map
3761 (org-export-get-parent table-cell)
3762 'table-cell 'identity info 'first-match)
3763 table-cell)
3764 (memq 'left (org-export-table-cell-borders table-cell info))))
3766 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
3767 "Non-nil when TABLE-CELL is at the end of a row group.
3768 INFO is a plist used as a communication channel."
3769 ;; A cell ends a column group either when it is at the end of a row
3770 ;; or when it has a right border.
3771 (or (equal (car (last (org-element-contents
3772 (org-export-get-parent table-cell))))
3773 table-cell)
3774 (memq 'right (org-export-table-cell-borders table-cell info))))
3776 (defun org-export-table-row-starts-rowgroup-p (table-row info)
3777 "Non-nil when TABLE-ROW is at the beginning of a column group.
3778 INFO is a plist used as a communication channel."
3779 (unless (or (eq (org-element-property :type table-row) 'rule)
3780 (org-export-table-row-is-special-p table-row info))
3781 (let ((borders (org-export-table-cell-borders
3782 (car (org-element-contents table-row)) info)))
3783 (or (memq 'top borders) (memq 'above borders)))))
3785 (defun org-export-table-row-ends-rowgroup-p (table-row info)
3786 "Non-nil when TABLE-ROW is at the end of a column group.
3787 INFO is a plist used as a communication channel."
3788 (unless (or (eq (org-element-property :type table-row) 'rule)
3789 (org-export-table-row-is-special-p table-row info))
3790 (let ((borders (org-export-table-cell-borders
3791 (car (org-element-contents table-row)) info)))
3792 (or (memq 'bottom borders) (memq 'below borders)))))
3794 (defun org-export-table-row-starts-header-p (table-row info)
3795 "Non-nil when TABLE-ROW is the first table header's row.
3796 INFO is a plist used as a communication channel."
3797 (and (org-export-table-has-header-p
3798 (org-export-get-parent-table table-row) info)
3799 (org-export-table-row-starts-rowgroup-p table-row info)
3800 (= (org-export-table-row-group table-row info) 1)))
3802 (defun org-export-table-row-ends-header-p (table-row info)
3803 "Non-nil when TABLE-ROW is the last table header's row.
3804 INFO is a plist used as a communication channel."
3805 (and (org-export-table-has-header-p
3806 (org-export-get-parent-table table-row) info)
3807 (org-export-table-row-ends-rowgroup-p table-row info)
3808 (= (org-export-table-row-group table-row info) 1)))
3810 (defun org-export-table-dimensions (table info)
3811 "Return TABLE dimensions.
3813 INFO is a plist used as a communication channel.
3815 Return value is a CONS like (ROWS . COLUMNS) where
3816 ROWS (resp. COLUMNS) is the number of exportable
3817 rows (resp. columns)."
3818 (let (first-row (columns 0) (rows 0))
3819 ;; Set number of rows, and extract first one.
3820 (org-element-map
3821 table 'table-row
3822 (lambda (row)
3823 (when (eq (org-element-property :type row) 'standard)
3824 (incf rows)
3825 (unless first-row (setq first-row row)))) info)
3826 ;; Set number of columns.
3827 (org-element-map first-row 'table-cell (lambda (cell) (incf columns)) info)
3828 ;; Return value.
3829 (cons rows columns)))
3831 (defun org-export-table-cell-address (table-cell info)
3832 "Return address of a regular TABLE-CELL object.
3834 TABLE-CELL is the cell considered. INFO is a plist used as
3835 a communication channel.
3837 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
3838 zero-based index. Only exportable cells are considered. The
3839 function returns nil for other cells."
3840 (let* ((table-row (org-export-get-parent table-cell))
3841 (table (org-export-get-parent-table table-cell)))
3842 ;; Ignore cells in special rows or in special column.
3843 (unless (or (org-export-table-row-is-special-p table-row info)
3844 (and (org-export-table-has-special-column-p table)
3845 (equal (car (org-element-contents table-row)) table-cell)))
3846 (cons
3847 ;; Row number.
3848 (let ((row-count 0))
3849 (org-element-map
3850 table 'table-row
3851 (lambda (row)
3852 (cond ((eq (org-element-property :type row) 'rule) nil)
3853 ((equal row table-row) row-count)
3854 (t (incf row-count) nil)))
3855 info 'first-match))
3856 ;; Column number.
3857 (let ((col-count 0))
3858 (org-element-map
3859 table-row 'table-cell
3860 (lambda (cell)
3861 (if (equal cell table-cell) col-count
3862 (incf col-count) nil))
3863 info 'first-match))))))
3865 (defun org-export-get-table-cell-at (address table info)
3866 "Return regular table-cell object at ADDRESS in TABLE.
3868 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
3869 zero-based index. TABLE is a table type element. INFO is
3870 a plist used as a communication channel.
3872 If no table-cell, among exportable cells, is found at ADDRESS,
3873 return nil."
3874 (let ((column-pos (cdr address)) (column-count 0))
3875 (org-element-map
3876 ;; Row at (car address) or nil.
3877 (let ((row-pos (car address)) (row-count 0))
3878 (org-element-map
3879 table 'table-row
3880 (lambda (row)
3881 (cond ((eq (org-element-property :type row) 'rule) nil)
3882 ((= row-count row-pos) row)
3883 (t (incf row-count) nil)))
3884 info 'first-match))
3885 'table-cell
3886 (lambda (cell)
3887 (if (= column-count column-pos) cell
3888 (incf column-count) nil))
3889 info 'first-match)))
3892 ;;;; For Tables Of Contents
3894 ;; `org-export-collect-headlines' builds a list of all exportable
3895 ;; headline elements, maybe limited to a certain depth. One can then
3896 ;; easily parse it and transcode it.
3898 ;; Building lists of tables, figures or listings is quite similar.
3899 ;; Once the generic function `org-export-collect-elements' is defined,
3900 ;; `org-export-collect-tables', `org-export-collect-figures' and
3901 ;; `org-export-collect-listings' can be derived from it.
3903 (defun org-export-collect-headlines (info &optional n)
3904 "Collect headlines in order to build a table of contents.
3906 INFO is a plist used as a communication channel.
3908 When non-nil, optional argument N must be an integer. It
3909 specifies the depth of the table of contents.
3911 Return a list of all exportable headlines as parsed elements."
3912 (org-element-map
3913 (plist-get info :parse-tree)
3914 'headline
3915 (lambda (headline)
3916 ;; Strip contents from HEADLINE.
3917 (let ((relative-level (org-export-get-relative-level headline info)))
3918 (unless (and n (> relative-level n)) headline)))
3919 info))
3921 (defun org-export-collect-elements (type info &optional predicate)
3922 "Collect referenceable elements of a determined type.
3924 TYPE can be a symbol or a list of symbols specifying element
3925 types to search. Only elements with a caption are collected.
3927 INFO is a plist used as a communication channel.
3929 When non-nil, optional argument PREDICATE is a function accepting
3930 one argument, an element of type TYPE. It returns a non-nil
3931 value when that element should be collected.
3933 Return a list of all elements found, in order of appearance."
3934 (org-element-map
3935 (plist-get info :parse-tree) type
3936 (lambda (element)
3937 (and (org-element-property :caption element)
3938 (or (not predicate) (funcall predicate element))
3939 element))
3940 info))
3942 (defun org-export-collect-tables (info)
3943 "Build a list of tables.
3944 INFO is a plist used as a communication channel.
3946 Return a list of table elements with a caption."
3947 (org-export-collect-elements 'table info))
3949 (defun org-export-collect-figures (info predicate)
3950 "Build a list of figures.
3952 INFO is a plist used as a communication channel. PREDICATE is
3953 a function which accepts one argument: a paragraph element and
3954 whose return value is non-nil when that element should be
3955 collected.
3957 A figure is a paragraph type element, with a caption, verifying
3958 PREDICATE. The latter has to be provided since a \"figure\" is
3959 a vague concept that may depend on back-end.
3961 Return a list of elements recognized as figures."
3962 (org-export-collect-elements 'paragraph info predicate))
3964 (defun org-export-collect-listings (info)
3965 "Build a list of src blocks.
3967 INFO is a plist used as a communication channel.
3969 Return a list of src-block elements with a caption."
3970 (org-export-collect-elements 'src-block info))
3973 ;;;; Topology
3975 ;; Here are various functions to retrieve information about the
3976 ;; neighbourhood of a given element or object. Neighbours of interest
3977 ;; are direct parent (`org-export-get-parent'), parent headline
3978 ;; (`org-export-get-parent-headline'), first element containing an
3979 ;; object, (`org-export-get-parent-element'), parent table
3980 ;; (`org-export-get-parent-table'), previous element or object
3981 ;; (`org-export-get-previous-element') and next element or object
3982 ;; (`org-export-get-next-element').
3984 ;; `org-export-get-genealogy' returns the full genealogy of a given
3985 ;; element or object, from closest parent to full parse tree.
3987 (defun org-export-get-parent (blob)
3988 "Return BLOB parent or nil.
3989 BLOB is the element or object considered."
3990 (org-element-property :parent blob))
3992 (defun org-export-get-genealogy (blob)
3993 "Return full genealogy relative to a given element or object.
3994 BLOB is the element or object being considered."
3995 (let (genealogy (parent blob))
3996 (while (setq parent (org-element-property :parent parent))
3997 (push parent genealogy))
3998 (nreverse genealogy)))
4000 (defun org-export-get-parent-headline (blob)
4001 "Return BLOB parent headline or nil.
4002 BLOB is the element or object being considered."
4003 (let ((parent blob))
4004 (while (and (setq parent (org-element-property :parent parent))
4005 (not (eq (org-element-type parent) 'headline))))
4006 parent))
4008 (defun org-export-get-parent-element (object)
4009 "Return first element containing OBJECT or nil.
4010 OBJECT is the object to consider."
4011 (let ((parent object))
4012 (while (and (setq parent (org-element-property :parent parent))
4013 (memq (org-element-type parent) org-element-all-objects)))
4014 parent))
4016 (defun org-export-get-parent-table (object)
4017 "Return OBJECT parent table or nil.
4018 OBJECT is either a `table-cell' or `table-element' type object."
4019 (let ((parent object))
4020 (while (and (setq parent (org-element-property :parent parent))
4021 (not (eq (org-element-type parent) 'table))))
4022 parent))
4024 (defun org-export-get-previous-element (blob)
4025 "Return previous element or object.
4026 BLOB is an element or object. Return previous element or object,
4027 a string, or nil."
4028 (let ((parent (org-export-get-parent blob)))
4029 (cadr (member blob (reverse (org-element-contents parent))))))
4031 (defun org-export-get-next-element (blob)
4032 "Return next element or object.
4033 BLOB is an element or object. Return next element or object,
4034 a string, or nil."
4035 (let ((parent (org-export-get-parent blob)))
4036 (cadr (member blob (org-element-contents parent)))))
4040 ;;; The Dispatcher
4042 ;; `org-export-dispatch' is the standard interactive way to start an
4043 ;; export process. It uses `org-export-dispatch-ui' as a subroutine
4044 ;; for its interface. Most commons back-ends should have an entry in
4045 ;; it.
4047 (defun org-export-dispatch ()
4048 "Export dispatcher for Org mode.
4050 It provides an access to common export related tasks in a buffer.
4051 Its interface comes in two flavours: standard and expert. While
4052 both share the same set of bindings, only the former displays the
4053 valid keys associations. Set `org-export-dispatch-use-expert-ui'
4054 to switch to one or the other.
4056 Return an error if key pressed has no associated command."
4057 (interactive)
4058 (let* ((input (org-export-dispatch-ui
4059 (if (listp org-export-initial-scope) org-export-initial-scope
4060 (list org-export-initial-scope))
4061 org-export-dispatch-use-expert-ui))
4062 (raw-key (car input))
4063 (optns (cdr input)))
4064 ;; Translate "C-a", "C-b"... into "a", "b"... Then take action
4065 ;; depending on user's key pressed.
4066 (case (if (< raw-key 27) (+ raw-key 96) raw-key)
4067 ;; Allow to quit with "q" key.
4068 (?q nil)
4069 ;; Export with `e-ascii' back-end.
4070 ((?A ?N ?U)
4071 (let ((outbuf
4072 (org-export-to-buffer
4073 'e-ascii "*Org E-ASCII Export*"
4074 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)
4075 `(:ascii-charset
4076 ,(case raw-key (?A 'ascii) (?N 'latin1) (t 'utf-8))))))
4077 (with-current-buffer outbuf (text-mode))
4078 (when org-export-show-temporary-export-buffer
4079 (switch-to-buffer-other-window outbuf))))
4080 ((?a ?n ?u)
4081 (org-e-ascii-export-to-ascii
4082 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)
4083 `(:ascii-charset ,(case raw-key (?a 'ascii) (?n 'latin1) (t 'utf-8)))))
4084 ;; Export with `e-latex' back-end.
4086 (let ((outbuf
4087 (org-export-to-buffer
4088 'e-latex "*Org E-LaTeX Export*"
4089 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
4090 (with-current-buffer outbuf (latex-mode))
4091 (when org-export-show-temporary-export-buffer
4092 (switch-to-buffer-other-window outbuf))))
4094 (org-e-latex-export-to-latex
4095 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
4097 (org-e-latex-export-to-pdf
4098 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
4100 (org-open-file
4101 (org-e-latex-export-to-pdf
4102 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
4103 ;; Export with `e-html' back-end.
4105 (let ((outbuf
4106 (org-export-to-buffer
4107 'e-html "*Org E-HTML Export*"
4108 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
4109 ;; set major mode
4110 (with-current-buffer outbuf (nxml-mode))
4111 (when org-export-show-temporary-export-buffer
4112 (switch-to-buffer-other-window outbuf))))
4114 (org-e-html-export-to-html
4115 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
4117 (org-open-file
4118 (org-e-html-export-to-html
4119 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
4120 ;; Export with `e-odt' back-end.
4122 (org-e-odt-export-to-odt
4123 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
4125 (org-open-file
4126 (org-e-odt-export-to-odt
4127 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
4128 ;; Publishing facilities
4130 (org-e-publish-current-file (memq 'force optns)))
4132 (org-e-publish-current-project (memq 'force optns)))
4134 (let ((project
4135 (assoc (org-icompleting-read
4136 "Publish project: " org-e-publish-project-alist nil t)
4137 org-e-publish-project-alist)))
4138 (org-e-publish project (memq 'force optns))))
4140 (org-e-publish-all (memq 'force optns)))
4141 ;; Undefined command.
4142 (t (error "No command associated with key %s"
4143 (char-to-string raw-key))))))
4145 (defun org-export-dispatch-ui (options expertp)
4146 "Handle interface for `org-export-dispatch'.
4148 OPTIONS is a list containing current interactive options set for
4149 export. It can contain any of the following symbols:
4150 `body' toggles a body-only export
4151 `subtree' restricts export to current subtree
4152 `visible' restricts export to visible part of buffer.
4153 `force' force publishing files.
4155 EXPERTP, when non-nil, triggers expert UI. In that case, no help
4156 buffer is provided, but indications about currently active
4157 options are given in the prompt. Moreover, \[?] allows to switch
4158 back to standard interface.
4160 Return value is a list with key pressed as CAR and a list of
4161 final interactive export options as CDR."
4162 (let ((help
4163 (format "---- (Options) -------------------------------------------
4165 \[1] Body only: %s [2] Export scope: %s
4166 \[3] Visible only: %s [4] Force publishing: %s
4169 --- (ASCII/Latin-1/UTF-8 Export) -------------------------
4171 \[a/n/u] to TXT file [A/N/U] to temporary buffer
4173 --- (HTML Export) ----------------------------------------
4175 \[h] to HTML file [b] ... and open it
4176 \[H] to temporary buffer
4178 --- (LaTeX Export) ---------------------------------------
4180 \[l] to TEX file [L] to temporary buffer
4181 \[p] to PDF file [d] ... and open it
4183 --- (ODF Export) -----------------------------------------
4185 \[o] to ODT file [O] ... and open it
4187 --- (Publish) --------------------------------------------
4189 \[F] current file [P] current project
4190 \[X] a project [E] every project"
4191 (if (memq 'body options) "On " "Off")
4192 (if (memq 'subtree options) "Subtree" "Buffer ")
4193 (if (memq 'visible options) "On " "Off")
4194 (if (memq 'force options) "On " "Off")))
4195 (standard-prompt "Export command: ")
4196 (expert-prompt (format "Export command (%s%s%s%s): "
4197 (if (memq 'body options) "b" "-")
4198 (if (memq 'subtree options) "s" "-")
4199 (if (memq 'visible options) "v" "-")
4200 (if (memq 'force options) "f" "-")))
4201 (handle-keypress
4202 (function
4203 ;; Read a character from command input, toggling interactive
4204 ;; options when applicable. PROMPT is the displayed prompt,
4205 ;; as a string.
4206 (lambda (prompt)
4207 (let ((key (read-char-exclusive prompt)))
4208 (cond
4209 ;; Ignore non-standard characters (i.e. "M-a").
4210 ((not (characterp key)) (org-export-dispatch-ui options expertp))
4211 ;; Help key: Switch back to standard interface if
4212 ;; expert UI was active.
4213 ((eq key ??) (org-export-dispatch-ui options nil))
4214 ;; Toggle export options.
4215 ((memq key '(?1 ?2 ?3 ?4))
4216 (org-export-dispatch-ui
4217 (let ((option (case key (?1 'body) (?2 'subtree) (?3 'visible)
4218 (?4 'force))))
4219 (if (memq option options) (remq option options)
4220 (cons option options)))
4221 expertp))
4222 ;; Action selected: Send key and options back to
4223 ;; `org-export-dispatch'.
4224 (t (cons key options))))))))
4225 ;; With expert UI, just read key with a fancy prompt. In standard
4226 ;; UI, display an intrusive help buffer.
4227 (if expertp (funcall handle-keypress expert-prompt)
4228 (save-window-excursion
4229 (delete-other-windows)
4230 (with-output-to-temp-buffer "*Org Export/Publishing Help*" (princ help))
4231 (org-fit-window-to-buffer
4232 (get-buffer-window "*Org Export/Publishing Help*"))
4233 (funcall handle-keypress standard-prompt)))))
4236 (provide 'org-export)
4237 ;;; org-export.el ends here