org-e-html: Fix misc. bugs
[org-mode.git] / contrib / lisp / org-export.el
blobb9294e59aceadbe639e1982ca6f2c703ebb74f3c
1 ;;; org-export.el --- Generic Export Engine For Org
3 ;; Copyright (C) 2012 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; This program is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
13 ;; This program is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
21 ;;; Commentary:
23 ;; This library implements a generic export engine for Org, built on
24 ;; its syntactical parser: Org Elements.
26 ;; Besides that parser, the generic exporter is made of three distinct
27 ;; parts:
29 ;; - The communication channel consists in a property list, which is
30 ;; created and updated during the process. Its use is to offer
31 ;; every piece of information, would it be about initial environment
32 ;; or contextual data, all in a single place. The exhaustive list
33 ;; of properties is given in "The Communication Channel" section of
34 ;; this file.
36 ;; - The transcoder walks the parse tree, ignores or treat as plain
37 ;; text elements and objects according to export options, and
38 ;; eventually calls back-end specific functions to do the real
39 ;; transcoding, concatenating their return value along the way.
41 ;; - The filter system is activated at the very beginning and the very
42 ;; end of the export process, and each time an element or an object
43 ;; has been converted. It is the entry point to fine-tune standard
44 ;; output from back-end transcoders.
46 ;; The core function is `org-export-as'. It returns the transcoded
47 ;; buffer as a string.
49 ;; In order to implement a back-end for this generic exporter, up to
50 ;; three steps may be needed:
52 ;; 1. Define a variable, `org-BACKEND-translate-alist' where elements
53 ;; and objects types are associated to translator functions.
55 ;; These functions should return a string without any trailing
56 ;; space, or nil. They must accept three arguments: the object or
57 ;; element itself, its contents or nil when it isn't recursive and
58 ;; the property list used as a communication channel.
60 ;; Contents, when not nil, are stripped from any global indentation
61 ;; (although the relative one is preserved). They also always end
62 ;; with a single newline character.
64 ;; If, for a given type, no function is found, that element or
65 ;; object type will simply be ignored, along with any blank line or
66 ;; white space at its end. The same will happen if the function
67 ;; returns the nil value. If that function returns the empty
68 ;; string, the type will be ignored, but the blank lines or white
69 ;; 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. The former returns the final transcoded
74 ;; string, and can be used to add a preamble and a postamble to
75 ;; document's body. It must accept two arguments: the transcoded
76 ;; string and the property list containing export options. The
77 ;; latter, when defined, is to be called on every text not
78 ;; recognized as an element or an object. It must accept two
79 ;; arguments: the text string and the information channel.
81 ;; 2. Optionally define a variable, `org-BACKEND-options-alist', in
82 ;; order to support new export options, buffer keywords or
83 ;; "#+OPTIONS:" items specific to the back-end. See
84 ;; `org-export-options-alist' for supported defaults and syntax.
86 ;; 3. Optionally define a variable, `org-BACKEND-filters-alist', in
87 ;; order to apply developer filters. See "The Filter System"
88 ;; section in this file for more information.
90 ;; If the new back-end shares most properties with another one,
91 ;; `org-export-define-derived-backend' can be used to simplify the
92 ;; process.
94 ;; Any back-end can define its own variables. Among them, those
95 ;; customizables should belong to the `org-export-BACKEND' group.
97 ;; Tools for common tasks across back-ends are implemented in the
98 ;; penultimate part of this file. A dispatcher for standard back-ends
99 ;; is provided in the last one.
101 ;;; Code:
103 (eval-when-compile (require 'cl))
104 (require 'org-element)
108 ;;; Internal Variables
110 ;; Among internal variables, the most important is
111 ;; `org-export-options-alist'. This variable define the global export
112 ;; options, shared between every exporter, and how they are acquired.
114 (defconst org-export-max-depth 19
115 "Maximum nesting depth for headlines, counting from 0.")
117 (defconst org-export-options-alist
118 '((:author "AUTHOR" nil user-full-name t)
119 (:creator "CREATOR" nil org-export-creator-string)
120 (:date "DATE" nil nil t)
121 (:description "DESCRIPTION" nil nil newline)
122 (:email "EMAIL" nil user-mail-address t)
123 (:exclude-tags "EXPORT_EXCLUDE_TAGS" nil org-export-exclude-tags split)
124 (:headline-levels nil "H" org-export-headline-levels)
125 (:keywords "KEYWORDS" nil nil space)
126 (:language "LANGUAGE" nil org-export-default-language t)
127 (:preserve-breaks nil "\\n" org-export-preserve-breaks)
128 (:section-numbers nil "num" org-export-with-section-numbers)
129 (:select-tags "EXPORT_SELECT_TAGS" nil org-export-select-tags split)
130 (:time-stamp-file nil "timestamp" org-export-time-stamp-file)
131 (:title "TITLE" nil nil space)
132 (:with-archived-trees nil "arch" org-export-with-archived-trees)
133 (:with-author nil "author" org-export-with-author)
134 (:with-clocks nil "c" org-export-with-clocks)
135 (:with-creator nil "creator" org-export-with-creator)
136 (:with-drawers nil "d" org-export-with-drawers)
137 (:with-email nil "email" org-export-with-email)
138 (:with-emphasize nil "*" org-export-with-emphasize)
139 (:with-entities nil "e" org-export-with-entities)
140 (:with-fixed-width nil ":" org-export-with-fixed-width)
141 (:with-footnotes nil "f" org-export-with-footnotes)
142 (:with-plannings nil "p" org-export-with-planning)
143 (:with-priority nil "pri" org-export-with-priority)
144 (:with-special-strings nil "-" org-export-with-special-strings)
145 (:with-sub-superscript nil "^" org-export-with-sub-superscripts)
146 (:with-toc nil "toc" org-export-with-toc)
147 (:with-tables nil "|" org-export-with-tables)
148 (:with-tags nil "tags" org-export-with-tags)
149 (:with-tasks nil "tasks" org-export-with-tasks)
150 (:with-timestamps nil "<" org-export-with-timestamps)
151 (:with-todo-keywords nil "todo" org-export-with-todo-keywords))
152 "Alist between export properties and ways to set them.
154 The CAR of the alist is the property name, and the CDR is a list
155 like (KEYWORD OPTION DEFAULT BEHAVIOUR) where:
157 KEYWORD is a string representing a buffer keyword, or nil.
158 OPTION is a string that could be found in an #+OPTIONS: line.
159 DEFAULT is the default value for the property.
160 BEHAVIOUR determine how Org should handle multiple keywords for
161 the same property. It is a symbol among:
162 nil Keep old value and discard the new one.
163 t Replace old value with the new one.
164 `space' Concatenate the values, separating them with a space.
165 `newline' Concatenate the values, separating them with
166 a newline.
167 `split' Split values at white spaces, and cons them to the
168 previous list.
170 KEYWORD and OPTION have precedence over DEFAULT.
172 All these properties should be back-end agnostic. For back-end
173 specific properties, define a similar variable named
174 `org-BACKEND-options-alist', replacing BACKEND with the name of
175 the appropriate back-end. You can also redefine properties
176 there, as they have precedence over these.")
178 (defconst org-export-special-keywords
179 '("SETUP_FILE" "OPTIONS" "MACRO")
180 "List of in-buffer keywords that require special treatment.
181 These keywords are not directly associated to a property. The
182 way they are handled must be hard-coded into
183 `org-export-get-inbuffer-options' function.")
185 (defconst org-export-filters-alist
186 '((:filter-bold . org-export-filter-bold-functions)
187 (:filter-babel-call . org-export-filter-babel-call-functions)
188 (:filter-center-block . org-export-filter-center-block-functions)
189 (:filter-clock . org-export-filter-clock-functions)
190 (:filter-code . org-export-filter-code-functions)
191 (:filter-comment . org-export-filter-comment-functions)
192 (:filter-comment-block . org-export-filter-comment-block-functions)
193 (:filter-drawer . org-export-filter-drawer-functions)
194 (:filter-dynamic-block . org-export-filter-dynamic-block-functions)
195 (:filter-entity . org-export-filter-entity-functions)
196 (:filter-example-block . org-export-filter-example-block-functions)
197 (:filter-export-block . org-export-filter-export-block-functions)
198 (:filter-export-snippet . org-export-filter-export-snippet-functions)
199 (:filter-final-output . org-export-filter-final-output-functions)
200 (:filter-fixed-width . org-export-filter-fixed-width-functions)
201 (:filter-footnote-definition . org-export-filter-footnote-definition-functions)
202 (:filter-footnote-reference . org-export-filter-footnote-reference-functions)
203 (:filter-headline . org-export-filter-headline-functions)
204 (:filter-horizontal-rule . org-export-filter-horizontal-rule-functions)
205 (:filter-inline-babel-call . org-export-filter-inline-babel-call-functions)
206 (:filter-inline-src-block . org-export-filter-inline-src-block-functions)
207 (:filter-inlinetask . org-export-filter-inlinetask-functions)
208 (:filter-italic . org-export-filter-italic-functions)
209 (:filter-item . org-export-filter-item-functions)
210 (:filter-keyword . org-export-filter-keyword-functions)
211 (:filter-latex-environment . org-export-filter-latex-environment-functions)
212 (:filter-latex-fragment . org-export-filter-latex-fragment-functions)
213 (:filter-line-break . org-export-filter-line-break-functions)
214 (:filter-link . org-export-filter-link-functions)
215 (:filter-macro . org-export-filter-macro-functions)
216 (:filter-paragraph . org-export-filter-paragraph-functions)
217 (:filter-parse-tree . org-export-filter-parse-tree-functions)
218 (:filter-plain-list . org-export-filter-plain-list-functions)
219 (:filter-plain-text . org-export-filter-plain-text-functions)
220 (:filter-planning . org-export-filter-planning-functions)
221 (:filter-property-drawer . org-export-filter-property-drawer-functions)
222 (:filter-quote-block . org-export-filter-quote-block-functions)
223 (:filter-quote-section . org-export-filter-quote-section-functions)
224 (:filter-radio-target . org-export-filter-radio-target-functions)
225 (:filter-section . org-export-filter-section-functions)
226 (:filter-special-block . org-export-filter-special-block-functions)
227 (:filter-src-block . org-export-filter-src-block-functions)
228 (:filter-statistics-cookie . org-export-filter-statistics-cookie-functions)
229 (:filter-strike-through . org-export-filter-strike-through-functions)
230 (:filter-subscript . org-export-filter-subscript-functions)
231 (:filter-superscript . org-export-filter-superscript-functions)
232 (:filter-table . org-export-filter-table-functions)
233 (:filter-table-cell . org-export-filter-table-cell-functions)
234 (:filter-table-row . org-export-filter-table-row-functions)
235 (:filter-target . org-export-filter-target-functions)
236 (:filter-timestamp . org-export-filter-timestamp-functions)
237 (:filter-underline . org-export-filter-underline-functions)
238 (:filter-verbatim . org-export-filter-verbatim-functions)
239 (:filter-verse-block . org-export-filter-verse-block-functions))
240 "Alist between filters properties and initial values.
242 The key of each association is a property name accessible through
243 the communication channel its value is a configurable global
244 variable defining initial filters.
246 This list is meant to install user specified filters. Back-end
247 developers may install their own filters using
248 `org-BACKEND-filters-alist', where BACKEND is the name of the
249 considered back-end. Filters defined there will always be
250 prepended to the current list, so they always get applied
251 first.")
253 (defconst org-export-default-inline-image-rule
254 `(("file" .
255 ,(format "\\.%s\\'"
256 (regexp-opt
257 '("png" "jpeg" "jpg" "gif" "tiff" "tif" "xbm"
258 "xpm" "pbm" "pgm" "ppm") t))))
259 "Default rule for link matching an inline image.
260 This rule applies to links with no description. By default, it
261 will be considered as an inline image if it targets a local file
262 whose extension is either \"png\", \"jpeg\", \"jpg\", \"gif\",
263 \"tiff\", \"tif\", \"xbm\", \"xpm\", \"pbm\", \"pgm\" or \"ppm\".
264 See `org-export-inline-image-p' for more information about
265 rules.")
269 ;;; User-configurable Variables
271 ;; Configuration for the masses.
273 ;; They should never be accessed directly, as their value is to be
274 ;; stored in a property list (cf. `org-export-options-alist').
275 ;; Back-ends will read their value from there instead.
277 (defgroup org-export nil
278 "Options for exporting Org mode files."
279 :tag "Org Export"
280 :group 'org)
282 (defgroup org-export-general nil
283 "General options for export engine."
284 :tag "Org Export General"
285 :group 'org-export)
287 (defcustom org-export-with-archived-trees 'headline
288 "Whether sub-trees with the ARCHIVE tag should be exported.
290 This can have three different values:
291 nil Do not export, pretend this tree is not present.
292 t Do export the entire tree.
293 `headline' Only export the headline, but skip the tree below it.
295 This option can also be set with the #+OPTIONS line,
296 e.g. \"arch:nil\"."
297 :group 'org-export-general
298 :type '(choice
299 (const :tag "Not at all" nil)
300 (const :tag "Headline only" 'headline)
301 (const :tag "Entirely" t)))
303 (defcustom org-export-with-author t
304 "Non-nil means insert author name into the exported file.
305 This option can also be set with the #+OPTIONS line,
306 e.g. \"author:nil\"."
307 :group 'org-export-general
308 :type 'boolean)
310 (defcustom org-export-with-clocks nil
311 "Non-nil means export CLOCK keywords.
312 This option can also be set with the #+OPTIONS line,
313 e.g. \"c:t\"."
314 :group 'org-export-general
315 :type 'boolean)
317 (defcustom org-export-with-creator 'comment
318 "Non-nil means the postamble should contain a creator sentence.
320 The sentence can be set in `org-export-creator-string' and
321 defaults to \"Generated by Org mode XX in Emacs XXX.\".
323 If the value is `comment' insert it as a comment."
324 :group 'org-export-general
325 :type '(choice
326 (const :tag "No creator sentence" nil)
327 (const :tag "Sentence as a comment" 'comment)
328 (const :tag "Insert the sentence" t)))
330 (defcustom org-export-creator-string
331 (format "Generated by Org mode %s in Emacs %s."
332 (if (fboundp 'org-version) (org-version) "(Unknown)")
333 emacs-version)
334 "String to insert at the end of the generated document."
335 :group 'org-export-general
336 :type '(string :tag "Creator string"))
338 (defcustom org-export-with-drawers t
339 "Non-nil means export contents of standard drawers.
341 When t, all drawers are exported. This may also be a list of
342 drawer names to export. This variable doesn't apply to
343 properties drawers.
345 This option can also be set with the #+OPTIONS line,
346 e.g. \"d:nil\"."
347 :group 'org-export-general
348 :type '(choice
349 (const :tag "All drawers" t)
350 (const :tag "None" nil)
351 (repeat :tag "Selected drawers"
352 (string :tag "Drawer name"))))
354 (defcustom org-export-with-email nil
355 "Non-nil means insert author email into the exported file.
356 This option can also be set with the #+OPTIONS line,
357 e.g. \"email:t\"."
358 :group 'org-export-general
359 :type 'boolean)
361 (defcustom org-export-with-emphasize t
362 "Non-nil means interpret *word*, /word/, and _word_ as emphasized text.
364 If the export target supports emphasizing text, the word will be
365 typeset in bold, italic, or underlined, respectively. Not all
366 export backends support this.
368 This option can also be set with the #+OPTIONS line, e.g. \"*:nil\"."
369 :group 'org-export-general
370 :type 'boolean)
372 (defcustom org-export-exclude-tags '("noexport")
373 "Tags that exclude a tree from export.
375 All trees carrying any of these tags will be excluded from
376 export. This is without condition, so even subtrees inside that
377 carry one of the `org-export-select-tags' will be removed.
379 This option can also be set with the #+EXPORT_EXCLUDE_TAGS:
380 keyword."
381 :group 'org-export-general
382 :type '(repeat (string :tag "Tag")))
384 (defcustom org-export-with-fixed-width t
385 "Non-nil means lines starting with \":\" will be in fixed width font.
387 This can be used to have pre-formatted text, fragments of code
388 etc. For example:
389 : ;; Some Lisp examples
390 : (while (defc cnt)
391 : (ding))
392 will be looking just like this in also HTML. See also the QUOTE
393 keyword. Not all export backends support this.
395 This option can also be set with the #+OPTIONS line, e.g. \"::nil\"."
396 :group 'org-export-translation
397 :type 'boolean)
399 (defcustom org-export-with-footnotes t
400 "Non-nil means Org footnotes should be exported.
401 This option can also be set with the #+OPTIONS line,
402 e.g. \"f:nil\"."
403 :group 'org-export-general
404 :type 'boolean)
406 (defcustom org-export-headline-levels 3
407 "The last level which is still exported as a headline.
409 Inferior levels will produce itemize lists when exported. Note
410 that a numeric prefix argument to an exporter function overrides
411 this setting.
413 This option can also be set with the #+OPTIONS line, e.g. \"H:2\"."
414 :group 'org-export-general
415 :type 'integer)
417 (defcustom org-export-default-language "en"
418 "The default language for export and clocktable translations, as a string.
419 This may have an association in
420 `org-clock-clocktable-language-setup'."
421 :group 'org-export-general
422 :type '(string :tag "Language"))
424 (defcustom org-export-preserve-breaks nil
425 "Non-nil means preserve all line breaks when exporting.
427 Normally, in HTML output paragraphs will be reformatted.
429 This option can also be set with the #+OPTIONS line,
430 e.g. \"\\n:t\"."
431 :group 'org-export-general
432 :type 'boolean)
434 (defcustom org-export-with-entities t
435 "Non-nil means interpret entities when exporting.
437 For example, HTML export converts \\alpha to &alpha; and \\AA to
438 &Aring;.
440 For a list of supported names, see the constant `org-entities'
441 and the user option `org-entities-user'.
443 This option can also be set with the #+OPTIONS line,
444 e.g. \"e:nil\"."
445 :group 'org-export-general
446 :type 'boolean)
448 (defcustom org-export-with-planning nil
449 "Non-nil means include planning info in export.
450 This option can also be set with the #+OPTIONS: line,
451 e.g. \"p:t\"."
452 :group 'org-export-general
453 :type 'boolean)
455 (defcustom org-export-with-priority nil
456 "Non-nil means include priority cookies in export.
458 When nil, remove priority cookies for export.
460 This option can also be set with the #+OPTIONS line,
461 e.g. \"pri:t\"."
462 :group 'org-export-general
463 :type 'boolean)
465 (defcustom org-export-with-section-numbers t
466 "Non-nil means add section numbers to headlines when exporting.
468 When set to an integer n, numbering will only happen for
469 headlines whose relative level is higher or equal to n.
471 This option can also be set with the #+OPTIONS line,
472 e.g. \"num:t\"."
473 :group 'org-export-general
474 :type 'boolean)
476 (defcustom org-export-select-tags '("export")
477 "Tags that select a tree for export.
479 If any such tag is found in a buffer, all trees that do not carry
480 one of these tags will be ignored during export. Inside trees
481 that are selected like this, you can still deselect a subtree by
482 tagging it with one of the `org-export-exclude-tags'.
484 This option can also be set with the #+EXPORT_SELECT_TAGS:
485 keyword."
486 :group 'org-export-general
487 :type '(repeat (string :tag "Tag")))
489 (defcustom org-export-with-special-strings t
490 "Non-nil means interpret \"\-\", \"--\" and \"---\" for export.
492 When this option is turned on, these strings will be exported as:
494 Org HTML LaTeX
495 -----+----------+--------
496 \\- &shy; \\-
497 -- &ndash; --
498 --- &mdash; ---
499 ... &hellip; \ldots
501 This option can also be set with the #+OPTIONS line,
502 e.g. \"-:nil\"."
503 :group 'org-export-general
504 :type 'boolean)
506 (defcustom org-export-with-sub-superscripts t
507 "Non-nil means interpret \"_\" and \"^\" for export.
509 When this option is turned on, you can use TeX-like syntax for
510 sub- and superscripts. Several characters after \"_\" or \"^\"
511 will be considered as a single item - so grouping with {} is
512 normally not needed. For example, the following things will be
513 parsed as single sub- or superscripts.
515 10^24 or 10^tau several digits will be considered 1 item.
516 10^-12 or 10^-tau a leading sign with digits or a word
517 x^2-y^3 will be read as x^2 - y^3, because items are
518 terminated by almost any nonword/nondigit char.
519 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
521 Still, ambiguity is possible - so when in doubt use {} to enclose
522 the sub/superscript. If you set this variable to the symbol
523 `{}', the braces are *required* in order to trigger
524 interpretations as sub/superscript. This can be helpful in
525 documents that need \"_\" frequently in plain text.
527 This option can also be set with the #+OPTIONS line,
528 e.g. \"^:nil\"."
529 :group 'org-export-general
530 :type '(choice
531 (const :tag "Interpret them" t)
532 (const :tag "Curly brackets only" {})
533 (const :tag "Do not interpret them" nil)))
535 (defcustom org-export-with-toc t
536 "Non-nil means create a table of contents in exported files.
538 The TOC contains headlines with levels up
539 to`org-export-headline-levels'. When an integer, include levels
540 up to N in the toc, this may then be different from
541 `org-export-headline-levels', but it will not be allowed to be
542 larger than the number of headline levels. When nil, no table of
543 contents is made.
545 This option can also be set with the #+OPTIONS line,
546 e.g. \"toc:nil\" or \"toc:3\"."
547 :group 'org-export-general
548 :type '(choice
549 (const :tag "No Table of Contents" nil)
550 (const :tag "Full Table of Contents" t)
551 (integer :tag "TOC to level")))
553 (defcustom org-export-with-tables t
554 "If non-nil, lines starting with \"|\" define a table.
555 For example:
557 | Name | Address | Birthday |
558 |-------------+----------+-----------|
559 | Arthur Dent | England | 29.2.2100 |
561 This option can also be set with the #+OPTIONS line, e.g. \"|:nil\"."
562 :group 'org-export-general
563 :type 'boolean)
565 (defcustom org-export-with-tags t
566 "If nil, do not export tags, just remove them from headlines.
568 If this is the symbol `not-in-toc', tags will be removed from
569 table of contents entries, but still be shown in the headlines of
570 the document.
572 This option can also be set with the #+OPTIONS line,
573 e.g. \"tags:nil\"."
574 :group 'org-export-general
575 :type '(choice
576 (const :tag "Off" nil)
577 (const :tag "Not in TOC" not-in-toc)
578 (const :tag "On" t)))
580 (defcustom org-export-with-tasks t
581 "Non-nil means include TODO items for export.
582 This may have the following values:
583 t include tasks independent of state.
584 todo include only tasks that are not yet done.
585 done include only tasks that are already done.
586 nil remove all tasks before export
587 list of keywords keep only tasks with these keywords"
588 :group 'org-export-general
589 :type '(choice
590 (const :tag "All tasks" t)
591 (const :tag "No tasks" nil)
592 (const :tag "Not-done tasks" todo)
593 (const :tag "Only done tasks" done)
594 (repeat :tag "Specific TODO keywords"
595 (string :tag "Keyword"))))
597 (defcustom org-export-time-stamp-file t
598 "Non-nil means insert a time stamp into the exported file.
599 The time stamp shows when the file was created.
601 This option can also be set with the #+OPTIONS line,
602 e.g. \"timestamp:nil\"."
603 :group 'org-export-general
604 :type 'boolean)
606 (defcustom org-export-with-timestamps t
607 "Non nil means allow timestamps in export.
609 It can be set to `active', `inactive', t or nil, in order to
610 export, respectively, only active timestamps, only inactive ones,
611 all of them or none.
613 This option can also be set with the #+OPTIONS line, e.g.
614 \"<:nil\"."
615 :group 'org-export-general
616 :type '(choice
617 (const :tag "All timestamps" t)
618 (const :tag "Only active timestamps" active)
619 (const :tag "Only inactive timestamps" inactive)
620 (const :tag "No timestamp" nil)))
622 (defcustom org-export-with-todo-keywords t
623 "Non-nil means include TODO keywords in export.
624 When nil, remove all these keywords from the export."
625 :group 'org-export-general
626 :type 'boolean)
628 (defcustom org-export-allow-BIND 'confirm
629 "Non-nil means allow #+BIND to define local variable values for export.
630 This is a potential security risk, which is why the user must
631 confirm the use of these lines."
632 :group 'org-export-general
633 :type '(choice
634 (const :tag "Never" nil)
635 (const :tag "Always" t)
636 (const :tag "Ask a confirmation for each file" confirm)))
638 (defcustom org-export-snippet-translation-alist nil
639 "Alist between export snippets back-ends and exporter back-ends.
641 This variable allows to provide shortcuts for export snippets.
643 For example, with a value of '\(\(\"h\" . \"html\"\)\), the HTML
644 back-end will recognize the contents of \"@h{<b>}\" as HTML code
645 while every other back-end will ignore it."
646 :group 'org-export-general
647 :type '(repeat
648 (cons
649 (string :tag "Shortcut")
650 (string :tag "Back-end"))))
652 (defcustom org-export-coding-system nil
653 "Coding system for the exported file."
654 :group 'org-export-general
655 :type 'coding-system)
657 (defcustom org-export-copy-to-kill-ring t
658 "Non-nil means exported stuff will also be pushed onto the kill ring."
659 :group 'org-export-general
660 :type 'boolean)
662 (defcustom org-export-initial-scope 'buffer
663 "The initial scope when exporting with `org-export-dispatch'.
664 This variable can be either set to `buffer' or `subtree'."
665 :group 'org-export-general
666 :type '(choice
667 (const :tag "Export current buffer" 'buffer)
668 (const :tag "Export current subtree" 'subtree)))
670 (defcustom org-export-show-temporary-export-buffer t
671 "Non-nil means show buffer after exporting to temp buffer.
672 When Org exports to a file, the buffer visiting that file is ever
673 shown, but remains buried. However, when exporting to
674 a temporary buffer, that buffer is popped up in a second window.
675 When this variable is nil, the buffer remains buried also in
676 these cases."
677 :group 'org-export-general
678 :type 'boolean)
680 (defcustom org-export-dispatch-use-expert-ui nil
681 "Non-nil means using a non-intrusive `org-export-dispatch'.
682 In that case, no help buffer is displayed. Though, an indicator
683 for current export scope is added to the prompt \(i.e. \"b\" when
684 output is restricted to body only, \"s\" when it is restricted to
685 the current subtree and \"v\" when only visible elements are
686 considered for export\). Also, \[?] allows to switch back to
687 standard mode."
688 :group 'org-export-general
689 :type 'boolean)
693 ;;; Defining New Back-ends
695 (defmacro org-export-define-derived-backend (child parent &rest body)
696 "Create a new back-end as a variant of an existing one.
698 CHILD is the name of the derived back-end. PARENT is the name of
699 the parent back-end.
701 BODY can start with pre-defined keyword arguments. The following
702 keywords are understood:
704 `:filters-alist'
706 Alist of filters that will overwrite or complete filters
707 defined in PARENT back-end, if any.
709 `:options-alist'
711 Alist of buffer keywords or #+OPTIONS items that will
712 overwrite or complete those defined in PARENT back-end, if
713 any.
715 `:translate-alist'
717 Alist of element and object types and transcoders that will
718 overwrite or complete transcode table from PARENT back-end.
720 As an example, here is how one could define \"my-latex\" back-end
721 as a variant of `e-latex' back-end with a custom template
722 function:
724 \(org-export-define-derived-backend my-latex e-latex
725 :translate-alist ((template . my-latex-template-fun)))
727 The back-end could then be called with, for example:
729 \(org-export-to-buffer 'my-latex \"*Test my-latex\")"
730 (declare (debug (&define name symbolp [&rest keywordp sexp] def-body))
731 (indent 2))
732 (let (filters options translate)
733 (while (keywordp (car body))
734 (case (pop body)
735 (:filters-alist (setq filters (pop body)))
736 (:options-alist (setq options (pop body)))
737 (:translate-alist (setq translate (pop body)))
738 (t (pop body))))
739 `(progn
740 ;; Define filters.
741 ,(let ((parent-filters (intern (format "org-%s-filters-alist" parent))))
742 (when (or (boundp parent-filters) filters)
743 `(defconst ,(intern (format "org-%s-filters-alist" child))
744 ',(append filters
745 (and (boundp parent-filters)
746 (copy-sequence (symbol-value parent-filters))))
747 "Alist between filters keywords and back-end specific filters.
748 See `org-export-filters-alist' for more information.")))
749 ;; Define options.
750 ,(let ((parent-options (intern (format "org-%s-options-alist" parent))))
751 (when (or (boundp parent-options) options)
752 `(defconst ,(intern (format "org-%s-options-alist" child))
753 ',(append options
754 (and (boundp parent-options)
755 (copy-sequence (symbol-value parent-options))))
756 "Alist between LaTeX export properties and ways to set them.
757 See `org-export-options-alist' for more information on the
758 structure of the values.")))
759 ;; Define translators.
760 (defvar ,(intern (format "org-%s-translate-alist" child))
761 ',(append translate
762 (copy-sequence
763 (symbol-value
764 (intern (format "org-%s-translate-alist" parent)))))
765 "Alist between element or object types and translators.")
766 ;; Splice in the body, if any.
767 ,@body)))
771 ;;; The Communication Channel
773 ;; During export process, every function has access to a number of
774 ;; properties. They are of two types:
776 ;; 1. Environment options are collected once at the very beginning of
777 ;; the process, out of the original buffer and configuration.
778 ;; Collecting them is handled by `org-export-get-environment'
779 ;; function.
781 ;; Most environment options are defined through the
782 ;; `org-export-options-alist' variable.
784 ;; 2. Tree properties are extracted directly from the parsed tree,
785 ;; just before export, by `org-export-collect-tree-properties'.
787 ;; Here is the full list of properties available during transcode
788 ;; process, with their category (option, tree or local) and their
789 ;; value type.
791 ;; + `:author' :: Author's name.
792 ;; - category :: option
793 ;; - type :: string
795 ;; + `:back-end' :: Current back-end used for transcoding.
796 ;; - category :: tree
797 ;; - type :: symbol
799 ;; + `:creator' :: String to write as creation information.
800 ;; - category :: option
801 ;; - type :: string
803 ;; + `:date' :: String to use as date.
804 ;; - category :: option
805 ;; - type :: string
807 ;; + `:description' :: Description text for the current data.
808 ;; - category :: option
809 ;; - type :: string
811 ;; + `:email' :: Author's email.
812 ;; - category :: option
813 ;; - type :: string
815 ;; + `:exclude-tags' :: Tags for exclusion of subtrees from export
816 ;; process.
817 ;; - category :: option
818 ;; - type :: list of strings
820 ;; + `:footnote-definition-alist' :: Alist between footnote labels and
821 ;; their definition, as parsed data. Only non-inlined footnotes
822 ;; are represented in this alist. Also, every definition isn't
823 ;; guaranteed to be referenced in the parse tree. The purpose of
824 ;; this property is to preserve definitions from oblivion
825 ;; (i.e. when the parse tree comes from a part of the original
826 ;; buffer), it isn't meant for direct use in a back-end. To
827 ;; retrieve a definition relative to a reference, use
828 ;; `org-export-get-footnote-definition' instead.
829 ;; - category :: option
830 ;; - type :: alist (STRING . LIST)
832 ;; + `:headline-levels' :: Maximum level being exported as an
833 ;; headline. Comparison is done with the relative level of
834 ;; headlines in the parse tree, not necessarily with their
835 ;; actual level.
836 ;; - category :: option
837 ;; - type :: integer
839 ;; + `:headline-offset' :: Difference between relative and real level
840 ;; of headlines in the parse tree. For example, a value of -1
841 ;; means a level 2 headline should be considered as level
842 ;; 1 (cf. `org-export-get-relative-level').
843 ;; - category :: tree
844 ;; - type :: integer
846 ;; + `:headline-numbering' :: Alist between headlines and their
847 ;; numbering, as a list of numbers
848 ;; (cf. `org-export-get-headline-number').
849 ;; - category :: tree
850 ;; - type :: alist (INTEGER . LIST)
852 ;; + `:ignore-list' :: List of elements and objects that should be
853 ;; ignored during export.
854 ;; - category :: tree
855 ;; - type :: list of elements and objects
857 ;; + `:input-file' :: Full path to input file, if any.
858 ;; - category :: option
859 ;; - type :: string or nil
861 ;; + `:keywords' :: List of keywords attached to data.
862 ;; - category :: option
863 ;; - type :: string
865 ;; + `:language' :: Default language used for translations.
866 ;; - category :: option
867 ;; - type :: string
869 ;; + `:parse-tree' :: Whole parse tree, available at any time during
870 ;; transcoding.
871 ;; - category :: option
872 ;; - type :: list (as returned by `org-element-parse-buffer')
874 ;; + `:preserve-breaks' :: Non-nil means transcoding should preserve
875 ;; all line breaks.
876 ;; - category :: option
877 ;; - type :: symbol (nil, t)
879 ;; + `:section-numbers' :: Non-nil means transcoding should add
880 ;; section numbers to headlines.
881 ;; - category :: option
882 ;; - type :: symbol (nil, t)
884 ;; + `:select-tags' :: List of tags enforcing inclusion of sub-trees
885 ;; in transcoding. When such a tag is present, subtrees without
886 ;; it are de facto excluded from the process. See
887 ;; `use-select-tags'.
888 ;; - category :: option
889 ;; - type :: list of strings
891 ;; + `:target-list' :: List of targets encountered in the parse tree.
892 ;; This is used to partly resolve "fuzzy" links
893 ;; (cf. `org-export-resolve-fuzzy-link').
894 ;; - category :: tree
895 ;; - type :: list of strings
897 ;; + `:time-stamp-file' :: Non-nil means transcoding should insert
898 ;; a time stamp in the output.
899 ;; - category :: option
900 ;; - type :: symbol (nil, t)
902 ;; + `:translate-alist' :: Alist between element and object types and
903 ;; transcoding functions relative to the current back-end.
904 ;; Special keys `template' and `plain-text' are also possible.
905 ;; - category :: option
906 ;; - type :: alist (SYMBOL . FUNCTION)
908 ;; + `:with-archived-trees' :: Non-nil when archived subtrees should
909 ;; also be transcoded. If it is set to the `headline' symbol,
910 ;; only the archived headline's name is retained.
911 ;; - category :: option
912 ;; - type :: symbol (nil, t, `headline')
914 ;; + `:with-author' :: Non-nil means author's name should be included
915 ;; in the output.
916 ;; - category :: option
917 ;; - type :: symbol (nil, t)
919 ;; + `:with-clocks' :: Non-nild means clock keywords should be exported.
920 ;; - category :: option
921 ;; - type :: symbol (nil, t)
923 ;; + `:with-creator' :: Non-nild means a creation sentence should be
924 ;; inserted at the end of the transcoded string. If the value
925 ;; is `comment', it should be commented.
926 ;; - category :: option
927 ;; - type :: symbol (`comment', nil, t)
929 ;; + `:with-drawers' :: Non-nil means drawers should be exported. If
930 ;; its value is a list of names, only drawers with such names
931 ;; will be transcoded.
932 ;; - category :: option
933 ;; - type :: symbol (nil, t) or list of strings
935 ;; + `:with-email' :: Non-nil means output should contain author's
936 ;; email.
937 ;; - category :: option
938 ;; - type :: symbol (nil, t)
940 ;; + `:with-emphasize' :: Non-nil means emphasized text should be
941 ;; interpreted.
942 ;; - category :: option
943 ;; - type :: symbol (nil, t)
945 ;; + `:with-fixed-width' :: Non-nil if transcoder should interpret
946 ;; strings starting with a colon as a fixed-with (verbatim) area.
947 ;; - category :: option
948 ;; - type :: symbol (nil, t)
950 ;; + `:with-footnotes' :: Non-nil if transcoder should interpret
951 ;; footnotes.
952 ;; - category :: option
953 ;; - type :: symbol (nil, t)
955 ;; + `:with-plannings' :: Non-nil means transcoding should include
956 ;; planning info.
957 ;; - category :: option
958 ;; - type :: symbol (nil, t)
960 ;; + `:with-priority' :: Non-nil means transcoding should include
961 ;; priority cookies.
962 ;; - category :: option
963 ;; - type :: symbol (nil, t)
965 ;; + `:with-special-strings' :: Non-nil means transcoding should
966 ;; interpret special strings in plain text.
967 ;; - category :: option
968 ;; - type :: symbol (nil, t)
970 ;; + `:with-sub-superscript' :: Non-nil means transcoding should
971 ;; interpret subscript and superscript. With a value of "{}",
972 ;; only interpret those using curly brackets.
973 ;; - category :: option
974 ;; - type :: symbol (nil, {}, t)
976 ;; + `:with-tables' :: Non-nil means transcoding should interpret
977 ;; tables.
978 ;; - category :: option
979 ;; - type :: symbol (nil, t)
981 ;; + `:with-tags' :: Non-nil means transcoding should keep tags in
982 ;; headlines. A `not-in-toc' value will remove them from the
983 ;; table of contents, if any, nonetheless.
984 ;; - category :: option
985 ;; - type :: symbol (nil, t, `not-in-toc')
987 ;; + `:with-tasks' :: Non-nil means transcoding should include
988 ;; headlines with a TODO keyword. A `todo' value will only
989 ;; include headlines with a todo type keyword while a `done'
990 ;; value will do the contrary. If a list of strings is provided,
991 ;; only tasks with keywords belonging to that list will be kept.
992 ;; - category :: option
993 ;; - type :: symbol (t, todo, done, nil) or list of strings
995 ;; + `:with-timestamps' :: Non-nil means transcoding should include
996 ;; time stamps. Special value `active' (resp. `inactive') ask to
997 ;; export only active (resp. inactive) timestamps. Otherwise,
998 ;; completely remove them.
999 ;; - category :: option
1000 ;; - type :: symbol: (`active', `inactive', t, nil)
1002 ;; + `:with-toc' :: Non-nil means that a table of contents has to be
1003 ;; added to the output. An integer value limits its depth.
1004 ;; - category :: option
1005 ;; - type :: symbol (nil, t or integer)
1007 ;; + `:with-todo-keywords' :: Non-nil means transcoding should
1008 ;; include TODO keywords.
1009 ;; - category :: option
1010 ;; - type :: symbol (nil, t)
1013 ;;;; Environment Options
1015 ;; Environment options encompass all parameters defined outside the
1016 ;; scope of the parsed data. They come from five sources, in
1017 ;; increasing precedence order:
1019 ;; - Global variables,
1020 ;; - Buffer's attributes,
1021 ;; - Options keyword symbols,
1022 ;; - Buffer keywords,
1023 ;; - Subtree properties.
1025 ;; The central internal function with regards to environment options
1026 ;; is `org-export-get-environment'. It updates global variables with
1027 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
1028 ;; the different sources.
1030 ;; The internal functions doing the retrieval are:
1031 ;; `org-export-get-global-options',
1032 ;; `org-export-get-buffer-attributes',
1033 ;; `org-export-parse-option-keyword',
1034 ;; `org-export-get-subtree-options' and
1035 ;; `org-export-get-inbuffer-options'
1037 ;; Also, `org-export-confirm-letbind' and `org-export-install-letbind'
1038 ;; take care of the part relative to "#+BIND:" keywords.
1040 (defun org-export-get-environment (&optional backend subtreep ext-plist)
1041 "Collect export options from the current buffer.
1043 Optional argument BACKEND is a symbol specifying which back-end
1044 specific options to read, if any.
1046 When optional argument SUBTREEP is non-nil, assume the export is
1047 done against the current sub-tree.
1049 Third optional argument EXT-PLIST is a property list with
1050 external parameters overriding Org default settings, but still
1051 inferior to file-local settings."
1052 ;; First install #+BIND variables.
1053 (org-export-install-letbind-maybe)
1054 ;; Get and prioritize export options...
1055 (org-combine-plists
1056 ;; ... from global variables...
1057 (org-export-get-global-options backend)
1058 ;; ... from buffer's attributes...
1059 (org-export-get-buffer-attributes)
1060 ;; ... from an external property list...
1061 ext-plist
1062 ;; ... from in-buffer settings...
1063 (org-export-get-inbuffer-options
1064 backend
1065 (and buffer-file-name (org-remove-double-quotes buffer-file-name)))
1066 ;; ... and from subtree, when appropriate.
1067 (and subtreep (org-export-get-subtree-options))
1068 ;; Also install back-end symbol and its translation table.
1069 `(:back-end
1070 ,backend
1071 :translate-alist
1072 ,(let ((trans-alist (intern (format "org-%s-translate-alist" backend))))
1073 (when (boundp trans-alist) (symbol-value trans-alist))))))
1075 (defun org-export-parse-option-keyword (options &optional backend)
1076 "Parse an OPTIONS line and return values as a plist.
1077 Optional argument BACKEND is a symbol specifying which back-end
1078 specific items to read, if any."
1079 (let* ((all
1080 (append org-export-options-alist
1081 (and backend
1082 (let ((var (intern
1083 (format "org-%s-options-alist" backend))))
1084 (and (boundp var) (eval var))))))
1085 ;; Build an alist between #+OPTION: item and property-name.
1086 (alist (delq nil
1087 (mapcar (lambda (e)
1088 (when (nth 2 e) (cons (regexp-quote (nth 2 e))
1089 (car e))))
1090 all)))
1091 plist)
1092 (mapc (lambda (e)
1093 (when (string-match (concat "\\(\\`\\|[ \t]\\)"
1094 (car e)
1095 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
1096 options)
1097 (setq plist (plist-put plist
1098 (cdr e)
1099 (car (read-from-string
1100 (match-string 2 options)))))))
1101 alist)
1102 plist))
1104 (defun org-export-get-subtree-options ()
1105 "Get export options in subtree at point.
1107 Assume point is at subtree's beginning.
1109 Return options as a plist."
1110 (let (prop plist)
1111 (when (setq prop (progn (looking-at org-todo-line-regexp)
1112 (or (save-match-data
1113 (org-entry-get (point) "EXPORT_TITLE"))
1114 (org-match-string-no-properties 3))))
1115 (setq plist
1116 (plist-put
1117 plist :title
1118 (org-element-parse-secondary-string
1119 prop
1120 (cdr (assq 'keyword org-element-string-restrictions))))))
1121 (when (setq prop (org-entry-get (point) "EXPORT_TEXT"))
1122 (setq plist (plist-put plist :text prop)))
1123 (when (setq prop (org-entry-get (point) "EXPORT_AUTHOR"))
1124 (setq plist (plist-put plist :author prop)))
1125 (when (setq prop (org-entry-get (point) "EXPORT_DATE"))
1126 (setq plist (plist-put plist :date prop)))
1127 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
1128 (setq plist (org-export-add-options-to-plist plist prop)))
1129 plist))
1131 (defun org-export-get-inbuffer-options (&optional backend files)
1132 "Return current buffer export options, as a plist.
1134 Optional argument BACKEND, when non-nil, is a symbol specifying
1135 which back-end specific options should also be read in the
1136 process.
1138 Optional argument FILES is a list of setup files names read so
1139 far, used to avoid circular dependencies.
1141 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1142 (org-with-wide-buffer
1143 (goto-char (point-min))
1144 (let ((case-fold-search t) plist)
1145 ;; 1. Special keywords, as in `org-export-special-keywords'.
1146 (let ((special-re (org-make-options-regexp org-export-special-keywords)))
1147 (while (re-search-forward special-re nil t)
1148 (let ((element (org-element-at-point)))
1149 (when (eq (org-element-type element) 'keyword)
1150 (let* ((key (org-element-property :key element))
1151 (val (org-element-property :value element))
1152 (prop
1153 (cond
1154 ((string= key "SETUP_FILE")
1155 (let ((file
1156 (expand-file-name
1157 (org-remove-double-quotes (org-trim val)))))
1158 ;; Avoid circular dependencies.
1159 (unless (member file files)
1160 (with-temp-buffer
1161 (insert (org-file-contents file 'noerror))
1162 (org-mode)
1163 (org-export-get-inbuffer-options
1164 backend (cons file files))))))
1165 ((string= key "OPTIONS")
1166 (org-export-parse-option-keyword val backend))
1167 ((string= key "MACRO")
1168 (when (string-match
1169 "^\\([-a-zA-Z0-9_]+\\)\\(?:[ \t]+\\(.*?\\)[ \t]*$\\)?"
1170 val)
1171 (let ((key
1172 (intern
1173 (concat ":macro-"
1174 (downcase (match-string 1 val)))))
1175 (value (org-match-string-no-properties 2 val)))
1176 (cond
1177 ((not value) nil)
1178 ;; Value will be evaled: do not parse it.
1179 ((string-match "\\`(eval\\>" value)
1180 (list key (list value)))
1181 ;; Value has to be parsed for nested
1182 ;; macros.
1184 (list
1186 (let ((restr (org-element-restriction 'macro)))
1187 (org-element-parse-secondary-string
1188 ;; If user explicitly asks for
1189 ;; a newline, be sure to preserve it
1190 ;; from further filling with
1191 ;; `hard-newline'. Also replace
1192 ;; "\\n" with "\n", "\\\n" with "\\n"
1193 ;; and so on...
1194 (replace-regexp-in-string
1195 "\\(\\\\\\\\\\)n" "\\\\"
1196 (replace-regexp-in-string
1197 "\\(?:^\\|[^\\\\]\\)\\(\\\\n\\)"
1198 hard-newline value nil nil 1)
1199 nil nil 1)
1200 restr)))))))))))
1201 (setq plist (org-combine-plists plist prop)))))))
1202 ;; 2. Standard options, as in `org-export-options-alist'.
1203 (let* ((all (append org-export-options-alist
1204 ;; Also look for back-end specific options
1205 ;; if BACKEND is defined.
1206 (and backend
1207 (let ((var
1208 (intern
1209 (format "org-%s-options-alist" backend))))
1210 (and (boundp var) (eval var))))))
1211 ;; Build alist between keyword name and property name.
1212 (alist
1213 (delq nil (mapcar
1214 (lambda (e) (when (nth 1 e) (cons (nth 1 e) (car e))))
1215 all)))
1216 ;; Build regexp matching all keywords associated to export
1217 ;; options. Note: the search is case insensitive.
1218 (opt-re (org-make-options-regexp
1219 (delq nil (mapcar (lambda (e) (nth 1 e)) all)))))
1220 (goto-char (point-min))
1221 (while (re-search-forward opt-re nil t)
1222 (let ((element (org-element-at-point)))
1223 (when (eq (org-element-type element) 'keyword)
1224 (let* ((key (org-element-property :key element))
1225 (val (org-element-property :value element))
1226 (prop (cdr (assoc key alist)))
1227 (behaviour (nth 4 (assq prop all))))
1228 (setq plist
1229 (plist-put
1230 plist prop
1231 ;; Handle value depending on specified BEHAVIOUR.
1232 (case behaviour
1233 (space
1234 (if (not (plist-get plist prop)) (org-trim val)
1235 (concat (plist-get plist prop) " " (org-trim val))))
1236 (newline
1237 (org-trim
1238 (concat (plist-get plist prop) "\n" (org-trim val))))
1239 (split
1240 `(,@(plist-get plist prop) ,@(org-split-string val)))
1241 ('t val)
1242 (otherwise (if (not (plist-member plist prop)) val
1243 (plist-get plist prop))))))))))
1244 ;; Parse keywords specified in `org-element-parsed-keywords'.
1245 (mapc
1246 (lambda (key)
1247 (let* ((prop (cdr (assoc key alist)))
1248 (value (and prop (plist-get plist prop))))
1249 (when (stringp value)
1250 (setq plist
1251 (plist-put
1252 plist prop
1253 (org-element-parse-secondary-string
1254 value (org-element-restriction 'keyword)))))))
1255 org-element-parsed-keywords))
1256 ;; 3. Return final value.
1257 plist)))
1259 (defun org-export-get-buffer-attributes ()
1260 "Return properties related to buffer attributes, as a plist."
1261 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
1262 (list
1263 ;; Store full path of input file name, or nil. For internal use.
1264 :input-file visited-file
1265 :title (or (and visited-file
1266 (file-name-sans-extension
1267 (file-name-nondirectory visited-file)))
1268 (buffer-name (buffer-base-buffer)))
1269 :macro-modification-time
1270 (and visited-file
1271 (file-exists-p visited-file)
1272 (concat "(eval (format-time-string \"$1\" '"
1273 (prin1-to-string (nth 5 (file-attributes visited-file)))
1274 "))"))
1275 ;; Store input file name as a macro.
1276 :macro-input-file (and visited-file (file-name-nondirectory visited-file))
1277 ;; `:macro-date', `:macro-time' and `:macro-property' could as
1278 ;; well be initialized as tree properties, since they don't
1279 ;; depend on buffer properties. Though, it may be more logical
1280 ;; to keep them close to other ":macro-" properties.
1281 :macro-date "(eval (format-time-string \"$1\"))"
1282 :macro-time "(eval (format-time-string \"$1\"))"
1283 :macro-property "(eval (org-entry-get nil \"$1\" 'selective))")))
1285 (defun org-export-get-global-options (&optional backend)
1286 "Return global export options as a plist.
1288 Optional argument BACKEND, if non-nil, is a symbol specifying
1289 which back-end specific export options should also be read in the
1290 process."
1291 (let ((all (append org-export-options-alist
1292 (and backend
1293 (let ((var (intern
1294 (format "org-%s-options-alist" backend))))
1295 (and (boundp var) (eval var))))))
1296 ;; Output value.
1297 plist)
1298 (mapc (lambda (cell)
1299 (setq plist (plist-put plist (car cell) (eval (nth 3 cell)))))
1300 all)
1301 ;; Return value.
1302 plist))
1304 (defun org-export-store-footnote-definitions (info)
1305 "Collect and store footnote definitions from current buffer in INFO.
1307 INFO is a plist containing export options.
1309 Footnotes definitions are stored as a alist whose CAR is
1310 footnote's label, as a string, and CDR the contents, as a parse
1311 tree. This alist will be consed to the value of
1312 `:footnote-definition-alist' in INFO, if any.
1314 The new plist is returned; use
1316 \(setq info (org-export-store-footnote-definitions info))
1318 to be sure to use the new value. INFO is modified by side
1319 effects."
1320 ;; Footnotes definitions must be collected in the original buffer,
1321 ;; as there's no insurance that they will still be in the parse
1322 ;; tree, due to some narrowing.
1323 (plist-put
1324 info :footnote-definition-alist
1325 (let ((alist (plist-get info :footnote-definition-alist)))
1326 (org-with-wide-buffer
1327 (goto-char (point-min))
1328 (while (re-search-forward org-footnote-definition-re nil t)
1329 (let ((def (org-footnote-at-definition-p)))
1330 (when def
1331 (org-skip-whitespace)
1332 (push (cons (car def)
1333 (save-restriction
1334 (narrow-to-region (point) (nth 2 def))
1335 ;; Like `org-element-parse-buffer', but
1336 ;; makes sure the definition doesn't start
1337 ;; with a section element.
1338 (nconc
1339 (list 'org-data nil)
1340 (org-element-parse-elements
1341 (point-min) (point-max) nil nil nil nil nil))))
1342 alist))))
1343 alist))))
1345 (defvar org-export-allow-BIND-local nil)
1346 (defun org-export-confirm-letbind ()
1347 "Can we use #+BIND values during export?
1348 By default this will ask for confirmation by the user, to divert
1349 possible security risks."
1350 (cond
1351 ((not org-export-allow-BIND) nil)
1352 ((eq org-export-allow-BIND t) t)
1353 ((local-variable-p 'org-export-allow-BIND-local) org-export-allow-BIND-local)
1354 (t (org-set-local 'org-export-allow-BIND-local
1355 (yes-or-no-p "Allow BIND values in this buffer? ")))))
1357 (defun org-export-install-letbind-maybe ()
1358 "Install the values from #+BIND lines as local variables.
1359 Variables must be installed before in-buffer options are
1360 retrieved."
1361 (let (letbind pair)
1362 (org-with-wide-buffer
1363 (goto-char (point-min))
1364 (while (re-search-forward (org-make-options-regexp '("BIND")) nil t)
1365 (when (org-export-confirm-letbind)
1366 (push (read (concat "(" (org-match-string-no-properties 2) ")"))
1367 letbind))))
1368 (while (setq pair (pop letbind))
1369 (org-set-local (car pair) (nth 1 pair)))))
1372 ;;;; Tree Properties
1374 ;; Tree properties are infromation extracted from parse tree. They
1375 ;; are initialized at the beginning of the transcoding process by
1376 ;; `org-export-collect-tree-properties'.
1378 ;; Dedicated functions focus on computing the value of specific tree
1379 ;; properties during initialization. Thus,
1380 ;; `org-export-populate-ignore-list' lists elements and objects that
1381 ;; should be skipped during export, `org-export-get-min-level' gets
1382 ;; the minimal exportable level, used as a basis to compute relative
1383 ;; level for headlines. Eventually
1384 ;; `org-export-collect-headline-numbering' builds an alist between
1385 ;; headlines and their numbering.
1387 (defun org-export-collect-tree-properties (data info)
1388 "Extract tree properties from parse tree.
1390 DATA is the parse tree from which information is retrieved. INFO
1391 is a list holding export options.
1393 Following tree properties are set or updated:
1394 `:footnote-definition-alist' List of footnotes definitions in
1395 original buffer and current parse tree.
1397 `:headline-offset' Offset between true level of headlines and
1398 local level. An offset of -1 means an headline
1399 of level 2 should be considered as a level
1400 1 headline in the context.
1402 `:headline-numbering' Alist of all headlines as key an the
1403 associated numbering as value.
1405 `:ignore-list' List of elements that should be ignored during
1406 export.
1408 `:target-list' List of all targets in the parse tree."
1409 ;; Install the parse tree in the communication channel, in order to
1410 ;; use `org-export-get-genealogy' and al.
1411 (setq info (plist-put info :parse-tree data))
1412 ;; Get the list of elements and objects to ignore, and put it into
1413 ;; `:ignore-list'. Do not overwrite any user ignore that might have
1414 ;; been done during parse tree filtering.
1415 (setq info
1416 (plist-put info
1417 :ignore-list
1418 (append (org-export-populate-ignore-list data info)
1419 (plist-get info :ignore-list))))
1420 ;; Compute `:headline-offset' in order to be able to use
1421 ;; `org-export-get-relative-level'.
1422 (setq info
1423 (plist-put info
1424 :headline-offset (- 1 (org-export-get-min-level data info))))
1425 ;; Update footnotes definitions list with definitions in parse tree.
1426 ;; This is required since buffer expansion might have modified
1427 ;; boundaries of footnote definitions contained in the parse tree.
1428 ;; This way, definitions in `footnote-definition-alist' are bound to
1429 ;; match those in the parse tree.
1430 (let ((defs (plist-get info :footnote-definition-alist)))
1431 (org-element-map
1432 data 'footnote-definition
1433 (lambda (fn)
1434 (push (cons (org-element-property :label fn)
1435 `(org-data nil ,@(org-element-contents fn)))
1436 defs)))
1437 (setq info (plist-put info :footnote-definition-alist defs)))
1438 ;; Properties order doesn't matter: get the rest of the tree
1439 ;; properties.
1440 (nconc
1441 `(:target-list
1442 ,(org-element-map
1443 data '(keyword target)
1444 (lambda (blob)
1445 (when (or (eq (org-element-type blob) 'target)
1446 (string= (org-element-property :key blob) "TARGET"))
1447 blob)) info)
1448 :headline-numbering ,(org-export-collect-headline-numbering data info))
1449 info))
1451 (defun org-export-get-min-level (data options)
1452 "Return minimum exportable headline's level in DATA.
1453 DATA is parsed tree as returned by `org-element-parse-buffer'.
1454 OPTIONS is a plist holding export options."
1455 (catch 'exit
1456 (let ((min-level 10000))
1457 (mapc
1458 (lambda (blob)
1459 (when (and (eq (org-element-type blob) 'headline)
1460 (not (member blob (plist-get options :ignore-list))))
1461 (setq min-level
1462 (min (org-element-property :level blob) min-level)))
1463 (when (= min-level 1) (throw 'exit 1)))
1464 (org-element-contents data))
1465 ;; If no headline was found, for the sake of consistency, set
1466 ;; minimum level to 1 nonetheless.
1467 (if (= min-level 10000) 1 min-level))))
1469 (defun org-export-collect-headline-numbering (data options)
1470 "Return numbering of all exportable headlines in a parse tree.
1472 DATA is the parse tree. OPTIONS is the plist holding export
1473 options.
1475 Return an alist whose key is an headline and value is its
1476 associated numbering \(in the shape of a list of numbers\)."
1477 (let ((numbering (make-vector org-export-max-depth 0)))
1478 (org-element-map
1479 data
1480 'headline
1481 (lambda (headline)
1482 (let ((relative-level
1483 (1- (org-export-get-relative-level headline options))))
1484 (cons
1485 headline
1486 (loop for n across numbering
1487 for idx from 0 to org-export-max-depth
1488 when (< idx relative-level) collect n
1489 when (= idx relative-level) collect (aset numbering idx (1+ n))
1490 when (> idx relative-level) do (aset numbering idx 0)))))
1491 options)))
1493 (defun org-export-populate-ignore-list (data options)
1494 "Return list of elements and objects to ignore during export.
1495 DATA is the parse tree to traverse. OPTIONS is the plist holding
1496 export options."
1497 (let (ignore
1498 (walk-data
1499 (function
1500 (lambda (data options selected)
1501 ;; Collect ignored elements or objects into IGNORE-LIST.
1502 (mapc
1503 (lambda (el)
1504 (if (org-export--skip-p el options selected) (push el ignore)
1505 (let ((type (org-element-type el)))
1506 (if (and (eq (plist-get info :with-archived-trees) 'headline)
1507 (eq (org-element-type el) 'headline)
1508 (org-element-property :archivedp el))
1509 ;; If headline is archived but tree below has
1510 ;; to be skipped, add it to ignore list.
1511 (mapc (lambda (e) (push e ignore))
1512 (org-element-contents el))
1513 ;; Move into recursive objects/elements.
1514 (when (org-element-contents el)
1515 (funcall walk-data el options selected))))))
1516 (org-element-contents data))))))
1517 ;; Main call. First find trees containing a select tag, if any.
1518 (funcall walk-data data options (org-export--selected-trees data options))
1519 ;; Return value.
1520 ignore))
1522 (defun org-export--selected-trees (data info)
1523 "Return list of headlines containing a select tag in their tree.
1524 DATA is parsed data as returned by `org-element-parse-buffer'.
1525 INFO is a plist holding export options."
1526 (let (selected-trees
1527 (walk-data
1528 (function
1529 (lambda (data genealogy)
1530 (case (org-element-type data)
1531 (org-data (mapc (lambda (el) (funcall walk-data el genealogy))
1532 (org-element-contents data)))
1533 (headline
1534 (let ((tags (org-element-property :tags data)))
1535 (if (loop for tag in (plist-get info :select-tags)
1536 thereis (member tag tags))
1537 ;; When a select tag is found, mark full
1538 ;; genealogy and every headline within the tree
1539 ;; as acceptable.
1540 (setq selected-trees
1541 (append
1542 genealogy
1543 (org-element-map data 'headline 'identity)
1544 selected-trees))
1545 ;; Else, continue searching in tree, recursively.
1546 (mapc
1547 (lambda (el) (funcall walk-data el (cons data genealogy)))
1548 (org-element-contents data))))))))))
1549 (funcall walk-data data nil) selected-trees))
1551 (defun org-export--skip-p (blob options selected)
1552 "Non-nil when element or object BLOB should be skipped during export.
1553 OPTIONS is the plist holding export options. SELECTED, when
1554 non-nil, is a list of headlines belonging to a tree with a select
1555 tag."
1556 (case (org-element-type blob)
1557 ;; Check headline.
1558 (headline
1559 (let ((with-tasks (plist-get options :with-tasks))
1560 (todo (org-element-property :todo-keyword blob))
1561 (todo-type (org-element-property :todo-type blob))
1562 (archived (plist-get options :with-archived-trees))
1563 (tags (org-element-property :tags blob)))
1565 ;; Ignore subtrees with an exclude tag.
1566 (loop for k in (plist-get options :exclude-tags)
1567 thereis (member k tags))
1568 ;; When a select tag is present in the buffer, ignore any tree
1569 ;; without it.
1570 (and selected (not (member blob selected)))
1571 ;; Ignore commented sub-trees.
1572 (org-element-property :commentedp blob)
1573 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
1574 (and (not archived) (org-element-property :archivedp blob))
1575 ;; Ignore tasks, if specified by `:with-tasks' property.
1576 (and todo
1577 (or (not with-tasks)
1578 (and (memq with-tasks '(todo done))
1579 (not (eq todo-type with-tasks)))
1580 (and (consp with-tasks) (not (member todo with-tasks))))))))
1581 ;; Check timestamp.
1582 (timestamp
1583 (case (plist-get options :with-timestamps)
1584 ;; No timestamp allowed.
1585 ('nil t)
1586 ;; Only active timestamps allowed and the current one isn't
1587 ;; active.
1588 (active
1589 (not (memq (org-element-property :type blob)
1590 '(active active-range))))
1591 ;; Only inactive timestamps allowed and the current one isn't
1592 ;; inactive.
1593 (inactive
1594 (not (memq (org-element-property :type blob)
1595 '(inactive inactive-range))))))
1596 ;; Check drawer.
1597 (drawer
1598 (or (not (plist-get options :with-drawers))
1599 (and (consp (plist-get options :with-drawers))
1600 (not (member (org-element-property :drawer-name blob)
1601 (plist-get options :with-drawers))))))
1602 ;; Check table-row.
1603 (table-row (org-export-table-row-is-special-p blob options))
1604 ;; Check table-cell.
1605 (table-cell
1606 (and (org-export-table-has-special-column-p
1607 (nth 1 (org-export-get-genealogy blob options)))
1608 (not (org-export-get-previous-element blob options))))
1609 ;; Check clock.
1610 (clock (not (plist-get options :with-clocks)))
1611 ;; Check planning.
1612 (planning (not (plist-get options :with-plannings)))))
1616 ;;; The Transcoder
1618 ;; `org-export-data' reads a parse tree (obtained with, i.e.
1619 ;; `org-element-parse-buffer') and transcodes it into a specified
1620 ;; back-end output. It takes care of filtering out elements or
1621 ;; objects according to export options and organizing the output blank
1622 ;; lines and white space are preserved.
1624 ;; Internally, three functions handle the filtering of objects and
1625 ;; elements during the export. In particular,
1626 ;; `org-export-ignore-element' marks an element or object so future
1627 ;; parse tree traversals skip it, `org-export-interpret-p' tells which
1628 ;; elements or objects should be seen as real Org syntax and
1629 ;; `org-export-expand' transforms the others back into their original
1630 ;; shape
1632 ;; `org-export-transcoder' is an accessor returning appropriate
1633 ;; translator function for a given element or object.
1635 (defun org-export-transcoder (blob info)
1636 "Return appropriate transcoder for BLOB.
1637 INFO is a plist containing export directives."
1638 (let ((type (org-element-type blob)))
1639 ;; Return contents only for complete parse trees.
1640 (if (eq type 'org-data) (lambda (blob contents info) contents)
1641 (let ((transcoder (cdr (assq type (plist-get info :translate-alist)))))
1642 (and (fboundp transcoder) transcoder)))))
1644 (defun org-export-data (data info)
1645 "Convert DATA into current back-end format.
1647 DATA is a parse tree, an element or an object or a secondary
1648 string. INFO is a plist holding export options.
1650 Return transcoded string."
1651 (let* ((type (org-element-type data))
1652 (results
1653 (cond
1654 ;; Ignored element/object.
1655 ((member data (plist-get info :ignore-list)) nil)
1656 ;; Plain text.
1657 ((eq type 'plain-text)
1658 (org-export-filter-apply-functions
1659 (plist-get info :filter-plain-text)
1660 (let ((transcoder (org-export-transcoder data info)))
1661 (if transcoder (funcall transcoder data info) data))
1662 info))
1663 ;; Uninterpreted element/object: change it back to Org
1664 ;; syntax and export again resulting raw string.
1665 ((not (org-export-interpret-p data info))
1666 (org-export-data
1667 (org-export-expand
1668 data
1669 (mapconcat (lambda (blob) (org-export-data blob info))
1670 (org-element-contents data)
1671 ""))
1672 info))
1673 ;; Secondary string.
1674 ((not type)
1675 (mapconcat (lambda (obj) (org-export-data obj info)) data ""))
1676 ;; Element/Object without contents or, as a special case,
1677 ;; headline with archive tag and archived trees restricted
1678 ;; to title only.
1679 ((or (not (org-element-contents data))
1680 (and (eq type 'headline)
1681 (eq (plist-get info :with-archived-trees) 'headline)
1682 (org-element-property :archivedp data)))
1683 (let ((transcoder (org-export-transcoder data info)))
1684 (and (fboundp transcoder) (funcall transcoder data nil info))))
1685 ;; Element/Object with contents.
1687 (let ((transcoder (org-export-transcoder data info)))
1688 (when transcoder
1689 (let* ((greaterp (memq type org-element-greater-elements))
1690 (objectp (and (not greaterp)
1691 (memq type org-element-recursive-objects)))
1692 (contents
1693 (mapconcat
1694 (lambda (element) (org-export-data element info))
1695 (org-element-contents
1696 (if (or greaterp objectp) data
1697 ;; Elements directly containing objects
1698 ;; must have their indentation normalized
1699 ;; first.
1700 (org-element-normalize-contents
1701 data
1702 ;; When normalizing contents of the first
1703 ;; paragraph in an item or a footnote
1704 ;; definition, ignore first line's
1705 ;; indentation: there is none and it
1706 ;; might be misleading.
1707 (when (eq type 'paragraph)
1708 (let ((parent (org-export-get-parent data info)))
1709 (and (equal (car (org-element-contents parent))
1710 data)
1711 (memq (org-element-type parent)
1712 '(footnote-definition item))))))))
1713 "")))
1714 (funcall transcoder data
1715 (if greaterp (org-element-normalize-string contents)
1716 contents)
1717 info))))))))
1718 (cond
1719 ((not results) nil)
1720 ((memq type '(org-data plain-text nil)) results)
1721 ;; Append the same white space between elements or objects as in
1722 ;; the original buffer, and call appropriate filters.
1724 (let ((results
1725 (org-export-filter-apply-functions
1726 (plist-get info (intern (format ":filter-%s" type)))
1727 (let ((post-blank (org-element-property :post-blank data)))
1728 (if (memq type org-element-all-elements)
1729 (concat (org-element-normalize-string results)
1730 (make-string post-blank ?\n))
1731 (concat results (make-string post-blank ? ))))
1732 info)))
1733 ;; Eventually return string.
1734 results)))))
1736 (defun org-export-interpret-p (blob info)
1737 "Non-nil if element or object BLOB should be interpreted as Org syntax.
1738 Check is done according to export options INFO, stored as
1739 a plist."
1740 (case (org-element-type blob)
1741 ;; ... entities...
1742 (entity (plist-get info :with-entities))
1743 ;; ... emphasis...
1744 (emphasis (plist-get info :with-emphasize))
1745 ;; ... fixed-width areas.
1746 (fixed-width (plist-get info :with-fixed-width))
1747 ;; ... footnotes...
1748 ((footnote-definition footnote-reference)
1749 (plist-get info :with-footnotes))
1750 ;; ... sub/superscripts...
1751 ((subscript superscript)
1752 (let ((sub/super-p (plist-get info :with-sub-superscript)))
1753 (if (eq sub/super-p '{})
1754 (org-element-property :use-brackets-p blob)
1755 sub/super-p)))
1756 ;; ... tables...
1757 (table (plist-get info :with-tables))
1758 (otherwise t)))
1760 (defsubst org-export-expand (blob contents)
1761 "Expand a parsed element or object to its original state.
1762 BLOB is either an element or an object. CONTENTS is its
1763 contents, as a string or nil."
1764 (funcall
1765 (intern (format "org-element-%s-interpreter" (org-element-type blob)))
1766 blob contents))
1768 (defun org-export-ignore-element (element info)
1769 "Add ELEMENT to `:ignore-list' in INFO.
1771 Any element in `:ignore-list' will be skipped when using
1772 `org-element-map'. INFO is modified by side effects."
1773 (plist-put info :ignore-list (cons element (plist-get info :ignore-list))))
1777 ;;; The Filter System
1779 ;; Filters allow end-users to tweak easily the transcoded output.
1780 ;; They are the functional counterpart of hooks, as every filter in
1781 ;; a set is applied to the return value of the previous one.
1783 ;; Every set is back-end agnostic. Although, a filter is always
1784 ;; called, in addition to the string it applies to, with the back-end
1785 ;; used as argument, so it's easy enough for the end-user to add
1786 ;; back-end specific filters in the set. The communication channel,
1787 ;; as a plist, is required as the third argument.
1789 ;; Filters sets are defined below. There are of four types:
1791 ;; - `org-export-filter-parse-tree-functions' applies directly on the
1792 ;; complete parsed tree. It's the only filters set that doesn't
1793 ;; apply to a string.
1794 ;; - `org-export-filter-final-output-functions' applies to the final
1795 ;; transcoded string.
1796 ;; - `org-export-filter-plain-text-functions' applies to any string
1797 ;; not recognized as Org syntax.
1798 ;; - `org-export-filter-TYPE-functions' applies on the string returned
1799 ;; after an element or object of type TYPE has been transcoded.
1801 ;; All filters sets are applied through
1802 ;; `org-export-filter-apply-functions' function. Filters in a set are
1803 ;; applied in a LIFO fashion. It allows developers to be sure that
1804 ;; their filters will be applied first.
1806 ;; Filters properties are installed in communication channel with
1807 ;; `org-export-install-filters' function.
1809 ;; Eventually, a hook (`org-export-before-parsing-hook') is run just
1810 ;; before parsing to allow for heavy structure modifications.
1813 ;;;; Before Parsing Hook
1815 (defvar org-export-before-parsing-hook nil
1816 "Hook run before parsing an export buffer.
1817 This is run after include keywords have been expanded and Babel
1818 code executed, on a copy of original buffer's area being
1819 exported. Visibility is the same as in the original one. Point
1820 is left at the beginning of the new one.")
1823 ;;;; Special Filters
1825 (defvar org-export-filter-parse-tree-functions nil
1826 "List of functions applied to the parsed tree.
1827 Each filter is called with three arguments: the parse tree, as
1828 returned by `org-element-parse-buffer', the back-end, as
1829 a symbol, and the communication channel, as a plist. It must
1830 return the modified parse tree to transcode.")
1832 (defvar org-export-filter-final-output-functions nil
1833 "List of functions applied to the transcoded string.
1834 Each filter is called with three arguments: the full transcoded
1835 string, the back-end, as a symbol, and the communication channel,
1836 as a plist. It must return a string that will be used as the
1837 final export output.")
1839 (defvar org-export-filter-plain-text-functions nil
1840 "List of functions applied to plain text.
1841 Each filter is called with three arguments: a string which
1842 contains no Org syntax, the back-end, as a symbol, and the
1843 communication channel, as a plist. It must return a string or
1844 nil.")
1847 ;;;; Elements Filters
1849 (defvar org-export-filter-center-block-functions nil
1850 "List of functions applied to a transcoded center block.
1851 Each filter is called with three arguments: the transcoded data,
1852 as a string, the back-end, as a symbol, and the communication
1853 channel, as a plist. It must return a string or nil.")
1855 (defvar org-export-filter-clock-functions nil
1856 "List of functions applied to a transcoded clock.
1857 Each filter is called with three arguments: the transcoded data,
1858 as a string, the back-end, as a symbol, and the communication
1859 channel, as a plist. It must return a string or nil.")
1861 (defvar org-export-filter-drawer-functions nil
1862 "List of functions applied to a transcoded drawer.
1863 Each filter is called with three arguments: the transcoded data,
1864 as a string, the back-end, as a symbol, and the communication
1865 channel, as a plist. It must return a string or nil.")
1867 (defvar org-export-filter-dynamic-block-functions nil
1868 "List of functions applied to a transcoded dynamic-block.
1869 Each filter is called with three arguments: the transcoded data,
1870 as a string, the back-end, as a symbol, and the communication
1871 channel, as a plist. It must return a string or nil.")
1873 (defvar org-export-filter-headline-functions nil
1874 "List of functions applied to a transcoded headline.
1875 Each filter is called with three arguments: the transcoded data,
1876 as a string, the back-end, as a symbol, and the communication
1877 channel, as a plist. It must return a string or nil.")
1879 (defvar org-export-filter-inlinetask-functions nil
1880 "List of functions applied to a transcoded inlinetask.
1881 Each filter is called with three arguments: the transcoded data,
1882 as a string, the back-end, as a symbol, and the communication
1883 channel, as a plist. It must return a string or nil.")
1885 (defvar org-export-filter-plain-list-functions nil
1886 "List of functions applied to a transcoded plain-list.
1887 Each filter is called with three arguments: the transcoded data,
1888 as a string, the back-end, as a symbol, and the communication
1889 channel, as a plist. It must return a string or nil.")
1891 (defvar org-export-filter-item-functions nil
1892 "List of functions applied to a transcoded item.
1893 Each filter is called with three arguments: the transcoded data,
1894 as a string, the back-end, as a symbol, and the communication
1895 channel, as a plist. It must return a string or nil.")
1897 (defvar org-export-filter-comment-functions nil
1898 "List of functions applied to a transcoded comment.
1899 Each filter is called with three arguments: the transcoded data,
1900 as a string, the back-end, as a symbol, and the communication
1901 channel, as a plist. It must return a string or nil.")
1903 (defvar org-export-filter-comment-block-functions nil
1904 "List of functions applied to a transcoded comment-comment.
1905 Each filter is called with three arguments: the transcoded data,
1906 as a string, the back-end, as a symbol, and the communication
1907 channel, as a plist. It must return a string or nil.")
1909 (defvar org-export-filter-example-block-functions nil
1910 "List of functions applied to a transcoded example-block.
1911 Each filter is called with three arguments: the transcoded data,
1912 as a string, the back-end, as a symbol, and the communication
1913 channel, as a plist. It must return a string or nil.")
1915 (defvar org-export-filter-export-block-functions nil
1916 "List of functions applied to a transcoded export-block.
1917 Each filter is called with three arguments: the transcoded data,
1918 as a string, the back-end, as a symbol, and the communication
1919 channel, as a plist. It must return a string or nil.")
1921 (defvar org-export-filter-fixed-width-functions nil
1922 "List of functions applied to a transcoded fixed-width.
1923 Each filter is called with three arguments: the transcoded data,
1924 as a string, the back-end, as a symbol, and the communication
1925 channel, as a plist. It must return a string or nil.")
1927 (defvar org-export-filter-footnote-definition-functions nil
1928 "List of functions applied to a transcoded footnote-definition.
1929 Each filter is called with three arguments: the transcoded data,
1930 as a string, the back-end, as a symbol, and the communication
1931 channel, as a plist. It must return a string or nil.")
1933 (defvar org-export-filter-horizontal-rule-functions nil
1934 "List of functions applied to a transcoded horizontal-rule.
1935 Each filter is called with three arguments: the transcoded data,
1936 as a string, the back-end, as a symbol, and the communication
1937 channel, as a plist. It must return a string or nil.")
1939 (defvar org-export-filter-keyword-functions nil
1940 "List of functions applied to a transcoded keyword.
1941 Each filter is called with three arguments: the transcoded data,
1942 as a string, the back-end, as a symbol, and the communication
1943 channel, as a plist. It must return a string or nil.")
1945 (defvar org-export-filter-latex-environment-functions nil
1946 "List of functions applied to a transcoded latex-environment.
1947 Each filter is called with three arguments: the transcoded data,
1948 as a string, the back-end, as a symbol, and the communication
1949 channel, as a plist. It must return a string or nil.")
1951 (defvar org-export-filter-babel-call-functions nil
1952 "List of functions applied to a transcoded babel-call.
1953 Each filter is called with three arguments: the transcoded data,
1954 as a string, the back-end, as a symbol, and the communication
1955 channel, as a plist. It must return a string or nil.")
1957 (defvar org-export-filter-paragraph-functions nil
1958 "List of functions applied to a transcoded paragraph.
1959 Each filter is called with three arguments: the transcoded data,
1960 as a string, the back-end, as a symbol, and the communication
1961 channel, as a plist. It must return a string or nil.")
1963 (defvar org-export-filter-planning-functions nil
1964 "List of functions applied to a transcoded planning.
1965 Each filter is called with three arguments: the transcoded data,
1966 as a string, the back-end, as a symbol, and the communication
1967 channel, as a plist. It must return a string or nil.")
1969 (defvar org-export-filter-property-drawer-functions nil
1970 "List of functions applied to a transcoded property-drawer.
1971 Each filter is called with three arguments: the transcoded data,
1972 as a string, the back-end, as a symbol, and the communication
1973 channel, as a plist. It must return a string or nil.")
1975 (defvar org-export-filter-quote-block-functions nil
1976 "List of functions applied to a transcoded quote block.
1977 Each filter is called with three arguments: the transcoded quote
1978 data, as a string, the back-end, as a symbol, and the
1979 communication channel, as a plist. It must return a string or
1980 nil.")
1982 (defvar org-export-filter-quote-section-functions nil
1983 "List of functions applied to a transcoded quote-section.
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-section-functions nil
1989 "List of functions applied to a transcoded section.
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-special-block-functions nil
1995 "List of functions applied to a transcoded special 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-src-block-functions nil
2001 "List of functions applied to a transcoded src-block.
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-table-functions nil
2007 "List of functions applied to a transcoded table.
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-table-cell-functions nil
2013 "List of functions applied to a transcoded table-cell.
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-table-row-functions nil
2019 "List of functions applied to a transcoded table-row.
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-verse-block-functions nil
2025 "List of functions applied to a transcoded verse block.
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.")
2031 ;;;; Objects Filters
2033 (defvar org-export-filter-bold-functions nil
2034 "List of functions applied to transcoded bold text.
2035 Each filter is called with three arguments: the transcoded data,
2036 as a string, the back-end, as a symbol, and the communication
2037 channel, as a plist. It must return a string or nil.")
2039 (defvar org-export-filter-code-functions nil
2040 "List of functions applied to transcoded code text.
2041 Each filter is called with three arguments: the transcoded data,
2042 as a string, the back-end, as a symbol, and the communication
2043 channel, as a plist. It must return a string or nil.")
2045 (defvar org-export-filter-entity-functions nil
2046 "List of functions applied to a transcoded entity.
2047 Each filter is called with three arguments: the transcoded data,
2048 as a string, the back-end, as a symbol, and the communication
2049 channel, as a plist. It must return a string or nil.")
2051 (defvar org-export-filter-export-snippet-functions nil
2052 "List of functions applied to a transcoded export-snippet.
2053 Each filter is called with three arguments: the transcoded data,
2054 as a string, the back-end, as a symbol, and the communication
2055 channel, as a plist. It must return a string or nil.")
2057 (defvar org-export-filter-footnote-reference-functions nil
2058 "List of functions applied to a transcoded footnote-reference.
2059 Each filter is called with three arguments: the transcoded data,
2060 as a string, the back-end, as a symbol, and the communication
2061 channel, as a plist. It must return a string or nil.")
2063 (defvar org-export-filter-inline-babel-call-functions nil
2064 "List of functions applied to a transcoded inline-babel-call.
2065 Each filter is called with three arguments: the transcoded data,
2066 as a string, the back-end, as a symbol, and the communication
2067 channel, as a plist. It must return a string or nil.")
2069 (defvar org-export-filter-inline-src-block-functions nil
2070 "List of functions applied to a transcoded inline-src-block.
2071 Each filter is called with three arguments: the transcoded data,
2072 as a string, the back-end, as a symbol, and the communication
2073 channel, as a plist. It must return a string or nil.")
2075 (defvar org-export-filter-italic-functions nil
2076 "List of functions applied to transcoded italic text.
2077 Each filter is called with three arguments: the transcoded data,
2078 as a string, the back-end, as a symbol, and the communication
2079 channel, as a plist. It must return a string or nil.")
2081 (defvar org-export-filter-latex-fragment-functions nil
2082 "List of functions applied to a transcoded latex-fragment.
2083 Each filter is called with three arguments: the transcoded data,
2084 as a string, the back-end, as a symbol, and the communication
2085 channel, as a plist. It must return a string or nil.")
2087 (defvar org-export-filter-line-break-functions nil
2088 "List of functions applied to a transcoded line-break.
2089 Each filter is called with three arguments: the transcoded data,
2090 as a string, the back-end, as a symbol, and the communication
2091 channel, as a plist. It must return a string or nil.")
2093 (defvar org-export-filter-link-functions nil
2094 "List of functions applied to a transcoded link.
2095 Each filter is called with three arguments: the transcoded data,
2096 as a string, the back-end, as a symbol, and the communication
2097 channel, as a plist. It must return a string or nil.")
2099 (defvar org-export-filter-macro-functions nil
2100 "List of functions applied to a transcoded macro.
2101 Each filter is called with three arguments: the transcoded data,
2102 as a string, the back-end, as a symbol, and the communication
2103 channel, as a plist. It must return a string or nil.")
2105 (defvar org-export-filter-radio-target-functions nil
2106 "List of functions applied to a transcoded radio-target.
2107 Each filter is called with three arguments: the transcoded data,
2108 as a string, the back-end, as a symbol, and the communication
2109 channel, as a plist. It must return a string or nil.")
2111 (defvar org-export-filter-statistics-cookie-functions nil
2112 "List of functions applied to a transcoded statistics-cookie.
2113 Each filter is called with three arguments: the transcoded data,
2114 as a string, the back-end, as a symbol, and the communication
2115 channel, as a plist. It must return a string or nil.")
2117 (defvar org-export-filter-strike-through-functions nil
2118 "List of functions applied to transcoded strike-through text.
2119 Each filter is called with three arguments: the transcoded data,
2120 as a string, the back-end, as a symbol, and the communication
2121 channel, as a plist. It must return a string or nil.")
2123 (defvar org-export-filter-subscript-functions nil
2124 "List of functions applied to a transcoded subscript.
2125 Each filter is called with three arguments: the transcoded data,
2126 as a string, the back-end, as a symbol, and the communication
2127 channel, as a plist. It must return a string or nil.")
2129 (defvar org-export-filter-superscript-functions nil
2130 "List of functions applied to a transcoded superscript.
2131 Each filter is called with three arguments: the transcoded data,
2132 as a string, the back-end, as a symbol, and the communication
2133 channel, as a plist. It must return a string or nil.")
2135 (defvar org-export-filter-target-functions nil
2136 "List of functions applied to a transcoded target.
2137 Each filter is called with three arguments: the transcoded data,
2138 as a string, the back-end, as a symbol, and the communication
2139 channel, as a plist. It must return a string or nil.")
2141 (defvar org-export-filter-timestamp-functions nil
2142 "List of functions applied to a transcoded timestamp.
2143 Each filter is called with three arguments: the transcoded data,
2144 as a string, the back-end, as a symbol, and the communication
2145 channel, as a plist. It must return a string or nil.")
2147 (defvar org-export-filter-underline-functions nil
2148 "List of functions applied to transcoded underline text.
2149 Each filter is called with three arguments: the transcoded data,
2150 as a string, the back-end, as a symbol, and the communication
2151 channel, as a plist. It must return a string or nil.")
2153 (defvar org-export-filter-verbatim-functions nil
2154 "List of functions applied to transcoded verbatim text.
2155 Each filter is called with three arguments: the transcoded data,
2156 as a string, the back-end, as a symbol, and the communication
2157 channel, as a plist. It must return a string or nil.")
2159 (defun org-export-filter-apply-functions (filters value info)
2160 "Call every function in FILTERS.
2161 Functions are called with arguments VALUE, current export
2162 back-end and INFO. Call is done in a LIFO fashion, to be sure
2163 that developer specified filters, if any, are called first."
2164 (loop for filter in filters
2165 if (not value) return nil else
2166 do (setq value (funcall filter value (plist-get info :back-end) info)))
2167 value)
2169 (defun org-export-install-filters (info)
2170 "Install filters properties in communication channel.
2172 INFO is a plist containing the current communication channel.
2174 Return the updated communication channel."
2175 (let (plist)
2176 ;; Install user defined filters with `org-export-filters-alist'.
2177 (mapc (lambda (p)
2178 (setq plist (plist-put plist (car p) (eval (cdr p)))))
2179 org-export-filters-alist)
2180 ;; Prepend back-end specific filters to that list.
2181 (let ((back-end-filters (intern (format "org-%s-filters-alist"
2182 (plist-get info :back-end)))))
2183 (when (boundp back-end-filters)
2184 (mapc (lambda (p)
2185 ;; Single values get consed, lists are prepended.
2186 (let ((key (car p)) (value (cdr p)))
2187 (when value
2188 (setq plist
2189 (plist-put
2190 plist key
2191 (if (atom value) (cons value (plist-get plist key))
2192 (append value (plist-get plist key))))))))
2193 (eval back-end-filters))))
2194 ;; Return new communication channel.
2195 (org-combine-plists info plist)))
2199 ;;; Core functions
2201 ;; This is the room for the main function, `org-export-as', along with
2202 ;; its derivatives, `org-export-to-buffer' and `org-export-to-file'.
2203 ;; They differ only by the way they output the resulting code.
2205 ;; `org-export-output-file-name' is an auxiliary function meant to be
2206 ;; used with `org-export-to-file'. With a given extension, it tries
2207 ;; to provide a canonical file name to write export output to.
2209 ;; Note that `org-export-as' doesn't really parse the current buffer,
2210 ;; but a copy of it (with the same buffer-local variables and
2211 ;; visibility), where include keywords are expanded and Babel blocks
2212 ;; are executed, if appropriate.
2213 ;; `org-export-with-current-buffer-copy' macro prepares that copy.
2215 ;; File inclusion is taken care of by
2216 ;; `org-export-expand-include-keyword' and
2217 ;; `org-export-prepare-file-contents'. Structure wise, including
2218 ;; a whole Org file in a buffer often makes little sense. For
2219 ;; example, if the file contains an headline and the include keyword
2220 ;; was within an item, the item should contain the headline. That's
2221 ;; why file inclusion should be done before any structure can be
2222 ;; associated to the file, that is before parsing.
2224 (defvar org-current-export-file) ; Dynamically scoped
2225 (defvar org-export-current-backend) ; Dynamically scoped
2226 (defun org-export-as
2227 (backend &optional subtreep visible-only body-only ext-plist noexpand)
2228 "Transcode current Org buffer into BACKEND code.
2230 If narrowing is active in the current buffer, only transcode its
2231 narrowed part.
2233 If a region is active, transcode that region.
2235 When optional argument SUBTREEP is non-nil, transcode the
2236 sub-tree at point, extracting information from the headline
2237 properties first.
2239 When optional argument VISIBLE-ONLY is non-nil, don't export
2240 contents of hidden elements.
2242 When optional argument BODY-ONLY is non-nil, only return body
2243 code, without preamble nor postamble.
2245 Optional argument EXT-PLIST, when provided, is a property list
2246 with external parameters overriding Org default settings, but
2247 still inferior to file-local settings.
2249 Optional argument NOEXPAND, when non-nil, prevents included files
2250 to be expanded and Babel code to be executed.
2252 Return code as a string."
2253 (save-excursion
2254 (save-restriction
2255 ;; Narrow buffer to an appropriate region or subtree for
2256 ;; parsing. If parsing subtree, be sure to remove main headline
2257 ;; too.
2258 (cond ((org-region-active-p)
2259 (narrow-to-region (region-beginning) (region-end)))
2260 (subtreep
2261 (org-narrow-to-subtree)
2262 (goto-char (point-min))
2263 (forward-line)
2264 (narrow-to-region (point) (point-max))))
2265 ;; 1. Get export environment from original buffer. Store
2266 ;; original footnotes definitions in communication channel as
2267 ;; they might not be accessible anymore in a narrowed parse
2268 ;; tree. Also install user's and developer's filters.
2269 (let ((info (org-export-install-filters
2270 (org-export-store-footnote-definitions
2271 (org-export-get-environment backend subtreep ext-plist))))
2272 ;; 2. Get parse tree. Buffer isn't parsed directly.
2273 ;; Instead, a temporary copy is created, where include
2274 ;; keywords are expanded and code blocks are evaluated.
2275 (tree (let ((buf (or (buffer-file-name (buffer-base-buffer))
2276 (current-buffer))))
2277 (org-export-with-current-buffer-copy
2278 (unless noexpand
2279 (org-export-expand-include-keyword)
2280 ;; Setting `org-current-export-file' is
2281 ;; required by Org Babel to properly resolve
2282 ;; noweb references.
2283 (let ((org-current-export-file buf))
2284 (org-export-blocks-preprocess)))
2285 (goto-char (point-min))
2286 ;; Run hook with `org-export-current-backend' set
2287 ;; to BACKEND.
2288 (let ((org-export-current-backend backend))
2289 (run-hooks 'org-export-before-parsing-hook))
2290 ;; Eventually parse buffer.
2291 (org-element-parse-buffer nil visible-only)))))
2292 ;; 3. Call parse-tree filters to get the final tree.
2293 (setq tree
2294 (org-export-filter-apply-functions
2295 (plist-get info :filter-parse-tree) tree info))
2296 ;; 4. Now tree is complete, compute its properties and add
2297 ;; them to communication channel.
2298 (setq info
2299 (org-combine-plists
2300 info (org-export-collect-tree-properties tree info)))
2301 ;; 5. Eventually transcode TREE. Wrap the resulting string
2302 ;; into a template, if required. Eventually call
2303 ;; final-output filter.
2304 (let* ((body (org-element-normalize-string (org-export-data tree info)))
2305 (template (intern (format "org-%s-template" backend)))
2306 (output (org-export-filter-apply-functions
2307 (plist-get info :filter-final-output)
2308 (if (or (not (fboundp template)) body-only) body
2309 (funcall template body info))
2310 info)))
2311 ;; Maybe add final OUTPUT to kill ring, then return it.
2312 (when org-export-copy-to-kill-ring (org-kill-new output))
2313 output)))))
2315 (defun org-export-to-buffer
2316 (backend buffer &optional subtreep visible-only body-only ext-plist noexpand)
2317 "Call `org-export-as' with output to a specified buffer.
2319 BACKEND is the back-end used for transcoding, as a symbol.
2321 BUFFER is the output buffer. If it already exists, it will be
2322 erased first, otherwise, it will be created.
2324 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY, EXT-PLIST
2325 and NOEXPAND are similar to those used in `org-export-as', which
2326 see.
2328 Return buffer."
2329 (let ((out (org-export-as
2330 backend subtreep visible-only body-only ext-plist noexpand))
2331 (buffer (get-buffer-create buffer)))
2332 (with-current-buffer buffer
2333 (erase-buffer)
2334 (insert out)
2335 (goto-char (point-min)))
2336 buffer))
2338 (defun org-export-to-file
2339 (backend file &optional subtreep visible-only body-only ext-plist noexpand)
2340 "Call `org-export-as' with output to a specified file.
2342 BACKEND is the back-end used for transcoding, as a symbol. FILE
2343 is the name of the output file, as a string.
2345 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY, EXT-PLIST
2346 and NOEXPAND are similar to those used in `org-export-as', which
2347 see.
2349 Return output file's name."
2350 ;; Checks for FILE permissions. `write-file' would do the same, but
2351 ;; we'd rather avoid needless transcoding of parse tree.
2352 (unless (file-writable-p file) (error "Output file not writable"))
2353 ;; Insert contents to a temporary buffer and write it to FILE.
2354 (let ((out (org-export-as
2355 backend subtreep visible-only body-only ext-plist noexpand)))
2356 (with-temp-buffer
2357 (insert out)
2358 (let ((coding-system-for-write org-export-coding-system))
2359 (write-file file))))
2360 ;; Return full path.
2361 file)
2363 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
2364 "Return output file's name according to buffer specifications.
2366 EXTENSION is a string representing the output file extension,
2367 with the leading dot.
2369 With a non-nil optional argument SUBTREEP, try to determine
2370 output file's name by looking for \"EXPORT_FILE_NAME\" property
2371 of subtree at point.
2373 When optional argument PUB-DIR is set, use it as the publishing
2374 directory.
2376 Return file name as a string, or nil if it couldn't be
2377 determined."
2378 (let ((base-name
2379 ;; File name may come from EXPORT_FILE_NAME subtree property,
2380 ;; assuming point is at beginning of said sub-tree.
2381 (file-name-sans-extension
2382 (or (and subtreep
2383 (org-entry-get
2384 (save-excursion
2385 (ignore-errors
2386 (org-back-to-heading (not visible-only)) (point)))
2387 "EXPORT_FILE_NAME" t))
2388 ;; File name may be extracted from buffer's associated
2389 ;; file, if any.
2390 (buffer-file-name (buffer-base-buffer))
2391 ;; Can't determine file name on our own: Ask user.
2392 (let ((read-file-name-function
2393 (and org-completion-use-ido 'ido-read-file-name)))
2394 (read-file-name
2395 "Output file: " pub-dir nil nil nil
2396 (lambda (name)
2397 (string= (file-name-extension name t) extension))))))))
2398 ;; Build file name. Enforce EXTENSION over whatever user may have
2399 ;; come up with. PUB-DIR, if defined, always has precedence over
2400 ;; any provided path.
2401 (cond
2402 (pub-dir
2403 (concat (file-name-as-directory pub-dir)
2404 (file-name-nondirectory base-name)
2405 extension))
2406 ((string= (file-name-nondirectory base-name) base-name)
2407 (concat (file-name-as-directory ".") base-name extension))
2408 (t (concat base-name extension)))))
2410 (defmacro org-export-with-current-buffer-copy (&rest body)
2411 "Apply BODY in a copy of the current buffer.
2413 The copy preserves local variables and visibility of the original
2414 buffer.
2416 Point is at buffer's beginning when BODY is applied."
2417 (org-with-gensyms (original-buffer offset buffer-string overlays)
2418 `(let ((,original-buffer ,(current-buffer))
2419 (,offset ,(1- (point-min)))
2420 (,buffer-string ,(buffer-string))
2421 (,overlays (mapcar
2422 'copy-overlay (overlays-in (point-min) (point-max)))))
2423 (with-temp-buffer
2424 (let ((buffer-invisibility-spec nil))
2425 (org-clone-local-variables
2426 ,original-buffer
2427 "^\\(org-\\|orgtbl-\\|major-mode$\\|outline-\\(regexp\\|level\\)$\\)")
2428 (insert ,buffer-string)
2429 (mapc (lambda (ov)
2430 (move-overlay
2432 (- (overlay-start ov) ,offset)
2433 (- (overlay-end ov) ,offset)
2434 (current-buffer)))
2435 ,overlays)
2436 (goto-char (point-min))
2437 (progn ,@body))))))
2438 (def-edebug-spec org-export-with-current-buffer-copy (body))
2440 (defun org-export-expand-include-keyword (&optional included dir)
2441 "Expand every include keyword in buffer.
2442 Optional argument INCLUDED is a list of included file names along
2443 with their line restriction, when appropriate. It is used to
2444 avoid infinite recursion. Optional argument DIR is the current
2445 working directory. It is used to properly resolve relative
2446 paths."
2447 (let ((case-fold-search t))
2448 (goto-char (point-min))
2449 (while (re-search-forward "^[ \t]*#\\+INCLUDE: \\(.*\\)" nil t)
2450 (when (eq (org-element-type (save-match-data (org-element-at-point)))
2451 'keyword)
2452 (beginning-of-line)
2453 ;; Extract arguments from keyword's value.
2454 (let* ((value (match-string 1))
2455 (ind (org-get-indentation))
2456 (file (and (string-match "^\"\\(\\S-+\\)\"" value)
2457 (prog1 (expand-file-name (match-string 1 value) dir)
2458 (setq value (replace-match "" nil nil value)))))
2459 (lines
2460 (and (string-match
2461 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\"" value)
2462 (prog1 (match-string 1 value)
2463 (setq value (replace-match "" nil nil value)))))
2464 (env (cond ((string-match "\\<example\\>" value) 'example)
2465 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
2466 (match-string 1 value))))
2467 ;; Minimal level of included file defaults to the child
2468 ;; level of the current headline, if any, or one. It
2469 ;; only applies is the file is meant to be included as
2470 ;; an Org one.
2471 (minlevel
2472 (and (not env)
2473 (if (string-match ":minlevel +\\([0-9]+\\)" value)
2474 (prog1 (string-to-number (match-string 1 value))
2475 (setq value (replace-match "" nil nil value)))
2476 (let ((cur (org-current-level)))
2477 (if cur (1+ (org-reduced-level cur)) 1))))))
2478 ;; Remove keyword.
2479 (delete-region (point) (progn (forward-line) (point)))
2480 (cond
2481 ((not (file-readable-p file)) (error "Cannot include file %s" file))
2482 ;; Check if files has already been parsed. Look after
2483 ;; inclusion lines too, as different parts of the same file
2484 ;; can be included too.
2485 ((member (list file lines) included)
2486 (error "Recursive file inclusion: %s" file))
2488 (cond
2489 ((eq env 'example)
2490 (insert
2491 (let ((ind-str (make-string ind ? ))
2492 (contents
2493 ;; Protect sensitive contents with commas.
2494 (replace-regexp-in-string
2495 "\\(^\\)\\([*]\\|[ \t]*#\\+\\)" ","
2496 (org-export-prepare-file-contents file lines)
2497 nil nil 1)))
2498 (format "%s#+BEGIN_EXAMPLE\n%s%s#+END_EXAMPLE\n"
2499 ind-str contents ind-str))))
2500 ((stringp env)
2501 (insert
2502 (let ((ind-str (make-string ind ? ))
2503 (contents
2504 ;; Protect sensitive contents with commas.
2505 (replace-regexp-in-string
2506 (if (string= env "org") "\\(^\\)\\(.\\)"
2507 "\\(^\\)\\([*]\\|[ \t]*#\\+\\)") ","
2508 (org-export-prepare-file-contents file lines)
2509 nil nil 1)))
2510 (format "%s#+BEGIN_SRC %s\n%s%s#+END_SRC\n"
2511 ind-str env contents ind-str))))
2513 (insert
2514 (with-temp-buffer
2515 (org-mode)
2516 (insert
2517 (org-export-prepare-file-contents file lines ind minlevel))
2518 (org-export-expand-include-keyword
2519 (cons (list file lines) included)
2520 (file-name-directory file))
2521 (buffer-string))))))))))))
2523 (defun org-export-prepare-file-contents (file &optional lines ind minlevel)
2524 "Prepare the contents of FILE for inclusion and return them as a string.
2526 When optional argument LINES is a string specifying a range of
2527 lines, include only those lines.
2529 Optional argument IND, when non-nil, is an integer specifying the
2530 global indentation of returned contents. Since its purpose is to
2531 allow an included file to stay in the same environment it was
2532 created \(i.e. a list item), it doesn't apply past the first
2533 headline encountered.
2535 Optional argument MINLEVEL, when non-nil, is an integer
2536 specifying the level that any top-level headline in the included
2537 file should have."
2538 (with-temp-buffer
2539 (insert-file-contents file)
2540 (when lines
2541 (let* ((lines (split-string lines "-"))
2542 (lbeg (string-to-number (car lines)))
2543 (lend (string-to-number (cadr lines)))
2544 (beg (if (zerop lbeg) (point-min)
2545 (goto-char (point-min))
2546 (forward-line (1- lbeg))
2547 (point)))
2548 (end (if (zerop lend) (point-max)
2549 (goto-char (point-min))
2550 (forward-line (1- lend))
2551 (point))))
2552 (narrow-to-region beg end)))
2553 ;; Remove blank lines at beginning and end of contents. The logic
2554 ;; behind that removal is that blank lines around include keyword
2555 ;; override blank lines in included file.
2556 (goto-char (point-min))
2557 (org-skip-whitespace)
2558 (beginning-of-line)
2559 (delete-region (point-min) (point))
2560 (goto-char (point-max))
2561 (skip-chars-backward " \r\t\n")
2562 (forward-line)
2563 (delete-region (point) (point-max))
2564 ;; If IND is set, preserve indentation of include keyword until
2565 ;; the first headline encountered.
2566 (when ind
2567 (unless (eq major-mode 'org-mode) (org-mode))
2568 (goto-char (point-min))
2569 (let ((ind-str (make-string ind ? )))
2570 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
2571 ;; Do not move footnote definitions out of column 0.
2572 (unless (and (looking-at org-footnote-definition-re)
2573 (eq (org-element-type (org-element-at-point))
2574 'footnote-definition))
2575 (insert ind-str))
2576 (forward-line))))
2577 ;; When MINLEVEL is specified, compute minimal level for headlines
2578 ;; in the file (CUR-MIN), and remove stars to each headline so
2579 ;; that headlines with minimal level have a level of MINLEVEL.
2580 (when minlevel
2581 (unless (eq major-mode 'org-mode) (org-mode))
2582 (let ((levels (org-map-entries
2583 (lambda () (org-reduced-level (org-current-level))))))
2584 (when levels
2585 (let ((offset (- minlevel (apply 'min levels))))
2586 (unless (zerop offset)
2587 (when org-odd-levels-only (setq offset (* offset 2)))
2588 ;; Only change stars, don't bother moving whole
2589 ;; sections.
2590 (org-map-entries
2591 (lambda () (if (< offset 0) (delete-char (abs offset))
2592 (insert (make-string offset ?*))))))))))
2593 (buffer-string)))
2596 ;;; Tools For Back-Ends
2598 ;; A whole set of tools is available to help build new exporters. Any
2599 ;; function general enough to have its use across many back-ends
2600 ;; should be added here.
2602 ;; As of now, functions operating on footnotes, headlines, links,
2603 ;; macros, references, src-blocks, tables and tables of contents are
2604 ;; implemented.
2606 ;;;; For Export Snippets
2608 ;; Every export snippet is transmitted to the back-end. Though, the
2609 ;; latter will only retain one type of export-snippet, ignoring
2610 ;; others, based on the former's target back-end. The function
2611 ;; `org-export-snippet-backend' returns that back-end for a given
2612 ;; export-snippet.
2614 (defun org-export-snippet-backend (export-snippet)
2615 "Return EXPORT-SNIPPET targeted back-end as a symbol.
2616 Translation, with `org-export-snippet-translation-alist', is
2617 applied."
2618 (let ((back-end (org-element-property :back-end export-snippet)))
2619 (intern
2620 (or (cdr (assoc back-end org-export-snippet-translation-alist))
2621 back-end))))
2624 ;;;; For Footnotes
2626 ;; `org-export-collect-footnote-definitions' is a tool to list
2627 ;; actually used footnotes definitions in the whole parse tree, or in
2628 ;; an headline, in order to add footnote listings throughout the
2629 ;; transcoded data.
2631 ;; `org-export-footnote-first-reference-p' is a predicate used by some
2632 ;; back-ends, when they need to attach the footnote definition only to
2633 ;; the first occurrence of the corresponding label.
2635 ;; `org-export-get-footnote-definition' and
2636 ;; `org-export-get-footnote-number' provide easier access to
2637 ;; additional information relative to a footnote reference.
2639 (defun org-export-collect-footnote-definitions (data info)
2640 "Return an alist between footnote numbers, labels and definitions.
2642 DATA is the parse tree from which definitions are collected.
2643 INFO is the plist used as a communication channel.
2645 Definitions are sorted by order of references. They either
2646 appear as Org data or as a secondary string for inlined
2647 footnotes. Unreferenced definitions are ignored."
2648 (let (num-alist
2649 (collect-fn
2650 (function
2651 (lambda (data)
2652 ;; Collect footnote number, label and definition in DATA.
2653 (org-element-map
2654 data 'footnote-reference
2655 (lambda (fn)
2656 (when (org-export-footnote-first-reference-p fn info)
2657 (let ((def (org-export-get-footnote-definition fn info)))
2658 (push
2659 (list (org-export-get-footnote-number fn info)
2660 (org-element-property :label fn)
2661 def)
2662 num-alist)
2663 ;; Also search in definition for nested footnotes.
2664 (when (eq (org-element-property :type fn) 'standard)
2665 (funcall collect-fn def)))))
2666 ;; Don't enter footnote definitions since it will happen
2667 ;; when their first reference is found.
2668 info nil 'footnote-definition)))))
2669 (funcall collect-fn (plist-get info :parse-tree))
2670 (reverse num-alist)))
2672 (defun org-export-footnote-first-reference-p (footnote-reference info)
2673 "Non-nil when a footnote reference is the first one for its label.
2675 FOOTNOTE-REFERENCE is the footnote reference being considered.
2676 INFO is the plist used as a communication channel."
2677 (let ((label (org-element-property :label footnote-reference)))
2678 ;; Anonymous footnotes are always a first reference.
2679 (if (not label) t
2680 ;; Otherwise, return the first footnote with the same LABEL and
2681 ;; test if it is equal to FOOTNOTE-REFERENCE.
2682 (let ((search-refs
2683 (function
2684 (lambda (data)
2685 (org-element-map
2686 data 'footnote-reference
2687 (lambda (fn)
2688 (cond
2689 ((string= (org-element-property :label fn) label)
2690 (throw 'exit fn))
2691 ;; If FN isn't inlined, be sure to traverse its
2692 ;; definition before resuming search. See
2693 ;; comments in `org-export-get-footnote-number'
2694 ;; for more information.
2695 ((eq (org-element-property :type fn) 'standard)
2696 (funcall search-refs
2697 (org-export-get-footnote-definition fn info)))))
2698 ;; Don't enter footnote definitions since it will
2699 ;; happen when their first reference is found.
2700 info 'first-match 'footnote-definition)))))
2701 (equal (catch 'exit (funcall search-refs (plist-get info :parse-tree)))
2702 footnote-reference)))))
2704 (defun org-export-get-footnote-definition (footnote-reference info)
2705 "Return definition of FOOTNOTE-REFERENCE as parsed data.
2706 INFO is the plist used as a communication channel."
2707 (let ((label (org-element-property :label footnote-reference)))
2708 (or (org-element-property :inline-definition footnote-reference)
2709 (cdr (assoc label (plist-get info :footnote-definition-alist))))))
2711 (defun org-export-get-footnote-number (footnote info)
2712 "Return number associated to a footnote.
2714 FOOTNOTE is either a footnote reference or a footnote definition.
2715 INFO is the plist used as a communication channel."
2716 (let ((label (org-element-property :label footnote))
2717 seen-refs
2718 (search-ref
2719 (function
2720 (lambda (data)
2721 ;; Search footnote references through DATA, filling
2722 ;; SEEN-REFS along the way.
2723 (org-element-map
2724 data 'footnote-reference
2725 (lambda (fn)
2726 (let ((fn-lbl (org-element-property :label fn)))
2727 (cond
2728 ;; Anonymous footnote match: return number.
2729 ((and (not fn-lbl) (equal fn footnote))
2730 (throw 'exit (1+ (length seen-refs))))
2731 ;; Labels match: return number.
2732 ((and label (string= label fn-lbl))
2733 (throw 'exit (1+ (length seen-refs))))
2734 ;; Anonymous footnote: it's always a new one. Also,
2735 ;; be sure to return nil from the `cond' so
2736 ;; `first-match' doesn't get us out of the loop.
2737 ((not fn-lbl) (push 'inline seen-refs) nil)
2738 ;; Label not seen so far: add it so SEEN-REFS.
2740 ;; Also search for subsequent references in footnote
2741 ;; definition so numbering following reading logic.
2742 ;; Note that we don't have to care about inline
2743 ;; definitions, since `org-element-map' already
2744 ;; traverse them at the right time.
2746 ;; Once again, return nil to stay in the loop.
2747 ((not (member fn-lbl seen-refs))
2748 (push fn-lbl seen-refs)
2749 (funcall search-ref
2750 (org-export-get-footnote-definition fn info))
2751 nil))))
2752 ;; Don't enter footnote definitions since it will happen
2753 ;; when their first reference is found.
2754 info 'first-match 'footnote-definition)))))
2755 (catch 'exit (funcall search-ref (plist-get info :parse-tree)))))
2758 ;;;; For Headlines
2760 ;; `org-export-get-relative-level' is a shortcut to get headline
2761 ;; level, relatively to the lower headline level in the parsed tree.
2763 ;; `org-export-get-headline-number' returns the section number of an
2764 ;; headline, while `org-export-number-to-roman' allows to convert it
2765 ;; to roman numbers.
2767 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
2768 ;; `org-export-last-sibling-p' are three useful predicates when it
2769 ;; comes to fulfill the `:headline-levels' property.
2771 (defun org-export-get-relative-level (headline info)
2772 "Return HEADLINE relative level within current parsed tree.
2773 INFO is a plist holding contextual information."
2774 (+ (org-element-property :level headline)
2775 (or (plist-get info :headline-offset) 0)))
2777 (defun org-export-low-level-p (headline info)
2778 "Non-nil when HEADLINE is considered as low level.
2780 INFO is a plist used as a communication channel.
2782 A low level headlines has a relative level greater than
2783 `:headline-levels' property value.
2785 Return value is the difference between HEADLINE relative level
2786 and the last level being considered as high enough, or nil."
2787 (let ((limit (plist-get info :headline-levels)))
2788 (when (wholenump limit)
2789 (let ((level (org-export-get-relative-level headline info)))
2790 (and (> level limit) (- level limit))))))
2792 (defun org-export-get-headline-number (headline info)
2793 "Return HEADLINE numbering as a list of numbers.
2794 INFO is a plist holding contextual information."
2795 (cdr (assoc headline (plist-get info :headline-numbering))))
2797 (defun org-export-numbered-headline-p (headline info)
2798 "Return a non-nil value if HEADLINE element should be numbered.
2799 INFO is a plist used as a communication channel."
2800 (let ((sec-num (plist-get info :section-numbers))
2801 (level (org-export-get-relative-level headline info)))
2802 (if (wholenump sec-num) (<= level sec-num) sec-num)))
2804 (defun org-export-number-to-roman (n)
2805 "Convert integer N into a roman numeral."
2806 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
2807 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
2808 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
2809 ( 1 . "I")))
2810 (res ""))
2811 (if (<= n 0)
2812 (number-to-string n)
2813 (while roman
2814 (if (>= n (caar roman))
2815 (setq n (- n (caar roman))
2816 res (concat res (cdar roman)))
2817 (pop roman)))
2818 res)))
2820 (defun org-export-get-tags (element info &optional tags)
2821 "Return list of tags associated to ELEMENT.
2823 ELEMENT has either an `headline' or an `inlinetask' type. INFO
2824 is a plist used as a communication channel.
2826 Select tags (see `org-export-select-tags') and exclude tags (see
2827 `org-export-exclude-tags') are removed from the list.
2829 When non-nil, optional argument TAGS should be a list of strings.
2830 Any tag belonging to this list will also be removed."
2831 (org-remove-if (lambda (tag) (or (member tag (plist-get info :select-tags))
2832 (member tag (plist-get info :exclude-tags))
2833 (member tag tags)))
2834 (org-element-property :tags element)))
2836 (defun org-export-first-sibling-p (headline info)
2837 "Non-nil when HEADLINE is the first sibling in its sub-tree.
2838 INFO is the plist used as a communication channel."
2839 (not (eq (org-element-type (org-export-get-previous-element headline info))
2840 'headline)))
2842 (defun org-export-last-sibling-p (headline info)
2843 "Non-nil when HEADLINE is the last sibling in its sub-tree.
2844 INFO is the plist used as a communication channel."
2845 (not (org-export-get-next-element headline info)))
2848 ;;;; For Links
2850 ;; `org-export-solidify-link-text' turns a string into a safer version
2851 ;; for links, replacing most non-standard characters with hyphens.
2853 ;; `org-export-get-coderef-format' returns an appropriate format
2854 ;; string for coderefs.
2856 ;; `org-export-inline-image-p' returns a non-nil value when the link
2857 ;; provided should be considered as an inline image.
2859 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
2860 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
2861 ;; returns an appropriate unique identifier when found, or nil.
2863 ;; `org-export-resolve-id-link' returns the first headline with
2864 ;; specified id or custom-id in parse tree, or nil when none was
2865 ;; found.
2867 ;; `org-export-resolve-coderef' associates a reference to a line
2868 ;; number in the element it belongs, or returns the reference itself
2869 ;; when the element isn't numbered.
2871 (defun org-export-solidify-link-text (s)
2872 "Take link text S and make a safe target out of it."
2873 (save-match-data
2874 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-]+") "-")))
2876 (defun org-export-get-coderef-format (path desc)
2877 "Return format string for code reference link.
2878 PATH is the link path. DESC is its description."
2879 (save-match-data
2880 (cond ((not desc) "%s")
2881 ((string-match (regexp-quote (concat "(" path ")")) desc)
2882 (replace-match "%s" t t desc))
2883 (t desc))))
2885 (defun org-export-inline-image-p (link &optional rules)
2886 "Non-nil if LINK object points to an inline image.
2888 Optional argument is a set of RULES defining inline images. It
2889 is an alist where associations have the following shape:
2891 \(TYPE . REGEXP)
2893 Applying a rule means apply REGEXP against LINK's path when its
2894 type is TYPE. The function will return a non-nil value if any of
2895 the provided rules is non-nil. The default rule is
2896 `org-export-default-inline-image-rule'.
2898 This only applies to links without a description."
2899 (and (not (org-element-contents link))
2900 (let ((case-fold-search t)
2901 (rules (or rules org-export-default-inline-image-rule)))
2902 (some
2903 (lambda (rule)
2904 (and (string= (org-element-property :type link) (car rule))
2905 (string-match (cdr rule)
2906 (org-element-property :path link))))
2907 rules))))
2909 (defun org-export-resolve-coderef (ref info)
2910 "Resolve a code reference REF.
2912 INFO is a plist used as a communication channel.
2914 Return associated line number in source code, or REF itself,
2915 depending on src-block or example element's switches."
2916 (org-element-map
2917 (plist-get info :parse-tree) '(example-block src-block)
2918 (lambda (el)
2919 (with-temp-buffer
2920 (insert (org-trim (org-element-property :value el)))
2921 (let* ((label-fmt (regexp-quote
2922 (or (org-element-property :label-fmt el)
2923 org-coderef-label-format)))
2924 (ref-re
2925 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
2926 (replace-regexp-in-string "%s" ref label-fmt nil t))))
2927 ;; Element containing REF is found. Resolve it to either
2928 ;; a label or a line number, as needed.
2929 (when (re-search-backward ref-re nil t)
2930 (cond
2931 ((org-element-property :use-labels el) ref)
2932 ((eq (org-element-property :number-lines el) 'continued)
2933 (+ (org-export-get-loc el info) (line-number-at-pos)))
2934 (t (line-number-at-pos)))))))
2935 info 'first-match))
2937 (defun org-export-resolve-fuzzy-link (link info)
2938 "Return LINK destination.
2940 INFO is a plist holding contextual information.
2942 Return value can be an object, an element, or nil:
2944 - If LINK path matches a target object (i.e. <<path>>) or
2945 element (i.e. \"#+TARGET: path\"), return it.
2947 - If LINK path exactly matches the name affiliated keyword
2948 \(i.e. #+NAME: path) of an element, return that element.
2950 - If LINK path exactly matches any headline name, return that
2951 element. If more than one headline share that name, priority
2952 will be given to the one with the closest common ancestor, if
2953 any, or the first one in the parse tree otherwise.
2955 - Otherwise, return nil.
2957 Assume LINK type is \"fuzzy\"."
2958 (let ((path (org-element-property :path link)))
2959 (cond
2960 ;; First try to find a matching "<<path>>" unless user specified
2961 ;; he was looking for an headline (path starts with a *
2962 ;; character).
2963 ((and (not (eq (substring path 0 1) ?*))
2964 (loop for target in (plist-get info :target-list)
2965 when (string= (org-element-property :value target) path)
2966 return target)))
2967 ;; Then try to find an element with a matching "#+NAME: path"
2968 ;; affiliated keyword.
2969 ((and (not (eq (substring path 0 1) ?*))
2970 (org-element-map
2971 (plist-get info :parse-tree) org-element-all-elements
2972 (lambda (el)
2973 (when (string= (org-element-property :name el) path) el))
2974 info 'first-match)))
2975 ;; Last case: link either points to an headline or to
2976 ;; nothingness. Try to find the source, with priority given to
2977 ;; headlines with the closest common ancestor. If such candidate
2978 ;; is found, return it, otherwise return nil.
2980 (let ((find-headline
2981 (function
2982 ;; Return first headline whose `:raw-value' property
2983 ;; is NAME in parse tree DATA, or nil.
2984 (lambda (name data)
2985 (org-element-map
2986 data 'headline
2987 (lambda (headline)
2988 (when (string=
2989 (org-element-property :raw-value headline)
2990 name)
2991 headline))
2992 info 'first-match)))))
2993 ;; Search among headlines sharing an ancestor with link,
2994 ;; from closest to farthest.
2995 (or (catch 'exit
2996 (mapc
2997 (lambda (parent)
2998 (when (eq (org-element-type parent) 'headline)
2999 (let ((foundp (funcall find-headline path parent)))
3000 (when foundp (throw 'exit foundp)))))
3001 (org-export-get-genealogy link info)) nil)
3002 ;; No match with a common ancestor: try the full parse-tree.
3003 (funcall find-headline path (plist-get info :parse-tree))))))))
3005 (defun org-export-resolve-id-link (link info)
3006 "Return headline referenced as LINK destination.
3008 INFO is a plist used as a communication channel.
3010 Return value can be an headline element or nil. Assume LINK type
3011 is either \"id\" or \"custom-id\"."
3012 (let ((id (org-element-property :path link)))
3013 (org-element-map
3014 (plist-get info :parse-tree) 'headline
3015 (lambda (headline)
3016 (when (or (string= (org-element-property :id headline) id)
3017 (string= (org-element-property :custom-id headline) id))
3018 headline))
3019 info 'first-match)))
3021 (defun org-export-resolve-radio-link (link info)
3022 "Return radio-target object referenced as LINK destination.
3024 INFO is a plist used as a communication channel.
3026 Return value can be a radio-target object or nil. Assume LINK
3027 has type \"radio\"."
3028 (let ((path (org-element-property :path link)))
3029 (org-element-map
3030 (plist-get info :parse-tree) 'radio-target
3031 (lambda (radio)
3032 (when (equal (org-element-property :value radio) path) radio))
3033 info 'first-match)))
3036 ;;;; For Macros
3038 ;; `org-export-expand-macro' simply takes care of expanding macros.
3040 (defun org-export-expand-macro (macro info)
3041 "Expand MACRO and return it as a string.
3042 INFO is a plist holding export options."
3043 (let* ((key (org-element-property :key macro))
3044 (args (org-element-property :args macro))
3045 ;; User's macros are stored in the communication channel with
3046 ;; a ":macro-" prefix. Replace arguments in VALUE. Also
3047 ;; expand recursively macros within.
3048 (value (org-export-data
3049 (mapcar
3050 (lambda (obj)
3051 (if (not (stringp obj)) (org-export-data obj info)
3052 (replace-regexp-in-string
3053 "\\$[0-9]+"
3054 (lambda (arg)
3055 (nth (1- (string-to-number (substring arg 1))) args))
3056 obj)))
3057 (plist-get info (intern (format ":macro-%s" key))))
3058 info)))
3059 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
3060 (when (string-match "\\`(eval\\>" value) (setq value (eval (read value))))
3061 ;; Return string.
3062 (format "%s" (or value ""))))
3065 ;;;; For References
3067 ;; `org-export-get-ordinal' associates a sequence number to any object
3068 ;; or element.
3070 (defun org-export-get-ordinal (element info &optional types predicate)
3071 "Return ordinal number of an element or object.
3073 ELEMENT is the element or object considered. INFO is the plist
3074 used as a communication channel.
3076 Optional argument TYPES, when non-nil, is a list of element or
3077 object types, as symbols, that should also be counted in.
3078 Otherwise, only provided element's type is considered.
3080 Optional argument PREDICATE is a function returning a non-nil
3081 value if the current element or object should be counted in. It
3082 accepts two arguments: the element or object being considered and
3083 the plist used as a communication channel. This allows to count
3084 only a certain type of objects (i.e. inline images).
3086 Return value is a list of numbers if ELEMENT is an headline or an
3087 item. It is nil for keywords. It represents the footnote number
3088 for footnote definitions and footnote references. If ELEMENT is
3089 a target, return the same value as if ELEMENT was the closest
3090 table, item or headline containing the target. In any other
3091 case, return the sequence number of ELEMENT among elements or
3092 objects of the same type."
3093 ;; A target keyword, representing an invisible target, never has
3094 ;; a sequence number.
3095 (unless (eq (org-element-type element) 'keyword)
3096 ;; Ordinal of a target object refer to the ordinal of the closest
3097 ;; table, item, or headline containing the object.
3098 (when (eq (org-element-type element) 'target)
3099 (setq element
3100 (loop for parent in (org-export-get-genealogy element info)
3101 when
3102 (memq
3103 (org-element-type parent)
3104 '(footnote-definition footnote-reference headline item
3105 table))
3106 return parent)))
3107 (case (org-element-type element)
3108 ;; Special case 1: An headline returns its number as a list.
3109 (headline (org-export-get-headline-number element info))
3110 ;; Special case 2: An item returns its number as a list.
3111 (item (let ((struct (org-element-property :structure element)))
3112 (org-list-get-item-number
3113 (org-element-property :begin element)
3114 struct
3115 (org-list-prevs-alist struct)
3116 (org-list-parents-alist struct))))
3117 ((footnote definition footnote-reference)
3118 (org-export-get-footnote-number element info))
3119 (otherwise
3120 (let ((counter 0))
3121 ;; Increment counter until ELEMENT is found again.
3122 (org-element-map
3123 (plist-get info :parse-tree) (or types (org-element-type element))
3124 (lambda (el)
3125 (cond
3126 ((equal element el) (1+ counter))
3127 ((not predicate) (incf counter) nil)
3128 ((funcall predicate el info) (incf counter) nil)))
3129 info 'first-match))))))
3132 ;;;; For Src-Blocks
3134 ;; `org-export-get-loc' counts number of code lines accumulated in
3135 ;; src-block or example-block elements with a "+n" switch until
3136 ;; a given element, excluded. Note: "-n" switches reset that count.
3138 ;; `org-export-unravel-code' extracts source code (along with a code
3139 ;; references alist) from an `element-block' or `src-block' type
3140 ;; element.
3142 ;; `org-export-format-code' applies a formatting function to each line
3143 ;; of code, providing relative line number and code reference when
3144 ;; appropriate. Since it doesn't access the original element from
3145 ;; which the source code is coming, it expects from the code calling
3146 ;; it to know if lines should be numbered and if code references
3147 ;; should appear.
3149 ;; Eventually, `org-export-format-code-default' is a higher-level
3150 ;; function (it makes use of the two previous functions) which handles
3151 ;; line numbering and code references inclusion, and returns source
3152 ;; code in a format suitable for plain text or verbatim output.
3154 (defun org-export-get-loc (element info)
3155 "Return accumulated lines of code up to ELEMENT.
3157 INFO is the plist used as a communication channel.
3159 ELEMENT is excluded from count."
3160 (let ((loc 0))
3161 (org-element-map
3162 (plist-get info :parse-tree)
3163 `(src-block example-block ,(org-element-type element))
3164 (lambda (el)
3165 (cond
3166 ;; ELEMENT is reached: Quit the loop.
3167 ((equal el element) t)
3168 ;; Only count lines from src-block and example-block elements
3169 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
3170 ((not (memq (org-element-type el) '(src-block example-block))) nil)
3171 ((let ((linums (org-element-property :number-lines el)))
3172 (when linums
3173 ;; Accumulate locs or reset them.
3174 (let ((lines (org-count-lines
3175 (org-trim (org-element-property :value el)))))
3176 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
3177 ;; Return nil to stay in the loop.
3178 nil)))
3179 info 'first-match)
3180 ;; Return value.
3181 loc))
3183 (defun org-export-unravel-code (element)
3184 "Clean source code and extract references out of it.
3186 ELEMENT has either a `src-block' an `example-block' type.
3188 Return a cons cell whose CAR is the source code, cleaned from any
3189 reference and protective comma and CDR is an alist between
3190 relative line number (integer) and name of code reference on that
3191 line (string)."
3192 (let* ((line 0) refs
3193 ;; Get code and clean it. Remove blank lines at its
3194 ;; beginning and end. Also remove protective commas.
3195 (code (let ((c (replace-regexp-in-string
3196 "\\`\\([ \t]*\n\\)+" ""
3197 (replace-regexp-in-string
3198 "\\(:?[ \t]*\n\\)*[ \t]*\\'" "\n"
3199 (org-element-property :value element)))))
3200 ;; If appropriate, remove global indentation.
3201 (unless (or org-src-preserve-indentation
3202 (org-element-property :preserve-indent element))
3203 (setq c (org-remove-indentation c)))
3204 ;; Free up the protected lines. Note: Org blocks
3205 ;; have commas at the beginning or every line.
3206 (if (string= (org-element-property :language element) "org")
3207 (replace-regexp-in-string "^," "" c)
3208 (replace-regexp-in-string
3209 "^\\(,\\)\\(:?\\*\\|[ \t]*#\\+\\)" "" c nil nil 1))))
3210 ;; Get format used for references.
3211 (label-fmt (regexp-quote
3212 (or (org-element-property :label-fmt element)
3213 org-coderef-label-format)))
3214 ;; Build a regexp matching a loc with a reference.
3215 (with-ref-re
3216 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
3217 (replace-regexp-in-string
3218 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
3219 ;; Return value.
3220 (cons
3221 ;; Code with references removed.
3222 (org-element-normalize-string
3223 (mapconcat
3224 (lambda (loc)
3225 (incf line)
3226 (if (not (string-match with-ref-re loc)) loc
3227 ;; Ref line: remove ref, and signal its position in REFS.
3228 (push (cons line (match-string 3 loc)) refs)
3229 (replace-match "" nil nil loc 1)))
3230 (org-split-string code "\n") "\n"))
3231 ;; Reference alist.
3232 refs)))
3234 (defun org-export-format-code (code fun &optional num-lines ref-alist)
3235 "Format CODE by applying FUN line-wise and return it.
3237 CODE is a string representing the code to format. FUN is
3238 a function. It must accept three arguments: a line of
3239 code (string), the current line number (integer) or nil and the
3240 reference associated to the current line (string) or nil.
3242 Optional argument NUM-LINES can be an integer representing the
3243 number of code lines accumulated until the current code. Line
3244 numbers passed to FUN will take it into account. If it is nil,
3245 FUN's second argument will always be nil. This number can be
3246 obtained with `org-export-get-loc' function.
3248 Optional argument REF-ALIST can be an alist between relative line
3249 number (i.e. ignoring NUM-LINES) and the name of the code
3250 reference on it. If it is nil, FUN's third argument will always
3251 be nil. It can be obtained through the use of
3252 `org-export-unravel-code' function."
3253 (let ((--locs (org-split-string code "\n"))
3254 (--line 0))
3255 (org-element-normalize-string
3256 (mapconcat
3257 (lambda (--loc)
3258 (incf --line)
3259 (let ((--ref (cdr (assq --line ref-alist))))
3260 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
3261 --locs "\n"))))
3263 (defun org-export-format-code-default (element info)
3264 "Return source code from ELEMENT, formatted in a standard way.
3266 ELEMENT is either a `src-block' or `example-block' element. INFO
3267 is a plist used as a communication channel.
3269 This function takes care of line numbering and code references
3270 inclusion. Line numbers, when applicable, appear at the
3271 beginning of the line, separated from the code by two white
3272 spaces. Code references, on the other hand, appear flushed to
3273 the right, separated by six white spaces from the widest line of
3274 code."
3275 ;; Extract code and references.
3276 (let* ((code-info (org-export-unravel-code element))
3277 (code (car code-info))
3278 (code-lines (org-split-string code "\n"))
3279 (refs (and (org-element-property :retain-labels element)
3280 (cdr code-info)))
3281 ;; Handle line numbering.
3282 (num-start (case (org-element-property :number-lines element)
3283 (continued (org-export-get-loc element info))
3284 (new 0)))
3285 (num-fmt
3286 (and num-start
3287 (format "%%%ds "
3288 (length (number-to-string
3289 (+ (length code-lines) num-start))))))
3290 ;; Prepare references display, if required. Any reference
3291 ;; should start six columns after the widest line of code,
3292 ;; wrapped with parenthesis.
3293 (max-width
3294 (+ (apply 'max (mapcar 'length code-lines))
3295 (if (not num-start) 0 (length (format num-fmt num-start))))))
3296 (org-export-format-code
3297 code
3298 (lambda (loc line-num ref)
3299 (let ((number-str (and num-fmt (format num-fmt line-num))))
3300 (concat
3301 number-str
3303 (and ref
3304 (concat (make-string
3305 (- (+ 6 max-width)
3306 (+ (length loc) (length number-str))) ? )
3307 (format "(%s)" ref))))))
3308 num-start refs)))
3311 ;;;; For Tables
3313 ;; `org-export-table-has-special-column-p' and and
3314 ;; `org-export-table-row-is-special-p' are predicates used to look for
3315 ;; meta-information about the table structure.
3317 ;; `org-table-has-header-p' tells when the rows before the first rule
3318 ;; should be considered as table's header.
3320 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
3321 ;; and `org-export-table-cell-borders' extract information from
3322 ;; a table-cell element.
3324 ;; `org-export-table-dimensions' gives the number on rows and columns
3325 ;; in the table, ignoring horizontal rules and special columns.
3326 ;; `org-export-table-cell-address', given a table-cell object, returns
3327 ;; the absolute address of a cell. On the other hand,
3328 ;; `org-export-get-table-cell-at' does the contrary.
3330 ;; `org-export-table-cell-starts-colgroup-p',
3331 ;; `org-export-table-cell-ends-colgroup-p',
3332 ;; `org-export-table-row-starts-rowgroup-p',
3333 ;; `org-export-table-row-ends-rowgroup-p',
3334 ;; `org-export-table-row-starts-header-p' and
3335 ;; `org-export-table-row-ends-header-p' indicate position of current
3336 ;; row or cell within the table.
3338 (defun org-export-table-has-special-column-p (table)
3339 "Non-nil when TABLE has a special column.
3340 All special columns will be ignored during export."
3341 ;; The table has a special column when every first cell of every row
3342 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
3343 ;; "*" "_" and "^". Though, do not consider a first row containing
3344 ;; only empty cells as special.
3345 (let ((special-column-p 'empty))
3346 (catch 'exit
3347 (mapc
3348 (lambda (row)
3349 (when (eq (org-element-property :type row) 'standard)
3350 (let ((value (org-element-contents
3351 (car (org-element-contents row)))))
3352 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
3353 (setq special-column-p 'special))
3354 ((not value))
3355 (t (throw 'exit nil))))))
3356 (org-element-contents table))
3357 (eq special-column-p 'special))))
3359 (defun org-export-table-has-header-p (table info)
3360 "Non-nil when TABLE has an header.
3362 INFO is a plist used as a communication channel.
3364 A table has an header when it contains at least two row groups."
3365 (let ((rowgroup 1) row-flag)
3366 (org-element-map
3367 table 'table-row
3368 (lambda (row)
3369 (cond
3370 ((> rowgroup 1) t)
3371 ((and row-flag (eq (org-element-property :type row) 'rule))
3372 (incf rowgroup) (setq row-flag nil))
3373 ((and (not row-flag) (eq (org-element-property :type row) 'standard))
3374 (setq row-flag t) nil)))
3375 info)))
3377 (defun org-export-table-row-is-special-p (table-row info)
3378 "Non-nil if TABLE-ROW is considered special.
3380 INFO is a plist used as the communication channel.
3382 All special rows will be ignored during export."
3383 (when (eq (org-element-property :type table-row) 'standard)
3384 (let ((first-cell (org-element-contents
3385 (car (org-element-contents table-row)))))
3386 ;; A row is special either when...
3388 ;; ... it starts with a field only containing "/",
3389 (equal first-cell '("/"))
3390 ;; ... the table contains a special column and the row start
3391 ;; with a marking character among, "^", "_", "$" or "!",
3392 (and (org-export-table-has-special-column-p
3393 (org-export-get-parent table-row info))
3394 (member first-cell '(("^") ("_") ("$") ("!"))))
3395 ;; ... it contains only alignment cookies and empty cells.
3396 (let ((special-row-p 'empty))
3397 (catch 'exit
3398 (mapc
3399 (lambda (cell)
3400 (let ((value (org-element-contents cell)))
3401 ;; Since VALUE is a secondary string, the following
3402 ;; checks avoid expanding it with `org-export-data'.
3403 (cond ((not value))
3404 ((and (not (cdr value))
3405 (stringp (car value))
3406 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
3407 (car value)))
3408 (setq special-row-p 'cookie))
3409 (t (throw 'exit nil)))))
3410 (org-element-contents table-row))
3411 (eq special-row-p 'cookie)))))))
3413 (defun org-export-table-row-group (table-row info)
3414 "Return TABLE-ROW's group.
3416 INFO is a plist used as the communication channel.
3418 Return value is the group number, as an integer, or nil special
3419 rows and table rules. Group 1 is also table's header."
3420 (unless (or (eq (org-element-property :type table-row) 'rule)
3421 (org-export-table-row-is-special-p table-row info))
3422 (let ((group 0) row-flag)
3423 (catch 'found
3424 (mapc
3425 (lambda (row)
3426 (cond
3427 ((and (eq (org-element-property :type row) 'standard)
3428 (not (org-export-table-row-is-special-p row info)))
3429 (unless row-flag (incf group) (setq row-flag t)))
3430 ((eq (org-element-property :type row) 'rule)
3431 (setq row-flag nil)))
3432 (when (equal table-row row) (throw 'found group)))
3433 (org-element-contents (org-export-get-parent table-row info)))))))
3435 (defun org-export-table-cell-width (table-cell info)
3436 "Return TABLE-CELL contents width.
3438 INFO is a plist used as the communication channel.
3440 Return value is the width given by the last width cookie in the
3441 same column as TABLE-CELL, or nil."
3442 (let* ((genealogy (org-export-get-genealogy table-cell info))
3443 (row (car genealogy))
3444 (column (let ((cells (org-element-contents row)))
3445 (- (length cells) (length (member table-cell cells)))))
3446 (table (nth 1 genealogy))
3447 cookie-width)
3448 (mapc
3449 (lambda (row)
3450 (cond
3451 ;; In a special row, try to find a width cookie at COLUMN.
3452 ((org-export-table-row-is-special-p row info)
3453 (let ((value (org-element-contents
3454 (elt (org-element-contents row) column))))
3455 ;; The following checks avoid expanding unnecessarily the
3456 ;; cell with `org-export-data'
3457 (when (and value
3458 (not (cdr value))
3459 (stringp (car value))
3460 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" (car value))
3461 (match-string 1 (car value)))
3462 (setq cookie-width
3463 (string-to-number (match-string 1 (car value)))))))
3464 ;; Ignore table rules.
3465 ((eq (org-element-property :type row) 'rule))))
3466 (org-element-contents table))
3467 ;; Return value.
3468 cookie-width))
3470 (defun org-export-table-cell-alignment (table-cell info)
3471 "Return TABLE-CELL contents alignment.
3473 INFO is a plist used as the communication channel.
3475 Return alignment as specified by the last alignment cookie in the
3476 same column as TABLE-CELL. If no such cookie is found, a default
3477 alignment value will be deduced from fraction of numbers in the
3478 column (see `org-table-number-fraction' for more information).
3479 Possible values are `left', `right' and `center'."
3480 (let* ((genealogy (org-export-get-genealogy table-cell info))
3481 (row (car genealogy))
3482 (column (let ((cells (org-element-contents row)))
3483 (- (length cells) (length (member table-cell cells)))))
3484 (table (nth 1 genealogy))
3485 (number-cells 0)
3486 (total-cells 0)
3487 cookie-align)
3488 (mapc
3489 (lambda (row)
3490 (cond
3491 ;; In a special row, try to find an alignment cookie at
3492 ;; COLUMN.
3493 ((org-export-table-row-is-special-p row info)
3494 (let ((value (org-element-contents
3495 (elt (org-element-contents row) column))))
3496 ;; Since VALUE is a secondary string, the following checks
3497 ;; avoid useless expansion through `org-export-data'.
3498 (when (and value
3499 (not (cdr value))
3500 (stringp (car value))
3501 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
3502 (car value))
3503 (match-string 1 (car value)))
3504 (setq cookie-align (match-string 1 (car value))))))
3505 ;; Ignore table rules.
3506 ((eq (org-element-property :type row) 'rule))
3507 ;; In a standard row, check if cell's contents are expressing
3508 ;; some kind of number. Increase NUMBER-CELLS accordingly.
3509 ;; Though, don't bother if an alignment cookie has already
3510 ;; defined cell's alignment.
3511 ((not cookie-align)
3512 (let ((value (org-export-data
3513 (org-element-contents
3514 (elt (org-element-contents row) column))
3515 info)))
3516 (incf total-cells)
3517 (when (string-match org-table-number-regexp value)
3518 (incf number-cells))))))
3519 (org-element-contents table))
3520 ;; Return value. Alignment specified by cookies has precedence
3521 ;; over alignment deduced from cells contents.
3522 (cond ((equal cookie-align "l") 'left)
3523 ((equal cookie-align "r") 'right)
3524 ((equal cookie-align "c") 'center)
3525 ((>= (/ (float number-cells) total-cells) org-table-number-fraction)
3526 'right)
3527 (t 'left))))
3529 (defun org-export-table-cell-borders (table-cell info)
3530 "Return TABLE-CELL borders.
3532 INFO is a plist used as a communication channel.
3534 Return value is a list of symbols, or nil. Possible values are:
3535 `top', `bottom', `above', `below', `left' and `right'. Note:
3536 `top' (resp. `bottom') only happen for a cell in the first
3537 row (resp. last row) of the table, ignoring table rules, if any.
3539 Returned borders ignore special rows."
3540 (let* ((genealogy (org-export-get-genealogy table-cell info))
3541 (row (car genealogy))
3542 (table (nth 1 genealogy))
3543 borders)
3544 ;; Top/above border? TABLE-CELL has a border above when a rule
3545 ;; used to demarcate row groups can be found above. Hence,
3546 ;; finding a rule isn't sufficient to push `above' in BORDERS:
3547 ;; another regular row has to be found above that rule.
3548 (let (rule-flag)
3549 (catch 'exit
3550 (mapc (lambda (row)
3551 (cond ((eq (org-element-property :type row) 'rule)
3552 (setq rule-flag t))
3553 ((not (org-export-table-row-is-special-p row info))
3554 (if rule-flag (throw 'exit (push 'above borders))
3555 (throw 'exit nil)))))
3556 ;; Look at every row before the current one.
3557 (cdr (member row (reverse (org-element-contents table)))))
3558 ;; No rule above, or rule found starts the table (ignoring any
3559 ;; special row): TABLE-CELL is at the top of the table.
3560 (when rule-flag (push 'above borders))
3561 (push 'top borders)))
3562 ;; Bottom/below border? TABLE-CELL has a border below when next
3563 ;; non-regular row below is a rule.
3564 (let (rule-flag)
3565 (catch 'exit
3566 (mapc (lambda (row)
3567 (cond ((eq (org-element-property :type row) 'rule)
3568 (setq rule-flag t))
3569 ((not (org-export-table-row-is-special-p row info))
3570 (if rule-flag (throw 'exit (push 'below borders))
3571 (throw 'exit nil)))))
3572 ;; Look at every row after the current one.
3573 (cdr (member row (org-element-contents table))))
3574 ;; No rule below, or rule found ends the table (modulo some
3575 ;; special row): TABLE-CELL is at the bottom of the table.
3576 (when rule-flag (push 'below borders))
3577 (push 'bottom borders)))
3578 ;; Right/left borders? They can only be specified by column
3579 ;; groups. Column groups are defined in a row starting with "/".
3580 ;; Also a column groups row only contains "<", "<>", ">" or blank
3581 ;; cells.
3582 (catch 'exit
3583 (let ((column (let ((cells (org-element-contents row)))
3584 (- (length cells) (length (member table-cell cells))))))
3585 (mapc
3586 (lambda (row)
3587 (unless (eq (org-element-property :type row) 'rule)
3588 (when (equal (org-element-contents
3589 (car (org-element-contents row)))
3590 '("/"))
3591 (let ((column-groups
3592 (mapcar
3593 (lambda (cell)
3594 (let ((value (org-element-contents cell)))
3595 (when (member value '(("<") ("<>") (">") nil))
3596 (car value))))
3597 (org-element-contents row))))
3598 ;; There's a left border when previous cell, if
3599 ;; any, ends a group, or current one starts one.
3600 (when (or (and (not (zerop column))
3601 (member (elt column-groups (1- column))
3602 '(">" "<>")))
3603 (member (elt column-groups column) '("<" "<>")))
3604 (push 'left borders))
3605 ;; There's a right border when next cell, if any,
3606 ;; starts a group, or current one ends one.
3607 (when (or (and (/= (1+ column) (length column-groups))
3608 (member (elt column-groups (1+ column))
3609 '("<" "<>")))
3610 (member (elt column-groups column) '(">" "<>")))
3611 (push 'right borders))
3612 (throw 'exit nil)))))
3613 ;; Table rows are read in reverse order so last column groups
3614 ;; row has precedence over any previous one.
3615 (reverse (org-element-contents table)))))
3616 ;; Return value.
3617 borders))
3619 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
3620 "Non-nil when TABLE-CELL is at the beginning of a row group.
3621 INFO is a plist used as a communication channel."
3622 ;; A cell starts a column group either when it is at the beginning
3623 ;; of a row (or after the special column, if any) or when it has
3624 ;; a left border.
3625 (or (equal (org-element-map
3626 (org-export-get-parent table-cell info)
3627 'table-cell 'identity info 'first-match)
3628 table-cell)
3629 (memq 'left (org-export-table-cell-borders table-cell info))))
3631 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
3632 "Non-nil when TABLE-CELL is at the end of a row group.
3633 INFO is a plist used as a communication channel."
3634 ;; A cell ends a column group either when it is at the end of a row
3635 ;; or when it has a right border.
3636 (or (equal (car (last (org-element-contents
3637 (org-export-get-parent table-cell info))))
3638 table-cell)
3639 (memq 'right (org-export-table-cell-borders table-cell info))))
3641 (defun org-export-table-row-starts-rowgroup-p (table-row info)
3642 "Non-nil when TABLE-ROW is at the beginning of a column group.
3643 INFO is a plist used as a communication channel."
3644 (unless (or (eq (org-element-property :type table-row) 'rule)
3645 (org-export-table-row-is-special-p table-row info))
3646 (let ((borders (org-export-table-cell-borders
3647 (car (org-element-contents table-row)) info)))
3648 (or (memq 'top borders) (memq 'above borders)))))
3650 (defun org-export-table-row-ends-rowgroup-p (table-row info)
3651 "Non-nil when TABLE-ROW is at the end of a column group.
3652 INFO is a plist used as a communication channel."
3653 (unless (or (eq (org-element-property :type table-row) 'rule)
3654 (org-export-table-row-is-special-p table-row info))
3655 (let ((borders (org-export-table-cell-borders
3656 (car (org-element-contents table-row)) info)))
3657 (or (memq 'bottom borders) (memq 'below borders)))))
3659 (defun org-export-table-row-starts-header-p (table-row info)
3660 "Non-nil when TABLE-ROW is the first table header's row.
3661 INFO is a plist used as a communication channel."
3662 (and (org-export-table-has-header-p
3663 (org-export-get-parent-table table-row info) info)
3664 (org-export-table-row-starts-rowgroup-p table-row info)
3665 (= (org-export-table-row-group table-row info) 1)))
3667 (defun org-export-table-row-ends-header-p (table-row info)
3668 "Non-nil when TABLE-ROW is the last table header's row.
3669 INFO is a plist used as a communication channel."
3670 (and (org-export-table-has-header-p
3671 (org-export-get-parent-table table-row info) info)
3672 (org-export-table-row-ends-rowgroup-p table-row info)
3673 (= (org-export-table-row-group table-row info) 1)))
3675 (defun org-export-table-dimensions (table info)
3676 "Return TABLE dimensions.
3678 INFO is a plist used as a communication channel.
3680 Return value is a CONS like (ROWS . COLUMNS) where
3681 ROWS (resp. COLUMNS) is the number of exportable
3682 rows (resp. columns)."
3683 (let (first-row (columns 0) (rows 0))
3684 ;; Set number of rows, and extract first one.
3685 (org-element-map
3686 table 'table-row
3687 (lambda (row)
3688 (when (eq (org-element-property :type row) 'standard)
3689 (incf rows)
3690 (unless first-row (setq first-row row)))) info)
3691 ;; Set number of columns.
3692 (org-element-map first-row 'table-cell (lambda (cell) (incf columns)) info)
3693 ;; Return value.
3694 (cons rows columns)))
3696 (defun org-export-table-cell-address (table-cell info)
3697 "Return address of a regular TABLE-CELL object.
3699 TABLE-CELL is the cell considered. INFO is a plist used as
3700 a communication channel.
3702 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
3703 zero-based index. Only exportable cells are considered. The
3704 function returns nil for other cells."
3705 (let* ((table-row (org-export-get-parent table-cell info))
3706 (table (org-export-get-parent-table table-cell info)))
3707 ;; Ignore cells in special rows or in special column.
3708 (unless (or (org-export-table-row-is-special-p table-row info)
3709 (and (org-export-table-has-special-column-p table)
3710 (equal (car (org-element-contents table-row)) table-cell)))
3711 (cons
3712 ;; Row number.
3713 (let ((row-count 0))
3714 (org-element-map
3715 table 'table-row
3716 (lambda (row)
3717 (cond ((eq (org-element-property :type row) 'rule) nil)
3718 ((equal row table-row) row-count)
3719 (t (incf row-count) nil)))
3720 info 'first-match))
3721 ;; Column number.
3722 (let ((col-count 0))
3723 (org-element-map
3724 table-row 'table-cell
3725 (lambda (cell)
3726 (if (equal cell table-cell) col-count
3727 (incf col-count) nil))
3728 info 'first-match))))))
3730 (defun org-export-get-table-cell-at (address table info)
3731 "Return regular table-cell object at ADDRESS in TABLE.
3733 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
3734 zero-based index. TABLE is a table type element. INFO is
3735 a plist used as a communication channel.
3737 If no table-cell, among exportable cells, is found at ADDRESS,
3738 return nil."
3739 (let ((column-pos (cdr address)) (column-count 0))
3740 (org-element-map
3741 ;; Row at (car address) or nil.
3742 (let ((row-pos (car address)) (row-count 0))
3743 (org-element-map
3744 table 'table-row
3745 (lambda (row)
3746 (cond ((eq (org-element-property :type row) 'rule) nil)
3747 ((= row-count row-pos) row)
3748 (t (incf row-count) nil)))
3749 info 'first-match))
3750 'table-cell
3751 (lambda (cell)
3752 (if (= column-count column-pos) cell
3753 (incf column-count) nil))
3754 info 'first-match)))
3757 ;;;; For Tables Of Contents
3759 ;; `org-export-collect-headlines' builds a list of all exportable
3760 ;; headline elements, maybe limited to a certain depth. One can then
3761 ;; easily parse it and transcode it.
3763 ;; Building lists of tables, figures or listings is quite similar.
3764 ;; Once the generic function `org-export-collect-elements' is defined,
3765 ;; `org-export-collect-tables', `org-export-collect-figures' and
3766 ;; `org-export-collect-listings' can be derived from it.
3768 (defun org-export-collect-headlines (info &optional n)
3769 "Collect headlines in order to build a table of contents.
3771 INFO is a plist used as a communication channel.
3773 When non-nil, optional argument N must be an integer. It
3774 specifies the depth of the table of contents.
3776 Return a list of all exportable headlines as parsed elements."
3777 (org-element-map
3778 (plist-get info :parse-tree)
3779 'headline
3780 (lambda (headline)
3781 ;; Strip contents from HEADLINE.
3782 (let ((relative-level (org-export-get-relative-level headline info)))
3783 (unless (and n (> relative-level n)) headline)))
3784 info))
3786 (defun org-export-collect-elements (type info &optional predicate)
3787 "Collect referenceable elements of a determined type.
3789 TYPE can be a symbol or a list of symbols specifying element
3790 types to search. Only elements with a caption are collected.
3792 INFO is a plist used as a communication channel.
3794 When non-nil, optional argument PREDICATE is a function accepting
3795 one argument, an element of type TYPE. It returns a non-nil
3796 value when that element should be collected.
3798 Return a list of all elements found, in order of appearance."
3799 (org-element-map
3800 (plist-get info :parse-tree) type
3801 (lambda (element)
3802 (and (org-element-property :caption element)
3803 (or (not predicate) (funcall predicate element))
3804 element))
3805 info))
3807 (defun org-export-collect-tables (info)
3808 "Build a list of tables.
3809 INFO is a plist used as a communication channel.
3811 Return a list of table elements with a caption."
3812 (org-export-collect-elements 'table info))
3814 (defun org-export-collect-figures (info predicate)
3815 "Build a list of figures.
3817 INFO is a plist used as a communication channel. PREDICATE is
3818 a function which accepts one argument: a paragraph element and
3819 whose return value is non-nil when that element should be
3820 collected.
3822 A figure is a paragraph type element, with a caption, verifying
3823 PREDICATE. The latter has to be provided since a \"figure\" is
3824 a vague concept that may depend on back-end.
3826 Return a list of elements recognized as figures."
3827 (org-export-collect-elements 'paragraph info predicate))
3829 (defun org-export-collect-listings (info)
3830 "Build a list of src blocks.
3832 INFO is a plist used as a communication channel.
3834 Return a list of src-block elements with a caption."
3835 (org-export-collect-elements 'src-block info))
3838 ;;;; Topology
3840 ;; Here are various functions to retrieve information about the
3841 ;; neighbourhood of a given element or object. Neighbours of interest
3842 ;; are direct parent (`org-export-get-parent'), parent headline
3843 ;; (`org-export-get-parent-headline'), parent paragraph
3844 ;; (`org-export-get-parent-paragraph'), previous element or object
3845 ;; (`org-export-get-previous-element') and next element or object
3846 ;; (`org-export-get-next-element').
3848 ;; All of these functions are just a specific use of the more generic
3849 ;; `org-export-get-genealogy', which returns the genealogy relative to
3850 ;; the element or object.
3852 (defun org-export-get-genealogy (blob info)
3853 "Return genealogy relative to a given element or object.
3854 BLOB is the element or object being considered. INFO is a plist
3855 used as a communication channel."
3856 (let* ((type (org-element-type blob))
3857 (end (org-element-property :end blob))
3858 (walk-data
3859 (lambda (data genealogy)
3860 ;; Walk DATA, looking for BLOB. GENEALOGY is the list of
3861 ;; parents of all elements in DATA.
3862 (mapc
3863 (lambda (el)
3864 (cond
3865 ((stringp el) nil)
3866 ((equal el blob) (throw 'exit genealogy))
3867 ((>= (org-element-property :end el) end)
3868 ;; If BLOB is an object and EL contains a secondary
3869 ;; string, be sure to check it.
3870 (when (memq type org-element-all-objects)
3871 (let ((sec-prop
3872 (cdr (assq (org-element-type el)
3873 org-element-secondary-value-alist))))
3874 (when sec-prop
3875 (funcall
3876 walk-data
3877 (cons 'org-data
3878 (cons nil (org-element-property sec-prop el)))
3879 (cons el genealogy)))))
3880 (funcall walk-data el (cons el genealogy)))))
3881 (org-element-contents data)))))
3882 (catch 'exit (funcall walk-data (plist-get info :parse-tree) nil) nil)))
3884 (defun org-export-get-parent (blob info)
3885 "Return BLOB parent or nil.
3886 BLOB is the element or object considered. INFO is a plist used
3887 as a communication channel."
3888 (car (org-export-get-genealogy blob info)))
3890 (defun org-export-get-parent-headline (blob info)
3891 "Return BLOB parent headline or nil.
3892 BLOB is the element or object being considered. INFO is a plist
3893 used as a communication channel."
3894 (catch 'exit
3895 (mapc
3896 (lambda (el) (when (eq (org-element-type el) 'headline) (throw 'exit el)))
3897 (org-export-get-genealogy blob info))
3898 nil))
3900 (defun org-export-get-parent-paragraph (object info)
3901 "Return OBJECT parent paragraph or nil.
3902 OBJECT is the object to consider. INFO is a plist used as
3903 a communication channel."
3904 (catch 'exit
3905 (mapc
3906 (lambda (el) (when (eq (org-element-type el) 'paragraph) (throw 'exit el)))
3907 (org-export-get-genealogy object info))
3908 nil))
3910 (defun org-export-get-parent-table (object info)
3911 "Return OBJECT parent table or nil.
3912 OBJECT is either a `table-cell' or `table-element' type object.
3913 INFO is a plist used as a communication channel."
3914 (catch 'exit
3915 (mapc
3916 (lambda (el) (when (eq (org-element-type el) 'table) (throw 'exit el)))
3917 (org-export-get-genealogy object info))
3918 nil))
3920 (defun org-export-get-previous-element (blob info)
3921 "Return previous element or object.
3923 BLOB is an element or object. INFO is a plist used as
3924 a communication channel.
3926 Return previous element or object, a string, or nil."
3927 (let ((parent (org-export-get-parent blob info)))
3928 (cadr (member blob (reverse (org-element-contents parent))))))
3930 (defun org-export-get-next-element (blob info)
3931 "Return next element or object.
3933 BLOB is an element or object. INFO is a plist used as
3934 a communication channel.
3936 Return next element or object, a string, or nil."
3937 (let ((parent (org-export-get-parent blob info)))
3938 (cadr (member blob (org-element-contents parent)))))
3942 ;;; The Dispatcher
3944 ;; `org-export-dispatch' is the standard interactive way to start an
3945 ;; export process. It uses `org-export-dispatch-ui' as a subroutine
3946 ;; for its interface. Most commons back-ends should have an entry in
3947 ;; it.
3949 (defun org-export-dispatch ()
3950 "Export dispatcher for Org mode.
3952 It provides an access to common export related tasks in a buffer.
3953 Its interface comes in two flavours: standard and expert. While
3954 both share the same set of bindings, only the former displays the
3955 valid keys associations. Set `org-export-dispatch-use-expert-ui'
3956 to switch to one or the other.
3958 Return an error if key pressed has no associated command."
3959 (interactive)
3960 (let* ((input (org-export-dispatch-ui
3961 (if (listp org-export-initial-scope) org-export-initial-scope
3962 (list org-export-initial-scope))
3963 org-export-dispatch-use-expert-ui))
3964 (raw-key (car input))
3965 (optns (cdr input)))
3966 ;; Translate "C-a", "C-b"... into "a", "b"... Then take action
3967 ;; depending on user's key pressed.
3968 (case (if (< raw-key 27) (+ raw-key 96) raw-key)
3969 ;; Allow to quit with "q" key.
3970 (?q nil)
3971 ;; Export with `e-ascii' back-end.
3972 ((?A ?N ?U)
3973 (require 'org-e-ascii)
3974 (let ((outbuf
3975 (org-export-to-buffer
3976 'e-ascii "*Org E-ASCII Export*"
3977 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)
3978 `(:ascii-charset
3979 ,(case raw-key (?A 'ascii) (?N 'latin1) (t 'utf-8))))))
3980 (with-current-buffer outbuf (text-mode))
3981 (when org-export-show-temporary-export-buffer
3982 (switch-to-buffer-other-window outbuf))))
3983 ((?a ?n ?u)
3984 (require 'org-e-ascii)
3985 (org-e-ascii-export-to-ascii
3986 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)
3987 `(:ascii-charset ,(case raw-key (?a 'ascii) (?n 'latin1) (t 'utf-8)))))
3988 ;; Export with `e-latex' back-end.
3990 (require 'org-e-latex)
3991 (let ((outbuf
3992 (org-export-to-buffer
3993 'e-latex "*Org E-LaTeX Export*"
3994 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
3995 (with-current-buffer outbuf (latex-mode))
3996 (when org-export-show-temporary-export-buffer
3997 (switch-to-buffer-other-window outbuf))))
3999 (require 'org-e-latex)
4000 (org-e-latex-export-to-latex
4001 (require 'org-e-latex)
4002 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
4004 (require 'org-e-latex)
4005 (org-e-latex-export-to-pdf
4006 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
4008 (require 'org-e-latex)
4009 (org-open-file
4010 (org-e-latex-export-to-pdf
4011 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
4012 ;; Export with `e-html' back-end.
4014 (require 'org-e-html)
4015 (let ((outbuf
4016 (org-export-to-buffer
4017 'e-html "*Org E-HTML Export*"
4018 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
4019 ;; set major mode
4020 (with-current-buffer outbuf
4021 (if (featurep 'nxhtml-mode) (nxhtml-mode) (nxml-mode)))
4022 (when org-export-show-temporary-export-buffer
4023 (switch-to-buffer-other-window outbuf))))
4025 (require 'org-e-html)
4026 (org-e-html-export-to-html
4027 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
4029 (require 'org-e-html)
4030 (org-open-file
4031 (org-e-html-export-to-html
4032 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
4033 ;; Export with `e-odt' back-end.
4035 (require 'org-e-odt)
4036 (org-e-odt-export-to-odt
4037 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
4039 (require 'org-e-odt)
4040 (org-open-file
4041 (org-e-odt-export-to-odt
4042 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
4043 ;; Publishing facilities
4045 (require 'org-e-publish)
4046 (org-e-publish-current-file (memq 'force optns)))
4048 (require 'org-e-publish)
4049 (org-e-publish-current-project (memq 'force optns)))
4051 (require 'org-e-publish)
4052 (let ((project
4053 (assoc (org-icompleting-read
4054 "Publish project: " org-e-publish-project-alist nil t)
4055 org-e-publish-project-alist)))
4056 (org-e-publish project (memq 'force optns))))
4058 (require 'org-e-publish)
4059 (org-e-publish-all (memq 'force optns)))
4060 ;; Undefined command.
4061 (t (error "No command associated with key %s"
4062 (char-to-string raw-key))))))
4064 (defun org-export-dispatch-ui (options expertp)
4065 "Handle interface for `org-export-dispatch'.
4067 OPTIONS is a list containing current interactive options set for
4068 export. It can contain any of the following symbols:
4069 `body' toggles a body-only export
4070 `subtree' restricts export to current subtree
4071 `visible' restricts export to visible part of buffer.
4072 `force' force publishing files.
4074 EXPERTP, when non-nil, triggers expert UI. In that case, no help
4075 buffer is provided, but indications about currently active
4076 options are given in the prompt. Moreover, \[?] allows to switch
4077 back to standard interface.
4079 Return value is a list with key pressed as CAR and a list of
4080 final interactive export options as CDR."
4081 (let ((help
4082 (format "---- (Options) -------------------------------------------
4084 \[1] Body only: %s [2] Export scope: %s
4085 \[3] Visible only: %s [4] Force publishing: %s
4088 --- (ASCII/Latin-1/UTF-8 Export) -------------------------
4090 \[a/n/u] to TXT file [A/N/U] to temporary buffer
4092 --- (HTML Export) ----------------------------------------
4094 \[h] to HTML file [b] ... and open it
4095 \[H] to temporary buffer
4097 --- (LaTeX Export) ---------------------------------------
4099 \[l] to TEX file [L] to temporary buffer
4100 \[p] to PDF file [d] ... and open it
4102 --- (ODF Export) -----------------------------------------
4104 \[o] to ODT file [O] ... and open it
4106 --- (Publish) --------------------------------------------
4108 \[F] current file [P] current project
4109 \[X] a project [E] every project"
4110 (if (memq 'body options) "On " "Off")
4111 (if (memq 'subtree options) "Subtree" "Buffer ")
4112 (if (memq 'visible options) "On " "Off")
4113 (if (memq 'force options) "On " "Off")))
4114 (standard-prompt "Export command: ")
4115 (expert-prompt (format "Export command (%s%s%s%s): "
4116 (if (memq 'body options) "b" "-")
4117 (if (memq 'subtree options) "s" "-")
4118 (if (memq 'visible options) "v" "-")
4119 (if (memq 'force options) "f" "-")))
4120 (handle-keypress
4121 (function
4122 ;; Read a character from command input, toggling interactive
4123 ;; options when applicable. PROMPT is the displayed prompt,
4124 ;; as a string.
4125 (lambda (prompt)
4126 (let ((key (read-char-exclusive prompt)))
4127 (cond
4128 ;; Ignore non-standard characters (i.e. "M-a").
4129 ((not (characterp key)) (org-export-dispatch-ui options expertp))
4130 ;; Help key: Switch back to standard interface if
4131 ;; expert UI was active.
4132 ((eq key ??) (org-export-dispatch-ui options nil))
4133 ;; Toggle export options.
4134 ((memq key '(?1 ?2 ?3 ?4))
4135 (org-export-dispatch-ui
4136 (let ((option (case key (?1 'body) (?2 'subtree) (?3 'visible)
4137 (?4 'force))))
4138 (if (memq option options) (remq option options)
4139 (cons option options)))
4140 expertp))
4141 ;; Action selected: Send key and options back to
4142 ;; `org-export-dispatch'.
4143 (t (cons key options))))))))
4144 ;; With expert UI, just read key with a fancy prompt. In standard
4145 ;; UI, display an intrusive help buffer.
4146 (if expertp (funcall handle-keypress expert-prompt)
4147 (save-window-excursion
4148 (delete-other-windows)
4149 (with-output-to-temp-buffer "*Org Export/Publishing Help*" (princ help))
4150 (org-fit-window-to-buffer
4151 (get-buffer-window "*Org Export/Publishing Help*"))
4152 (funcall handle-keypress standard-prompt)))))
4155 (provide 'org-export)
4156 ;;; org-export.el ends here