ox-latex.el (latex): Don't force exporting with smart quotes
[org-mode.git] / lisp / ox.el
blob31b1907c0393a7cd6ea07bf4248882603e9272e8
1 ;;; ox.el --- Generic Export Engine for Org Mode
3 ;; Copyright (C) 2012, 2013 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; GNU Emacs 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 ;; GNU Emacs 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 GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
21 ;;; Commentary:
23 ;; This library implements a generic export engine for Org, built on
24 ;; its syntactical parser: Org Elements.
26 ;; Besides that parser, the generic exporter is made of three distinct
27 ;; parts:
29 ;; - The communication channel consists in a property list, which is
30 ;; created and updated during the process. Its use is to offer
31 ;; every piece of information, would it be about initial environment
32 ;; or contextual data, all in a single place. The exhaustive list
33 ;; of properties is given in "The Communication Channel" section of
34 ;; this file.
36 ;; - The transcoder walks the parse tree, ignores or treat as plain
37 ;; text elements and objects according to export options, and
38 ;; eventually calls back-end specific functions to do the real
39 ;; transcoding, concatenating their return value along the way.
41 ;; - The filter system is activated at the very beginning and the very
42 ;; end of the export process, and each time an element or an object
43 ;; has been converted. It is the entry point to fine-tune standard
44 ;; output from back-end transcoders. See "The Filter System"
45 ;; section for more information.
47 ;; The core function is `org-export-as'. It returns the transcoded
48 ;; buffer as a string.
50 ;; An export back-end is defined with `org-export-define-backend',
51 ;; which defines one mandatory information: his translation table.
52 ;; Its value is an alist whose keys are elements and objects types and
53 ;; values translator functions. See function's docstring for more
54 ;; information about translators.
56 ;; Optionally, `org-export-define-backend' can also support specific
57 ;; buffer keywords, OPTION keyword's items and filters. Also refer to
58 ;; function documentation for more information.
60 ;; If the new back-end shares most properties with another one,
61 ;; `org-export-define-derived-backend' can be used to simplify the
62 ;; process.
64 ;; Any back-end can define its own variables. Among them, those
65 ;; customizable should belong to the `org-export-BACKEND' group.
67 ;; Tools for common tasks across back-ends are implemented in the
68 ;; following part of the file.
70 ;; Then, a wrapper macro for asynchronous export,
71 ;; `org-export-async-start', along with tools to display results. are
72 ;; given in the penultimate part.
74 ;; Eventually, a dispatcher (`org-export-dispatch') for standard
75 ;; back-ends is provided in the last one.
77 ;;; Code:
79 (eval-when-compile (require 'cl))
80 (require 'org-element)
81 (require 'org-macro)
82 (require 'ob-exp)
84 (declare-function org-publish "ox-publish" (project &optional force async))
85 (declare-function org-publish-all "ox-publish" (&optional force async))
86 (declare-function
87 org-publish-current-file "ox-publish" (&optional force async))
88 (declare-function org-publish-current-project "ox-publish"
89 (&optional force async))
91 (defvar org-publish-project-alist)
92 (defvar org-table-number-fraction)
93 (defvar org-table-number-regexp)
97 ;;; Internal Variables
99 ;; Among internal variables, the most important is
100 ;; `org-export-options-alist'. This variable define the global export
101 ;; options, shared between every exporter, and how they are acquired.
103 (defconst org-export-max-depth 19
104 "Maximum nesting depth for headlines, counting from 0.")
106 (defconst org-export-options-alist
107 '((:author "AUTHOR" nil user-full-name t)
108 (:creator "CREATOR" nil org-export-creator-string)
109 (:date "DATE" nil nil t)
110 (:description "DESCRIPTION" nil nil newline)
111 (:email "EMAIL" nil user-mail-address t)
112 (:exclude-tags "EXCLUDE_TAGS" nil org-export-exclude-tags split)
113 (:headline-levels nil "H" org-export-headline-levels)
114 (:keywords "KEYWORDS" nil nil space)
115 (:language "LANGUAGE" nil org-export-default-language t)
116 (:preserve-breaks nil "\\n" org-export-preserve-breaks)
117 (:section-numbers nil "num" org-export-with-section-numbers)
118 (:select-tags "SELECT_TAGS" nil org-export-select-tags split)
119 (:time-stamp-file nil "timestamp" org-export-time-stamp-file)
120 (:title "TITLE" nil nil space)
121 (:with-archived-trees nil "arch" org-export-with-archived-trees)
122 (:with-author nil "author" org-export-with-author)
123 (:with-clocks nil "c" org-export-with-clocks)
124 (:with-creator nil "creator" org-export-with-creator)
125 (:with-date nil "date" org-export-with-date)
126 (:with-drawers nil "d" org-export-with-drawers)
127 (:with-email nil "email" org-export-with-email)
128 (:with-emphasize nil "*" org-export-with-emphasize)
129 (:with-entities nil "e" org-export-with-entities)
130 (:with-fixed-width nil ":" org-export-with-fixed-width)
131 (:with-footnotes nil "f" org-export-with-footnotes)
132 (:with-inlinetasks nil "inline" org-export-with-inlinetasks)
133 (:with-latex nil "tex" org-export-with-latex)
134 (:with-planning nil "p" org-export-with-planning)
135 (:with-priority nil "pri" org-export-with-priority)
136 (:with-smart-quotes nil "'" org-export-with-smart-quotes)
137 (:with-special-strings nil "-" org-export-with-special-strings)
138 (:with-statistics-cookies nil "stat" org-export-with-statistics-cookies)
139 (:with-sub-superscript nil "^" org-export-with-sub-superscripts)
140 (:with-toc nil "toc" org-export-with-toc)
141 (:with-tables nil "|" org-export-with-tables)
142 (:with-tags nil "tags" org-export-with-tags)
143 (:with-tasks nil "tasks" org-export-with-tasks)
144 (:with-timestamps nil "<" org-export-with-timestamps)
145 (:with-todo-keywords nil "todo" org-export-with-todo-keywords))
146 "Alist between export properties and ways to set them.
148 The CAR of the alist is the property name, and the CDR is a list
149 like (KEYWORD OPTION DEFAULT BEHAVIOUR) where:
151 KEYWORD is a string representing a buffer keyword, or nil. Each
152 property defined this way can also be set, during subtree
153 export, through a headline property named after the keyword
154 with the \"EXPORT_\" prefix (i.e. DATE keyword and EXPORT_DATE
155 property).
156 OPTION is a string that could be found in an #+OPTIONS: line.
157 DEFAULT is the default value for the property.
158 BEHAVIOUR determines how Org should handle multiple keywords for
159 the same property. It is a symbol among:
160 nil Keep old value and discard the new one.
161 t Replace old value with the new one.
162 `space' Concatenate the values, separating them with a space.
163 `newline' Concatenate the values, separating them with
164 a newline.
165 `split' Split values at white spaces, and cons them to the
166 previous list.
168 Values set through KEYWORD and OPTION have precedence over
169 DEFAULT.
171 All these properties should be back-end agnostic. Back-end
172 specific properties are set through `org-export-define-backend'.
173 Properties redefined there have precedence over these.")
175 (defconst org-export-special-keywords '("FILETAGS" "SETUPFILE" "OPTIONS")
176 "List of in-buffer keywords that require special treatment.
177 These keywords are not directly associated to a property. The
178 way they are handled must be hard-coded into
179 `org-export--get-inbuffer-options' function.")
181 (defconst org-export-filters-alist
182 '((:filter-bold . org-export-filter-bold-functions)
183 (:filter-babel-call . org-export-filter-babel-call-functions)
184 (:filter-center-block . org-export-filter-center-block-functions)
185 (:filter-clock . org-export-filter-clock-functions)
186 (:filter-code . org-export-filter-code-functions)
187 (:filter-comment . org-export-filter-comment-functions)
188 (:filter-comment-block . org-export-filter-comment-block-functions)
189 (:filter-diary-sexp . org-export-filter-diary-sexp-functions)
190 (:filter-drawer . org-export-filter-drawer-functions)
191 (:filter-dynamic-block . org-export-filter-dynamic-block-functions)
192 (:filter-entity . org-export-filter-entity-functions)
193 (:filter-example-block . org-export-filter-example-block-functions)
194 (:filter-export-block . org-export-filter-export-block-functions)
195 (:filter-export-snippet . org-export-filter-export-snippet-functions)
196 (:filter-final-output . org-export-filter-final-output-functions)
197 (:filter-fixed-width . org-export-filter-fixed-width-functions)
198 (:filter-footnote-definition . org-export-filter-footnote-definition-functions)
199 (:filter-footnote-reference . org-export-filter-footnote-reference-functions)
200 (:filter-headline . org-export-filter-headline-functions)
201 (:filter-horizontal-rule . org-export-filter-horizontal-rule-functions)
202 (:filter-inline-babel-call . org-export-filter-inline-babel-call-functions)
203 (:filter-inline-src-block . org-export-filter-inline-src-block-functions)
204 (:filter-inlinetask . org-export-filter-inlinetask-functions)
205 (:filter-italic . org-export-filter-italic-functions)
206 (:filter-item . org-export-filter-item-functions)
207 (:filter-keyword . org-export-filter-keyword-functions)
208 (:filter-latex-environment . org-export-filter-latex-environment-functions)
209 (:filter-latex-fragment . org-export-filter-latex-fragment-functions)
210 (:filter-line-break . org-export-filter-line-break-functions)
211 (:filter-link . org-export-filter-link-functions)
212 (:filter-node-property . org-export-filter-node-property-functions)
213 (:filter-options . org-export-filter-options-functions)
214 (:filter-paragraph . org-export-filter-paragraph-functions)
215 (:filter-parse-tree . org-export-filter-parse-tree-functions)
216 (:filter-plain-list . org-export-filter-plain-list-functions)
217 (:filter-plain-text . org-export-filter-plain-text-functions)
218 (:filter-planning . org-export-filter-planning-functions)
219 (:filter-property-drawer . org-export-filter-property-drawer-functions)
220 (:filter-quote-block . org-export-filter-quote-block-functions)
221 (:filter-quote-section . org-export-filter-quote-section-functions)
222 (:filter-radio-target . org-export-filter-radio-target-functions)
223 (:filter-section . org-export-filter-section-functions)
224 (:filter-special-block . org-export-filter-special-block-functions)
225 (:filter-src-block . org-export-filter-src-block-functions)
226 (:filter-statistics-cookie . org-export-filter-statistics-cookie-functions)
227 (:filter-strike-through . org-export-filter-strike-through-functions)
228 (:filter-subscript . org-export-filter-subscript-functions)
229 (:filter-superscript . org-export-filter-superscript-functions)
230 (:filter-table . org-export-filter-table-functions)
231 (:filter-table-cell . org-export-filter-table-cell-functions)
232 (:filter-table-row . org-export-filter-table-row-functions)
233 (:filter-target . org-export-filter-target-functions)
234 (:filter-timestamp . org-export-filter-timestamp-functions)
235 (:filter-underline . org-export-filter-underline-functions)
236 (:filter-verbatim . org-export-filter-verbatim-functions)
237 (:filter-verse-block . org-export-filter-verse-block-functions))
238 "Alist between filters properties and initial values.
240 The key of each association is a property name accessible through
241 the communication channel. Its value is a configurable global
242 variable defining initial filters.
244 This list is meant to install user specified filters. Back-end
245 developers may install their own filters using
246 `org-export-define-backend'. Filters defined there will always
247 be prepended to the current list, so they always get applied
248 first.")
250 (defconst org-export-default-inline-image-rule
251 `(("file" .
252 ,(format "\\.%s\\'"
253 (regexp-opt
254 '("png" "jpeg" "jpg" "gif" "tiff" "tif" "xbm"
255 "xpm" "pbm" "pgm" "ppm") t))))
256 "Default rule for link matching an inline image.
257 This rule applies to links with no description. By default, it
258 will be considered as an inline image if it targets a local file
259 whose extension is either \"png\", \"jpeg\", \"jpg\", \"gif\",
260 \"tiff\", \"tif\", \"xbm\", \"xpm\", \"pbm\", \"pgm\" or \"ppm\".
261 See `org-export-inline-image-p' for more information about
262 rules.")
264 (defvar org-export-async-debug nil
265 "Non-nil means asynchronous export process should leave data behind.
267 This data is found in the appropriate \"*Org Export Process*\"
268 buffer, and in files prefixed with \"org-export-process\" and
269 located in `temporary-file-directory'.
271 When non-nil, it will also set `debug-on-error' to a non-nil
272 value in the external process.")
274 (defvar org-export-stack-contents nil
275 "Record asynchronously generated export results and processes.
276 This is an alist: its CAR is the source of the
277 result (destination file or buffer for a finished process,
278 original buffer for a running one) and its CDR is a list
279 containing the back-end used, as a symbol, and either a process
280 or the time at which it finished. It is used to build the menu
281 from `org-export-stack'.")
283 (defvar org-export-registered-backends nil
284 "List of backends currently available in the exporter.
286 A backend is stored as a list where CAR is its name, as a symbol,
287 and CDR is a plist with the following properties:
288 `:filters-alist', `:menu-entry', `:options-alist' and
289 `:translate-alist'.
291 This variable is set with `org-export-define-backend' and
292 `org-export-define-derived-backend' functions.")
294 (defvar org-export-dispatch-last-action nil
295 "Last command called from the dispatcher.
296 The value should be a list. Its CAR is the action, as a symbol,
297 and its CDR is a list of export options.")
299 (defvar org-export-dispatch-last-position (make-marker)
300 "The position where the last export command was created using the dispatcher.
301 This marker will be used with `C-u C-c C-e' to make sure export repetition
302 uses the same subtree if the previous command was restricted to a subtree.")
305 ;;; User-configurable Variables
307 ;; Configuration for the masses.
309 ;; They should never be accessed directly, as their value is to be
310 ;; stored in a property list (cf. `org-export-options-alist').
311 ;; Back-ends will read their value from there instead.
313 (defgroup org-export nil
314 "Options for exporting Org mode files."
315 :tag "Org Export"
316 :group 'org)
318 (defgroup org-export-general nil
319 "General options for export engine."
320 :tag "Org Export General"
321 :group 'org-export)
323 (defcustom org-export-with-archived-trees 'headline
324 "Whether sub-trees with the ARCHIVE tag should be exported.
326 This can have three different values:
327 nil Do not export, pretend this tree is not present.
328 t Do export the entire tree.
329 `headline' Only export the headline, but skip the tree below it.
331 This option can also be set with the OPTIONS keyword,
332 e.g. \"arch:nil\"."
333 :group 'org-export-general
334 :type '(choice
335 (const :tag "Not at all" nil)
336 (const :tag "Headline only" 'headline)
337 (const :tag "Entirely" t)))
339 (defcustom org-export-with-author t
340 "Non-nil means insert author name into the exported file.
341 This option can also be set with the OPTIONS keyword,
342 e.g. \"author:nil\"."
343 :group 'org-export-general
344 :type 'boolean)
346 (defcustom org-export-with-clocks nil
347 "Non-nil means export CLOCK keywords.
348 This option can also be set with the OPTIONS keyword,
349 e.g. \"c:t\"."
350 :group 'org-export-general
351 :type 'boolean)
353 (defcustom org-export-with-creator 'comment
354 "Non-nil means the postamble should contain a creator sentence.
356 The sentence can be set in `org-export-creator-string' and
357 defaults to \"Generated by Org mode XX in Emacs XXX.\".
359 If the value is `comment' insert it as a comment."
360 :group 'org-export-general
361 :type '(choice
362 (const :tag "No creator sentence" nil)
363 (const :tag "Sentence as a comment" 'comment)
364 (const :tag "Insert the sentence" t)))
366 (defcustom org-export-with-date t
367 "Non-nil means insert date in the exported document.
368 This option can also be set with the OPTIONS keyword,
369 e.g. \"date:nil\"."
370 :group 'org-export-general
371 :type 'boolean)
373 (defcustom org-export-date-timestamp-format nil
374 "Time-stamp format string to use for DATE keyword.
376 The format string, when specified, only applies if date consists
377 in a single time-stamp. Otherwise its value will be ignored.
379 See `format-time-string' for details on how to build this
380 string."
381 :group 'org-export-general
382 :type '(choice
383 (string :tag "Time-stamp format string")
384 (const :tag "No format string" nil)))
386 (defcustom org-export-creator-string
387 (format "Emacs %s (Org mode %s)"
388 emacs-version
389 (if (fboundp 'org-version) (org-version) "unknown version"))
390 "Information about the creator of the document.
391 This option can also be set on with the CREATOR keyword."
392 :group 'org-export-general
393 :type '(string :tag "Creator string"))
395 (defcustom org-export-with-drawers '(not "LOGBOOK")
396 "Non-nil means export contents of standard drawers.
398 When t, all drawers are exported. This may also be a list of
399 drawer names to export. If that list starts with `not', only
400 drawers with such names will be ignored.
402 This variable doesn't apply to properties drawers.
404 This option can also be set with the OPTIONS keyword,
405 e.g. \"d:nil\"."
406 :group 'org-export-general
407 :version "24.4"
408 :package-version '(Org . "8.0")
409 :type '(choice
410 (const :tag "All drawers" t)
411 (const :tag "None" nil)
412 (repeat :tag "Selected drawers"
413 (string :tag "Drawer name"))
414 (list :tag "Ignored drawers"
415 (const :format "" not)
416 (repeat :tag "Specify names of drawers to ignore during export"
417 :inline t
418 (string :tag "Drawer name")))))
420 (defcustom org-export-with-email nil
421 "Non-nil means insert author email into the exported file.
422 This option can also be set with the OPTIONS keyword,
423 e.g. \"email:t\"."
424 :group 'org-export-general
425 :type 'boolean)
427 (defcustom org-export-with-emphasize t
428 "Non-nil means interpret *word*, /word/, _word_ and +word+.
430 If the export target supports emphasizing text, the word will be
431 typeset in bold, italic, with an underline or strike-through,
432 respectively.
434 This option can also be set with the OPTIONS keyword,
435 e.g. \"*:nil\"."
436 :group 'org-export-general
437 :type 'boolean)
439 (defcustom org-export-exclude-tags '("noexport")
440 "Tags that exclude a tree from export.
442 All trees carrying any of these tags will be excluded from
443 export. This is without condition, so even subtrees inside that
444 carry one of the `org-export-select-tags' will be removed.
446 This option can also be set with the EXCLUDE_TAGS keyword."
447 :group 'org-export-general
448 :type '(repeat (string :tag "Tag")))
450 (defcustom org-export-with-fixed-width t
451 "Non-nil means lines starting with \":\" will be in fixed width font.
453 This can be used to have pre-formatted text, fragments of code
454 etc. For example:
455 : ;; Some Lisp examples
456 : (while (defc cnt)
457 : (ding))
458 will be looking just like this in also HTML. See also the QUOTE
459 keyword. Not all export backends support this.
461 This option can also be set with the OPTIONS keyword,
462 e.g. \"::nil\"."
463 :group 'org-export-general
464 :type 'boolean)
466 (defcustom org-export-with-footnotes t
467 "Non-nil means Org footnotes should be exported.
468 This option can also be set with the OPTIONS keyword,
469 e.g. \"f:nil\"."
470 :group 'org-export-general
471 :type 'boolean)
473 (defcustom org-export-with-latex t
474 "Non-nil means process LaTeX environments and fragments.
476 This option can also be set with the OPTIONS line,
477 e.g. \"tex:verbatim\". Allowed values are:
479 nil Ignore math snippets.
480 `verbatim' Keep everything in verbatim.
481 t Allow export of math snippets."
482 :group 'org-export-general
483 :version "24.4"
484 :package-version '(Org . "8.0")
485 :type '(choice
486 (const :tag "Do not process math in any way" nil)
487 (const :tag "Interpret math snippets" t)
488 (const :tag "Leave math verbatim" verbatim)))
490 (defcustom org-export-headline-levels 3
491 "The last level which is still exported as a headline.
493 Inferior levels will usually produce itemize or enumerate lists
494 when exported, but back-end behaviour may differ.
496 This option can also be set with the OPTIONS keyword,
497 e.g. \"H:2\"."
498 :group 'org-export-general
499 :type 'integer)
501 (defcustom org-export-default-language "en"
502 "The default language for export and clocktable translations, as a string.
503 This may have an association in
504 `org-clock-clocktable-language-setup'. This option can also be
505 set with the LANGUAGE keyword."
506 :group 'org-export-general
507 :type '(string :tag "Language"))
509 (defcustom org-export-preserve-breaks nil
510 "Non-nil means preserve all line breaks when exporting.
511 This option can also be set with the OPTIONS keyword,
512 e.g. \"\\n:t\"."
513 :group 'org-export-general
514 :type 'boolean)
516 (defcustom org-export-with-entities t
517 "Non-nil means interpret entities when exporting.
519 For example, HTML export converts \\alpha to &alpha; and \\AA to
520 &Aring;.
522 For a list of supported names, see the constant `org-entities'
523 and the user option `org-entities-user'.
525 This option can also be set with the OPTIONS keyword,
526 e.g. \"e:nil\"."
527 :group 'org-export-general
528 :type 'boolean)
530 (defcustom org-export-with-inlinetasks t
531 "Non-nil means inlinetasks should be exported.
532 This option can also be set with the OPTIONS keyword,
533 e.g. \"inline:nil\"."
534 :group 'org-export-general
535 :version "24.4"
536 :package-version '(Org . "8.0")
537 :type 'boolean)
539 (defcustom org-export-with-planning nil
540 "Non-nil means include planning info in export.
542 Planning info is the line containing either SCHEDULED:,
543 DEADLINE:, CLOSED: time-stamps, or a combination of them.
545 This option can also be set with the OPTIONS keyword,
546 e.g. \"p:t\"."
547 :group 'org-export-general
548 :version "24.4"
549 :package-version '(Org . "8.0")
550 :type 'boolean)
552 (defcustom org-export-with-priority nil
553 "Non-nil means include priority cookies in export.
554 This option can also be set with the OPTIONS keyword,
555 e.g. \"pri:t\"."
556 :group 'org-export-general
557 :type 'boolean)
559 (defcustom org-export-with-section-numbers t
560 "Non-nil means add section numbers to headlines when exporting.
562 When set to an integer n, numbering will only happen for
563 headlines whose relative level is higher or equal to n.
565 This option can also be set with the OPTIONS keyword,
566 e.g. \"num:t\"."
567 :group 'org-export-general
568 :type 'boolean)
570 (defcustom org-export-select-tags '("export")
571 "Tags that select a tree for export.
573 If any such tag is found in a buffer, all trees that do not carry
574 one of these tags will be ignored during export. Inside trees
575 that are selected like this, you can still deselect a subtree by
576 tagging it with one of the `org-export-exclude-tags'.
578 This option can also be set with the SELECT_TAGS keyword."
579 :group 'org-export-general
580 :type '(repeat (string :tag "Tag")))
582 (defcustom org-export-with-smart-quotes nil
583 "Non-nil means activate smart quotes during export.
584 This option can also be set with the OPTIONS keyword,
585 e.g., \"':t\".
587 When setting this to non-nil, you need to take care of
588 using the correct Babel package when exporting to LaTeX.
589 E.g., you can load Babel for french like this:
591 #+LaTeX_HEADER: \\usepackage[french]{babel}"
592 :group 'org-export-general
593 :version "24.4"
594 :package-version '(Org . "8.0")
595 :type 'boolean)
597 (defcustom org-export-with-special-strings t
598 "Non-nil means interpret \"\\-\", \"--\" and \"---\" for export.
600 When this option is turned on, these strings will be exported as:
602 Org HTML LaTeX UTF-8
603 -----+----------+--------+-------
604 \\- &shy; \\-
605 -- &ndash; -- –
606 --- &mdash; --- —
607 ... &hellip; \\ldots …
609 This option can also be set with the OPTIONS keyword,
610 e.g. \"-:nil\"."
611 :group 'org-export-general
612 :type 'boolean)
614 (defcustom org-export-with-statistics-cookies t
615 "Non-nil means include statistics cookies in export.
616 This option can also be set with the OPTIONS keyword,
617 e.g. \"stat:nil\""
618 :group 'org-export-general
619 :version "24.4"
620 :package-version '(Org . "8.0")
621 :type 'boolean)
623 (defcustom org-export-with-sub-superscripts t
624 "Non-nil means interpret \"_\" and \"^\" for export.
626 When this option is turned on, you can use TeX-like syntax for
627 sub- and superscripts. Several characters after \"_\" or \"^\"
628 will be considered as a single item - so grouping with {} is
629 normally not needed. For example, the following things will be
630 parsed as single sub- or superscripts.
632 10^24 or 10^tau several digits will be considered 1 item.
633 10^-12 or 10^-tau a leading sign with digits or a word
634 x^2-y^3 will be read as x^2 - y^3, because items are
635 terminated by almost any nonword/nondigit char.
636 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
638 Still, ambiguity is possible - so when in doubt use {} to enclose
639 the sub/superscript. If you set this variable to the symbol
640 `{}', the braces are *required* in order to trigger
641 interpretations as sub/superscript. This can be helpful in
642 documents that need \"_\" frequently in plain text.
644 This option can also be set with the OPTIONS keyword,
645 e.g. \"^:nil\"."
646 :group 'org-export-general
647 :type '(choice
648 (const :tag "Interpret them" t)
649 (const :tag "Curly brackets only" {})
650 (const :tag "Do not interpret them" nil)))
652 (defcustom org-export-with-toc t
653 "Non-nil means create a table of contents in exported files.
655 The TOC contains headlines with levels up
656 to`org-export-headline-levels'. When an integer, include levels
657 up to N in the toc, this may then be different from
658 `org-export-headline-levels', but it will not be allowed to be
659 larger than the number of headline levels. When nil, no table of
660 contents is made.
662 This option can also be set with the OPTIONS keyword,
663 e.g. \"toc:nil\" or \"toc:3\"."
664 :group 'org-export-general
665 :type '(choice
666 (const :tag "No Table of Contents" nil)
667 (const :tag "Full Table of Contents" t)
668 (integer :tag "TOC to level")))
670 (defcustom org-export-with-tables t
671 "If non-nil, lines starting with \"|\" define a table.
672 For example:
674 | Name | Address | Birthday |
675 |-------------+----------+-----------|
676 | Arthur Dent | England | 29.2.2100 |
678 This option can also be set with the OPTIONS keyword,
679 e.g. \"|:nil\"."
680 :group 'org-export-general
681 :type 'boolean)
683 (defcustom org-export-with-tags t
684 "If nil, do not export tags, just remove them from headlines.
686 If this is the symbol `not-in-toc', tags will be removed from
687 table of contents entries, but still be shown in the headlines of
688 the document.
690 This option can also be set with the OPTIONS keyword,
691 e.g. \"tags:nil\"."
692 :group 'org-export-general
693 :type '(choice
694 (const :tag "Off" nil)
695 (const :tag "Not in TOC" not-in-toc)
696 (const :tag "On" t)))
698 (defcustom org-export-with-tasks t
699 "Non-nil means include TODO items for export.
701 This may have the following values:
702 t include tasks independent of state.
703 `todo' include only tasks that are not yet done.
704 `done' include only tasks that are already done.
705 nil ignore all tasks.
706 list of keywords include tasks with these keywords.
708 This option can also be set with the OPTIONS keyword,
709 e.g. \"tasks:nil\"."
710 :group 'org-export-general
711 :type '(choice
712 (const :tag "All tasks" t)
713 (const :tag "No tasks" nil)
714 (const :tag "Not-done tasks" todo)
715 (const :tag "Only done tasks" done)
716 (repeat :tag "Specific TODO keywords"
717 (string :tag "Keyword"))))
719 (defcustom org-export-time-stamp-file t
720 "Non-nil means insert a time stamp into the exported file.
721 The time stamp shows when the file was created. This option can
722 also be set with the OPTIONS keyword, e.g. \"timestamp:nil\"."
723 :group 'org-export-general
724 :type 'boolean)
726 (defcustom org-export-with-timestamps t
727 "Non nil means allow timestamps in export.
729 It can be set to `active', `inactive', t or nil, in order to
730 export, respectively, only active timestamps, only inactive ones,
731 all of them or none.
733 This option can also be set with the OPTIONS keyword, e.g.
734 \"<:nil\"."
735 :group 'org-export-general
736 :type '(choice
737 (const :tag "All timestamps" t)
738 (const :tag "Only active timestamps" active)
739 (const :tag "Only inactive timestamps" inactive)
740 (const :tag "No timestamp" nil)))
742 (defcustom org-export-with-todo-keywords t
743 "Non-nil means include TODO keywords in export.
744 When nil, remove all these keywords from the export. This option
745 can also be set with the OPTIONS keyword, e.g. \"todo:nil\"."
746 :group 'org-export-general
747 :type 'boolean)
749 (defcustom org-export-allow-bind-keywords nil
750 "Non-nil means BIND keywords can define local variable values.
751 This is a potential security risk, which is why the default value
752 is nil. You can also allow them through local buffer variables."
753 :group 'org-export-general
754 :version "24.4"
755 :package-version '(Org . "8.0")
756 :type 'boolean)
758 (defcustom org-export-snippet-translation-alist nil
759 "Alist between export snippets back-ends and exporter back-ends.
761 This variable allows to provide shortcuts for export snippets.
763 For example, with a value of '\(\(\"h\" . \"html\"\)\), the
764 HTML back-end will recognize the contents of \"@@h:<b>@@\" as
765 HTML code while every other back-end will ignore it."
766 :group 'org-export-general
767 :version "24.4"
768 :package-version '(Org . "8.0")
769 :type '(repeat
770 (cons (string :tag "Shortcut")
771 (string :tag "Back-end"))))
773 (defcustom org-export-coding-system nil
774 "Coding system for the exported file."
775 :group 'org-export-general
776 :version "24.4"
777 :package-version '(Org . "8.0")
778 :type 'coding-system)
780 (defcustom org-export-copy-to-kill-ring 'if-interactive
781 "Should we push exported content to the kill ring?"
782 :group 'org-export-general
783 :version "24.3"
784 :type '(choice
785 (const :tag "Always" t)
786 (const :tag "When export is done interactively" if-interactive)
787 (const :tag "Never" nil)))
789 (defcustom org-export-initial-scope 'buffer
790 "The initial scope when exporting with `org-export-dispatch'.
791 This variable can be either set to `buffer' or `subtree'."
792 :group 'org-export-general
793 :type '(choice
794 (const :tag "Export current buffer" 'buffer)
795 (const :tag "Export current subtree" 'subtree)))
797 (defcustom org-export-show-temporary-export-buffer t
798 "Non-nil means show buffer after exporting to temp buffer.
799 When Org exports to a file, the buffer visiting that file is ever
800 shown, but remains buried. However, when exporting to
801 a temporary buffer, that buffer is popped up in a second window.
802 When this variable is nil, the buffer remains buried also in
803 these cases."
804 :group 'org-export-general
805 :type 'boolean)
807 (defcustom org-export-in-background nil
808 "Non-nil means export and publishing commands will run in background.
809 Results from an asynchronous export are never displayed
810 automatically. But you can retrieve them with \\[org-export-stack]."
811 :group 'org-export-general
812 :version "24.4"
813 :package-version '(Org . "8.0")
814 :type 'boolean)
816 (defcustom org-export-async-init-file user-init-file
817 "File used to initialize external export process.
818 Value must be an absolute file name. It defaults to user's
819 initialization file. Though, a specific configuration makes the
820 process faster and the export more portable."
821 :group 'org-export-general
822 :version "24.4"
823 :package-version '(Org . "8.0")
824 :type '(file :must-match t))
826 (defcustom org-export-invisible-backends nil
827 "List of back-ends that shouldn't appear in the dispatcher.
829 Any back-end belonging to this list or derived from a back-end
830 belonging to it will not appear in the dispatcher menu.
832 Indeed, Org may require some export back-ends without notice. If
833 these modules are never to be used interactively, adding them
834 here will avoid cluttering the dispatcher menu."
835 :group 'org-export-general
836 :version "24.4"
837 :package-version '(Org . "8.0")
838 :type '(repeat (symbol :tag "Back-End")))
840 (defcustom org-export-dispatch-use-expert-ui nil
841 "Non-nil means using a non-intrusive `org-export-dispatch'.
842 In that case, no help buffer is displayed. Though, an indicator
843 for current export scope is added to the prompt (\"b\" when
844 output is restricted to body only, \"s\" when it is restricted to
845 the current subtree, \"v\" when only visible elements are
846 considered for export, \"f\" when publishing functions should be
847 passed the FORCE argument and \"a\" when the export should be
848 asynchronous). Also, \[?] allows to switch back to standard
849 mode."
850 :group 'org-export-general
851 :version "24.4"
852 :package-version '(Org . "8.0")
853 :type 'boolean)
857 ;;; Defining Back-ends
859 ;; `org-export-define-backend' is the standard way to define an export
860 ;; back-end. It allows to specify translators, filters, buffer
861 ;; options and a menu entry. If the new back-end shares translators
862 ;; with another back-end, `org-export-define-derived-backend' may be
863 ;; used instead.
865 ;; Internally, a back-end is stored as a list, of which CAR is the
866 ;; name of the back-end, as a symbol, and CDR a plist. Accessors to
867 ;; properties of a given back-end are: `org-export-backend-filters',
868 ;; `org-export-backend-menu', `org-export-backend-options' and
869 ;; `org-export-backend-translate-table'.
871 ;; Eventually `org-export-barf-if-invalid-backend' returns an error
872 ;; when a given back-end hasn't been registered yet.
874 (defun org-export-define-backend (backend translators &rest body)
875 "Define a new back-end BACKEND.
877 TRANSLATORS is an alist between object or element types and
878 functions handling them.
880 These functions should return a string without any trailing
881 space, or nil. They must accept three arguments: the object or
882 element itself, its contents or nil when it isn't recursive and
883 the property list used as a communication channel.
885 Contents, when not nil, are stripped from any global indentation
886 \(although the relative one is preserved). They also always end
887 with a single newline character.
889 If, for a given type, no function is found, that element or
890 object type will simply be ignored, along with any blank line or
891 white space at its end. The same will happen if the function
892 returns the nil value. If that function returns the empty
893 string, the type will be ignored, but the blank lines or white
894 spaces will be kept.
896 In addition to element and object types, one function can be
897 associated to the `template' (or `inner-template') symbol and
898 another one to the `plain-text' symbol.
900 The former returns the final transcoded string, and can be used
901 to add a preamble and a postamble to document's body. It must
902 accept two arguments: the transcoded string and the property list
903 containing export options. A function associated to `template'
904 will not be applied if export has option \"body-only\".
905 A function associated to `inner-template' is always applied.
907 The latter, when defined, is to be called on every text not
908 recognized as an element or an object. It must accept two
909 arguments: the text string and the information channel. It is an
910 appropriate place to protect special chars relative to the
911 back-end.
913 BODY can start with pre-defined keyword arguments. The following
914 keywords are understood:
916 :export-block
918 String, or list of strings, representing block names that
919 will not be parsed. This is used to specify blocks that will
920 contain raw code specific to the back-end. These blocks
921 still have to be handled by the relative `export-block' type
922 translator.
924 :filters-alist
926 Alist between filters and function, or list of functions,
927 specific to the back-end. See `org-export-filters-alist' for
928 a list of all allowed filters. Filters defined here
929 shouldn't make a back-end test, as it may prevent back-ends
930 derived from this one to behave properly.
932 :menu-entry
934 Menu entry for the export dispatcher. It should be a list
935 like:
937 '(KEY DESCRIPTION-OR-ORDINAL ACTION-OR-MENU)
939 where :
941 KEY is a free character selecting the back-end.
943 DESCRIPTION-OR-ORDINAL is either a string or a number.
945 If it is a string, is will be used to name the back-end in
946 its menu entry. If it is a number, the following menu will
947 be displayed as a sub-menu of the back-end with the same
948 KEY. Also, the number will be used to determine in which
949 order such sub-menus will appear (lowest first).
951 ACTION-OR-MENU is either a function or an alist.
953 If it is an action, it will be called with four
954 arguments (booleans): ASYNC, SUBTREEP, VISIBLE-ONLY and
955 BODY-ONLY. See `org-export-as' for further explanations on
956 some of them.
958 If it is an alist, associations should follow the
959 pattern:
961 '(KEY DESCRIPTION ACTION)
963 where KEY, DESCRIPTION and ACTION are described above.
965 Valid values include:
967 '(?m \"My Special Back-end\" my-special-export-function)
971 '(?l \"Export to LaTeX\"
972 \(?p \"As PDF file\" org-latex-export-to-pdf)
973 \(?o \"As PDF file and open\"
974 \(lambda (a s v b)
975 \(if a (org-latex-export-to-pdf t s v b)
976 \(org-open-file
977 \(org-latex-export-to-pdf nil s v b)))))))
979 or the following, which will be added to the previous
980 sub-menu,
982 '(?l 1
983 \((?B \"As TEX buffer (Beamer)\" org-beamer-export-as-latex)
984 \(?P \"As PDF file (Beamer)\" org-beamer-export-to-pdf)))
986 :options-alist
988 Alist between back-end specific properties introduced in
989 communication channel and how their value are acquired. See
990 `org-export-options-alist' for more information about
991 structure of the values."
992 (declare (indent 1))
993 (let (export-block filters menu-entry options contents)
994 (while (keywordp (car body))
995 (case (pop body)
996 (:export-block (let ((names (pop body)))
997 (setq export-block
998 (if (consp names) (mapcar 'upcase names)
999 (list (upcase names))))))
1000 (:filters-alist (setq filters (pop body)))
1001 (:menu-entry (setq menu-entry (pop body)))
1002 (:options-alist (setq options (pop body)))
1003 (t (pop body))))
1004 (setq contents (append (list :translate-alist translators)
1005 (and filters (list :filters-alist filters))
1006 (and options (list :options-alist options))
1007 (and menu-entry (list :menu-entry menu-entry))))
1008 ;; Register back-end.
1009 (let ((registeredp (assq backend org-export-registered-backends)))
1010 (if registeredp (setcdr registeredp contents)
1011 (push (cons backend contents) org-export-registered-backends)))
1012 ;; Tell parser to not parse EXPORT-BLOCK blocks.
1013 (when export-block
1014 (mapc
1015 (lambda (name)
1016 (add-to-list 'org-element-block-name-alist
1017 `(,name . org-element-export-block-parser)))
1018 export-block))))
1020 (defun org-export-define-derived-backend (child parent &rest body)
1021 "Create a new back-end as a variant of an existing one.
1023 CHILD is the name of the derived back-end. PARENT is the name of
1024 the parent back-end.
1026 BODY can start with pre-defined keyword arguments. The following
1027 keywords are understood:
1029 :export-block
1031 String, or list of strings, representing block names that
1032 will not be parsed. This is used to specify blocks that will
1033 contain raw code specific to the back-end. These blocks
1034 still have to be handled by the relative `export-block' type
1035 translator.
1037 :filters-alist
1039 Alist of filters that will overwrite or complete filters
1040 defined in PARENT back-end. See `org-export-filters-alist'
1041 for a list of allowed filters.
1043 :menu-entry
1045 Menu entry for the export dispatcher. See
1046 `org-export-define-backend' for more information about the
1047 expected value.
1049 :options-alist
1051 Alist of back-end specific properties that will overwrite or
1052 complete those defined in PARENT back-end. Refer to
1053 `org-export-options-alist' for more information about
1054 structure of the values.
1056 :translate-alist
1058 Alist of element and object types and transcoders that will
1059 overwrite or complete transcode table from PARENT back-end.
1060 Refer to `org-export-define-backend' for detailed information
1061 about transcoders.
1063 As an example, here is how one could define \"my-latex\" back-end
1064 as a variant of `latex' back-end with a custom template function:
1066 \(org-export-define-derived-backend 'my-latex 'latex
1067 :translate-alist '((template . my-latex-template-fun)))
1069 The back-end could then be called with, for example:
1071 \(org-export-to-buffer 'my-latex \"*Test my-latex*\")"
1072 (declare (indent 2))
1073 (let (export-block filters menu-entry options translators contents)
1074 (while (keywordp (car body))
1075 (case (pop body)
1076 (:export-block (let ((names (pop body)))
1077 (setq export-block
1078 (if (consp names) (mapcar 'upcase names)
1079 (list (upcase names))))))
1080 (:filters-alist (setq filters (pop body)))
1081 (:menu-entry (setq menu-entry (pop body)))
1082 (:options-alist (setq options (pop body)))
1083 (:translate-alist (setq translators (pop body)))
1084 (t (pop body))))
1085 (setq contents (append
1086 (list :parent parent)
1087 (let ((p-table (org-export-backend-translate-table parent)))
1088 (list :translate-alist (append translators p-table)))
1089 (let ((p-filters (org-export-backend-filters parent)))
1090 (list :filters-alist (append filters p-filters)))
1091 (let ((p-options (org-export-backend-options parent)))
1092 (list :options-alist (append options p-options)))
1093 (and menu-entry (list :menu-entry menu-entry))))
1094 (org-export-barf-if-invalid-backend parent)
1095 ;; Register back-end.
1096 (let ((registeredp (assq child org-export-registered-backends)))
1097 (if registeredp (setcdr registeredp contents)
1098 (push (cons child contents) org-export-registered-backends)))
1099 ;; Tell parser to not parse EXPORT-BLOCK blocks.
1100 (when export-block
1101 (mapc
1102 (lambda (name)
1103 (add-to-list 'org-element-block-name-alist
1104 `(,name . org-element-export-block-parser)))
1105 export-block))))
1107 (defun org-export-backend-parent (backend)
1108 "Return back-end from which BACKEND is derived, or nil."
1109 (plist-get (cdr (assq backend org-export-registered-backends)) :parent))
1111 (defun org-export-backend-filters (backend)
1112 "Return filters for BACKEND."
1113 (plist-get (cdr (assq backend org-export-registered-backends))
1114 :filters-alist))
1116 (defun org-export-backend-menu (backend)
1117 "Return menu entry for BACKEND."
1118 (plist-get (cdr (assq backend org-export-registered-backends))
1119 :menu-entry))
1121 (defun org-export-backend-options (backend)
1122 "Return export options for BACKEND."
1123 (plist-get (cdr (assq backend org-export-registered-backends))
1124 :options-alist))
1126 (defun org-export-backend-translate-table (backend)
1127 "Return translate table for BACKEND."
1128 (plist-get (cdr (assq backend org-export-registered-backends))
1129 :translate-alist))
1131 (defun org-export-barf-if-invalid-backend (backend)
1132 "Signal an error if BACKEND isn't defined."
1133 (unless (org-export-backend-translate-table backend)
1134 (error "Unknown \"%s\" back-end: Aborting export" backend)))
1136 (defun org-export-derived-backend-p (backend &rest backends)
1137 "Non-nil if BACKEND is derived from one of BACKENDS."
1138 (let ((parent backend))
1139 (while (and (not (memq parent backends))
1140 (setq parent (org-export-backend-parent parent))))
1141 parent))
1145 ;;; The Communication Channel
1147 ;; During export process, every function has access to a number of
1148 ;; properties. They are of two types:
1150 ;; 1. Environment options are collected once at the very beginning of
1151 ;; the process, out of the original buffer and configuration.
1152 ;; Collecting them is handled by `org-export-get-environment'
1153 ;; function.
1155 ;; Most environment options are defined through the
1156 ;; `org-export-options-alist' variable.
1158 ;; 2. Tree properties are extracted directly from the parsed tree,
1159 ;; just before export, by `org-export-collect-tree-properties'.
1161 ;; Here is the full list of properties available during transcode
1162 ;; process, with their category and their value type.
1164 ;; + `:author' :: Author's name.
1165 ;; - category :: option
1166 ;; - type :: string
1168 ;; + `:back-end' :: Current back-end used for transcoding.
1169 ;; - category :: tree
1170 ;; - type :: symbol
1172 ;; + `:creator' :: String to write as creation information.
1173 ;; - category :: option
1174 ;; - type :: string
1176 ;; + `:date' :: String to use as date.
1177 ;; - category :: option
1178 ;; - type :: string
1180 ;; + `:description' :: Description text for the current data.
1181 ;; - category :: option
1182 ;; - type :: string
1184 ;; + `:email' :: Author's email.
1185 ;; - category :: option
1186 ;; - type :: string
1188 ;; + `:exclude-tags' :: Tags for exclusion of subtrees from export
1189 ;; process.
1190 ;; - category :: option
1191 ;; - type :: list of strings
1193 ;; + `:export-options' :: List of export options available for current
1194 ;; process.
1195 ;; - category :: none
1196 ;; - type :: list of symbols, among `subtree', `body-only' and
1197 ;; `visible-only'.
1199 ;; + `:exported-data' :: Hash table used for memoizing
1200 ;; `org-export-data'.
1201 ;; - category :: tree
1202 ;; - type :: hash table
1204 ;; + `:filetags' :: List of global tags for buffer. Used by
1205 ;; `org-export-get-tags' to get tags with inheritance.
1206 ;; - category :: option
1207 ;; - type :: list of strings
1209 ;; + `:footnote-definition-alist' :: Alist between footnote labels and
1210 ;; their definition, as parsed data. Only non-inlined footnotes
1211 ;; are represented in this alist. Also, every definition isn't
1212 ;; guaranteed to be referenced in the parse tree. The purpose of
1213 ;; this property is to preserve definitions from oblivion
1214 ;; (i.e. when the parse tree comes from a part of the original
1215 ;; buffer), it isn't meant for direct use in a back-end. To
1216 ;; retrieve a definition relative to a reference, use
1217 ;; `org-export-get-footnote-definition' instead.
1218 ;; - category :: option
1219 ;; - type :: alist (STRING . LIST)
1221 ;; + `:headline-levels' :: Maximum level being exported as an
1222 ;; headline. Comparison is done with the relative level of
1223 ;; headlines in the parse tree, not necessarily with their
1224 ;; actual level.
1225 ;; - category :: option
1226 ;; - type :: integer
1228 ;; + `:headline-offset' :: Difference between relative and real level
1229 ;; of headlines in the parse tree. For example, a value of -1
1230 ;; means a level 2 headline should be considered as level
1231 ;; 1 (cf. `org-export-get-relative-level').
1232 ;; - category :: tree
1233 ;; - type :: integer
1235 ;; + `:headline-numbering' :: Alist between headlines and their
1236 ;; numbering, as a list of numbers
1237 ;; (cf. `org-export-get-headline-number').
1238 ;; - category :: tree
1239 ;; - type :: alist (INTEGER . LIST)
1241 ;; + `:id-alist' :: Alist between ID strings and destination file's
1242 ;; path, relative to current directory. It is used by
1243 ;; `org-export-resolve-id-link' to resolve ID links targeting an
1244 ;; external file.
1245 ;; - category :: option
1246 ;; - type :: alist (STRING . STRING)
1248 ;; + `:ignore-list' :: List of elements and objects that should be
1249 ;; ignored during export.
1250 ;; - category :: tree
1251 ;; - type :: list of elements and objects
1253 ;; + `:input-file' :: Full path to input file, if any.
1254 ;; - category :: option
1255 ;; - type :: string or nil
1257 ;; + `:keywords' :: List of keywords attached to data.
1258 ;; - category :: option
1259 ;; - type :: string
1261 ;; + `:language' :: Default language used for translations.
1262 ;; - category :: option
1263 ;; - type :: string
1265 ;; + `:parse-tree' :: Whole parse tree, available at any time during
1266 ;; transcoding.
1267 ;; - category :: option
1268 ;; - type :: list (as returned by `org-element-parse-buffer')
1270 ;; + `:preserve-breaks' :: Non-nil means transcoding should preserve
1271 ;; all line breaks.
1272 ;; - category :: option
1273 ;; - type :: symbol (nil, t)
1275 ;; + `:section-numbers' :: Non-nil means transcoding should add
1276 ;; section numbers to headlines.
1277 ;; - category :: option
1278 ;; - type :: symbol (nil, t)
1280 ;; + `:select-tags' :: List of tags enforcing inclusion of sub-trees
1281 ;; in transcoding. When such a tag is present, subtrees without
1282 ;; it are de facto excluded from the process. See
1283 ;; `use-select-tags'.
1284 ;; - category :: option
1285 ;; - type :: list of strings
1287 ;; + `:time-stamp-file' :: Non-nil means transcoding should insert
1288 ;; a time stamp in the output.
1289 ;; - category :: option
1290 ;; - type :: symbol (nil, t)
1292 ;; + `:translate-alist' :: Alist between element and object types and
1293 ;; transcoding functions relative to the current back-end.
1294 ;; Special keys `inner-template', `template' and `plain-text' are
1295 ;; also possible.
1296 ;; - category :: option
1297 ;; - type :: alist (SYMBOL . FUNCTION)
1299 ;; + `:with-archived-trees' :: Non-nil when archived subtrees should
1300 ;; also be transcoded. If it is set to the `headline' symbol,
1301 ;; only the archived headline's name is retained.
1302 ;; - category :: option
1303 ;; - type :: symbol (nil, t, `headline')
1305 ;; + `:with-author' :: Non-nil means author's name should be included
1306 ;; in the output.
1307 ;; - category :: option
1308 ;; - type :: symbol (nil, t)
1310 ;; + `:with-clocks' :: Non-nil means clock keywords should be exported.
1311 ;; - category :: option
1312 ;; - type :: symbol (nil, t)
1314 ;; + `:with-creator' :: Non-nil means a creation sentence should be
1315 ;; inserted at the end of the transcoded string. If the value
1316 ;; is `comment', it should be commented.
1317 ;; - category :: option
1318 ;; - type :: symbol (`comment', nil, t)
1320 ;; + `:with-date' :: Non-nil means output should contain a date.
1321 ;; - category :: option
1322 ;; - type :. symbol (nil, t)
1324 ;; + `:with-drawers' :: Non-nil means drawers should be exported. If
1325 ;; its value is a list of names, only drawers with such names
1326 ;; will be transcoded. If that list starts with `not', drawer
1327 ;; with these names will be skipped.
1328 ;; - category :: option
1329 ;; - type :: symbol (nil, t) or list of strings
1331 ;; + `:with-email' :: Non-nil means output should contain author's
1332 ;; email.
1333 ;; - category :: option
1334 ;; - type :: symbol (nil, t)
1336 ;; + `:with-emphasize' :: Non-nil means emphasized text should be
1337 ;; interpreted.
1338 ;; - category :: option
1339 ;; - type :: symbol (nil, t)
1341 ;; + `:with-fixed-width' :: Non-nil if transcoder should interpret
1342 ;; strings starting with a colon as a fixed-with (verbatim) area.
1343 ;; - category :: option
1344 ;; - type :: symbol (nil, t)
1346 ;; + `:with-footnotes' :: Non-nil if transcoder should interpret
1347 ;; footnotes.
1348 ;; - category :: option
1349 ;; - type :: symbol (nil, t)
1351 ;; + `:with-latex' :: Non-nil means `latex-environment' elements and
1352 ;; `latex-fragment' objects should appear in export output. When
1353 ;; this property is set to `verbatim', they will be left as-is.
1354 ;; - category :: option
1355 ;; - type :: symbol (`verbatim', nil, t)
1357 ;; + `:with-planning' :: Non-nil means transcoding should include
1358 ;; planning info.
1359 ;; - category :: option
1360 ;; - type :: symbol (nil, t)
1362 ;; + `:with-priority' :: Non-nil means transcoding should include
1363 ;; priority cookies.
1364 ;; - category :: option
1365 ;; - type :: symbol (nil, t)
1367 ;; + `:with-smart-quotes' :: Non-nil means activate smart quotes in
1368 ;; plain text.
1369 ;; - category :: option
1370 ;; - type :: symbol (nil, t)
1372 ;; + `:with-special-strings' :: Non-nil means transcoding should
1373 ;; interpret special strings in plain text.
1374 ;; - category :: option
1375 ;; - type :: symbol (nil, t)
1377 ;; + `:with-sub-superscript' :: Non-nil means transcoding should
1378 ;; interpret subscript and superscript. With a value of "{}",
1379 ;; only interpret those using curly brackets.
1380 ;; - category :: option
1381 ;; - type :: symbol (nil, {}, t)
1383 ;; + `:with-tables' :: Non-nil means transcoding should interpret
1384 ;; tables.
1385 ;; - category :: option
1386 ;; - type :: symbol (nil, t)
1388 ;; + `:with-tags' :: Non-nil means transcoding should keep tags in
1389 ;; headlines. A `not-in-toc' value will remove them from the
1390 ;; table of contents, if any, nonetheless.
1391 ;; - category :: option
1392 ;; - type :: symbol (nil, t, `not-in-toc')
1394 ;; + `:with-tasks' :: Non-nil means transcoding should include
1395 ;; headlines with a TODO keyword. A `todo' value will only
1396 ;; include headlines with a todo type keyword while a `done'
1397 ;; value will do the contrary. If a list of strings is provided,
1398 ;; only tasks with keywords belonging to that list will be kept.
1399 ;; - category :: option
1400 ;; - type :: symbol (t, todo, done, nil) or list of strings
1402 ;; + `:with-timestamps' :: Non-nil means transcoding should include
1403 ;; time stamps. Special value `active' (resp. `inactive') ask to
1404 ;; export only active (resp. inactive) timestamps. Otherwise,
1405 ;; completely remove them.
1406 ;; - category :: option
1407 ;; - type :: symbol: (`active', `inactive', t, nil)
1409 ;; + `:with-toc' :: Non-nil means that a table of contents has to be
1410 ;; added to the output. An integer value limits its depth.
1411 ;; - category :: option
1412 ;; - type :: symbol (nil, t or integer)
1414 ;; + `:with-todo-keywords' :: Non-nil means transcoding should
1415 ;; include TODO keywords.
1416 ;; - category :: option
1417 ;; - type :: symbol (nil, t)
1420 ;;;; Environment Options
1422 ;; Environment options encompass all parameters defined outside the
1423 ;; scope of the parsed data. They come from five sources, in
1424 ;; increasing precedence order:
1426 ;; - Global variables,
1427 ;; - Buffer's attributes,
1428 ;; - Options keyword symbols,
1429 ;; - Buffer keywords,
1430 ;; - Subtree properties.
1432 ;; The central internal function with regards to environment options
1433 ;; is `org-export-get-environment'. It updates global variables with
1434 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
1435 ;; the different sources.
1437 ;; The internal functions doing the retrieval are:
1438 ;; `org-export--get-global-options',
1439 ;; `org-export--get-buffer-attributes',
1440 ;; `org-export--parse-option-keyword',
1441 ;; `org-export--get-subtree-options' and
1442 ;; `org-export--get-inbuffer-options'
1444 ;; Also, `org-export--install-letbind-maybe' takes care of the part
1445 ;; relative to "#+BIND:" keywords.
1447 (defun org-export-get-environment (&optional backend subtreep ext-plist)
1448 "Collect export options from the current buffer.
1450 Optional argument BACKEND is a symbol specifying which back-end
1451 specific options to read, if any.
1453 When optional argument SUBTREEP is non-nil, assume the export is
1454 done against the current sub-tree.
1456 Third optional argument EXT-PLIST is a property list with
1457 external parameters overriding Org default settings, but still
1458 inferior to file-local settings."
1459 ;; First install #+BIND variables since these must be set before
1460 ;; global options are read.
1461 (dolist (pair (org-export--list-bound-variables))
1462 (org-set-local (car pair) (nth 1 pair)))
1463 ;; Get and prioritize export options...
1464 (org-combine-plists
1465 ;; ... from global variables...
1466 (org-export--get-global-options backend)
1467 ;; ... from an external property list...
1468 ext-plist
1469 ;; ... from in-buffer settings...
1470 (org-export--get-inbuffer-options backend)
1471 ;; ... and from subtree, when appropriate.
1472 (and subtreep (org-export--get-subtree-options backend))
1473 ;; Eventually add misc. properties.
1474 (list
1475 :back-end
1476 backend
1477 :translate-alist
1478 (org-export-backend-translate-table backend)
1479 :footnote-definition-alist
1480 ;; Footnotes definitions must be collected in the original
1481 ;; buffer, as there's no insurance that they will still be in
1482 ;; the parse tree, due to possible narrowing.
1483 (let (alist)
1484 (org-with-wide-buffer
1485 (goto-char (point-min))
1486 (while (re-search-forward org-footnote-definition-re nil t)
1487 (let ((def (save-match-data (org-element-at-point))))
1488 (when (eq (org-element-type def) 'footnote-definition)
1489 (push
1490 (cons (org-element-property :label def)
1491 (let ((cbeg (org-element-property :contents-begin def)))
1492 (when cbeg
1493 (org-element--parse-elements
1494 cbeg (org-element-property :contents-end def)
1495 nil nil nil nil (list 'org-data nil)))))
1496 alist))))
1497 alist))
1498 :id-alist
1499 ;; Collect id references.
1500 (let (alist)
1501 (org-with-wide-buffer
1502 (goto-char (point-min))
1503 (while (re-search-forward "\\[\\[id:\\S-+?\\]" nil t)
1504 (let ((link (org-element-context)))
1505 (when (eq (org-element-type link) 'link)
1506 (let* ((id (org-element-property :path link))
1507 (file (org-id-find-id-file id)))
1508 (when file
1509 (push (cons id (file-relative-name file)) alist)))))))
1510 alist))))
1512 (defun org-export--parse-option-keyword (options &optional backend)
1513 "Parse an OPTIONS line and return values as a plist.
1514 Optional argument BACKEND is a symbol specifying which back-end
1515 specific items to read, if any."
1516 (let* ((all
1517 ;; Priority is given to back-end specific options.
1518 (append (and backend (org-export-backend-options backend))
1519 org-export-options-alist))
1520 plist)
1521 (dolist (option all)
1522 (let ((property (car option))
1523 (item (nth 2 option)))
1524 (when (and item
1525 (not (plist-member plist property))
1526 (string-match (concat "\\(\\`\\|[ \t]\\)"
1527 (regexp-quote item)
1528 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
1529 options))
1530 (setq plist (plist-put plist
1531 property
1532 (car (read-from-string
1533 (match-string 2 options))))))))
1534 plist))
1536 (defun org-export--get-subtree-options (&optional backend)
1537 "Get export options in subtree at point.
1538 Optional argument BACKEND is a symbol specifying back-end used
1539 for export. Return options as a plist."
1540 ;; For each buffer keyword, create a headline property setting the
1541 ;; same property in communication channel. The name for the property
1542 ;; is the keyword with "EXPORT_" appended to it.
1543 (org-with-wide-buffer
1544 (let (prop plist)
1545 ;; Make sure point is at a heading.
1546 (if (org-at-heading-p) (org-up-heading-safe) (org-back-to-heading t))
1547 ;; Take care of EXPORT_TITLE. If it isn't defined, use headline's
1548 ;; title as its fallback value.
1549 (when (setq prop (or (org-entry-get (point) "EXPORT_TITLE")
1550 (progn (looking-at org-todo-line-regexp)
1551 (org-match-string-no-properties 3))))
1552 (setq plist
1553 (plist-put
1554 plist :title
1555 (org-element-parse-secondary-string
1556 prop (org-element-restriction 'keyword)))))
1557 ;; EXPORT_OPTIONS are parsed in a non-standard way.
1558 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
1559 (setq plist
1560 (nconc plist (org-export--parse-option-keyword prop backend))))
1561 ;; Handle other keywords. TITLE keyword is excluded as it has
1562 ;; been handled already.
1563 (let ((seen '("TITLE")))
1564 (mapc
1565 (lambda (option)
1566 (let ((property (car option))
1567 (keyword (nth 1 option)))
1568 (when (and keyword (not (member keyword seen)))
1569 (let* ((subtree-prop (concat "EXPORT_" keyword))
1570 ;; Export properties are not case-sensitive.
1571 (value (let ((case-fold-search t))
1572 (org-entry-get (point) subtree-prop))))
1573 (push keyword seen)
1574 (when (and value (not (plist-member plist property)))
1575 (setq plist
1576 (plist-put
1577 plist
1578 property
1579 (cond
1580 ;; Parse VALUE if required.
1581 ((member keyword org-element-document-properties)
1582 (org-element-parse-secondary-string
1583 value (org-element-restriction 'keyword)))
1584 ;; If BEHAVIOUR is `split' expected value is
1585 ;; a list of strings, not a string.
1586 ((eq (nth 4 option) 'split) (org-split-string value))
1587 (t value)))))))))
1588 ;; Look for both general keywords and back-end specific
1589 ;; options, with priority given to the latter.
1590 (append (and backend (org-export-backend-options backend))
1591 org-export-options-alist)))
1592 ;; Return value.
1593 plist)))
1595 (defun org-export--get-inbuffer-options (&optional backend)
1596 "Return current buffer export options, as a plist.
1598 Optional argument BACKEND, when non-nil, is a symbol specifying
1599 which back-end specific options should also be read in the
1600 process.
1602 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1603 (let* (plist
1604 get-options ; For byte-compiler.
1605 (case-fold-search t)
1606 (options (append
1607 ;; Priority is given to back-end specific options.
1608 (and backend (org-export-backend-options backend))
1609 org-export-options-alist))
1610 (regexp (format "^[ \t]*#\\+%s:"
1611 (regexp-opt (nconc (delq nil (mapcar 'cadr options))
1612 org-export-special-keywords))))
1613 (find-opt
1614 (lambda (keyword)
1615 ;; Return property name associated to KEYWORD.
1616 (catch 'exit
1617 (mapc (lambda (option)
1618 (when (equal (nth 1 option) keyword)
1619 (throw 'exit (car option))))
1620 options))))
1621 (get-options
1622 (lambda (&optional files plist)
1623 ;; Recursively read keywords in buffer. FILES is a list
1624 ;; of files read so far. PLIST is the current property
1625 ;; list obtained.
1626 (org-with-wide-buffer
1627 (goto-char (point-min))
1628 (while (re-search-forward regexp nil t)
1629 (let ((element (org-element-at-point)))
1630 (when (eq (org-element-type element) 'keyword)
1631 (let ((key (org-element-property :key element))
1632 (val (org-element-property :value element)))
1633 (cond
1634 ;; Options in `org-export-special-keywords'.
1635 ((equal key "SETUPFILE")
1636 (let ((file (expand-file-name
1637 (org-remove-double-quotes (org-trim val)))))
1638 ;; Avoid circular dependencies.
1639 (unless (member file files)
1640 (with-temp-buffer
1641 (insert (org-file-contents file 'noerror))
1642 (let ((org-inhibit-startup t)) (org-mode))
1643 (setq plist (funcall get-options
1644 (cons file files) plist))))))
1645 ((equal key "OPTIONS")
1646 (setq plist
1647 (org-combine-plists
1648 plist
1649 (org-export--parse-option-keyword val backend))))
1650 ((equal key "FILETAGS")
1651 (setq plist
1652 (org-combine-plists
1653 plist
1654 (list :filetags
1655 (org-uniquify
1656 (append (org-split-string val ":")
1657 (plist-get plist :filetags)))))))
1659 ;; Options in `org-export-options-alist'.
1660 (let* ((prop (funcall find-opt key))
1661 (behaviour (nth 4 (assq prop options))))
1662 (setq plist
1663 (plist-put
1664 plist prop
1665 ;; Handle value depending on specified
1666 ;; BEHAVIOUR.
1667 (case behaviour
1668 (space
1669 (if (not (plist-get plist prop))
1670 (org-trim val)
1671 (concat (plist-get plist prop)
1673 (org-trim val))))
1674 (newline
1675 (org-trim (concat (plist-get plist prop)
1676 "\n"
1677 (org-trim val))))
1678 (split `(,@(plist-get plist prop)
1679 ,@(org-split-string val)))
1680 ('t val)
1681 (otherwise
1682 (if (not (plist-member plist prop)) val
1683 (plist-get plist prop)))))))))))))
1684 ;; Return final value.
1685 plist))))
1686 ;; Read options in the current buffer.
1687 (setq plist (funcall get-options buffer-file-name nil))
1688 ;; Parse keywords specified in `org-element-document-properties'.
1689 (mapc (lambda (keyword)
1690 ;; Find the property associated to the keyword.
1691 (let* ((prop (funcall find-opt keyword))
1692 (value (and prop (plist-get plist prop))))
1693 (when (stringp value)
1694 (setq plist
1695 (plist-put plist prop
1696 (org-element-parse-secondary-string
1697 value (org-element-restriction 'keyword)))))))
1698 org-element-document-properties)
1699 ;; Return value.
1700 plist))
1702 (defun org-export--get-buffer-attributes ()
1703 "Return properties related to buffer attributes, as a plist."
1704 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
1705 (list
1706 ;; Store full path of input file name, or nil. For internal use.
1707 :input-file visited-file
1708 :title (or (and visited-file
1709 (file-name-sans-extension
1710 (file-name-nondirectory visited-file)))
1711 (buffer-name (buffer-base-buffer))))))
1713 (defun org-export--get-global-options (&optional backend)
1714 "Return global export options as a plist.
1716 Optional argument BACKEND, if non-nil, is a symbol specifying
1717 which back-end specific export options should also be read in the
1718 process."
1719 (let ((all
1720 ;; Priority is given to back-end specific options.
1721 (append (and backend (org-export-backend-options backend))
1722 org-export-options-alist))
1723 plist)
1724 (mapc
1725 (lambda (cell)
1726 (let ((prop (car cell)))
1727 (unless (plist-member plist prop)
1728 (setq plist
1729 (plist-put
1730 plist
1731 prop
1732 ;; Eval default value provided. If keyword is a member
1733 ;; of `org-element-document-properties', parse it as
1734 ;; a secondary string before storing it.
1735 (let ((value (eval (nth 3 cell))))
1736 (if (not (stringp value)) value
1737 (let ((keyword (nth 1 cell)))
1738 (if (not (member keyword org-element-document-properties))
1739 value
1740 (org-element-parse-secondary-string
1741 value (org-element-restriction 'keyword)))))))))))
1742 all)
1743 ;; Return value.
1744 plist))
1746 (defun org-export--list-bound-variables ()
1747 "Return variables bound from BIND keywords in current buffer.
1748 Also look for BIND keywords in setup files. The return value is
1749 an alist where associations are (VARIABLE-NAME VALUE)."
1750 (when org-export-allow-bind-keywords
1751 (let* (collect-bind ; For byte-compiler.
1752 (collect-bind
1753 (lambda (files alist)
1754 ;; Return an alist between variable names and their
1755 ;; value. FILES is a list of setup files names read so
1756 ;; far, used to avoid circular dependencies. ALIST is
1757 ;; the alist collected so far.
1758 (let ((case-fold-search t))
1759 (org-with-wide-buffer
1760 (goto-char (point-min))
1761 (while (re-search-forward
1762 "^[ \t]*#\\+\\(BIND\\|SETUPFILE\\):" nil t)
1763 (let ((element (org-element-at-point)))
1764 (when (eq (org-element-type element) 'keyword)
1765 (let ((val (org-element-property :value element)))
1766 (if (equal (org-element-property :key element) "BIND")
1767 (push (read (format "(%s)" val)) alist)
1768 ;; Enter setup file.
1769 (let ((file (expand-file-name
1770 (org-remove-double-quotes val))))
1771 (unless (member file files)
1772 (with-temp-buffer
1773 (let ((org-inhibit-startup t)) (org-mode))
1774 (insert (org-file-contents file 'noerror))
1775 (setq alist
1776 (funcall collect-bind
1777 (cons file files)
1778 alist))))))))))
1779 alist)))))
1780 ;; Return value in appropriate order of appearance.
1781 (nreverse (funcall collect-bind nil nil)))))
1784 ;;;; Tree Properties
1786 ;; Tree properties are information extracted from parse tree. They
1787 ;; are initialized at the beginning of the transcoding process by
1788 ;; `org-export-collect-tree-properties'.
1790 ;; Dedicated functions focus on computing the value of specific tree
1791 ;; properties during initialization. Thus,
1792 ;; `org-export--populate-ignore-list' lists elements and objects that
1793 ;; should be skipped during export, `org-export--get-min-level' gets
1794 ;; the minimal exportable level, used as a basis to compute relative
1795 ;; level for headlines. Eventually
1796 ;; `org-export--collect-headline-numbering' builds an alist between
1797 ;; headlines and their numbering.
1799 (defun org-export-collect-tree-properties (data info)
1800 "Extract tree properties from parse tree.
1802 DATA is the parse tree from which information is retrieved. INFO
1803 is a list holding export options.
1805 Following tree properties are set or updated:
1807 `:exported-data' Hash table used to memoize results from
1808 `org-export-data'.
1810 `:footnote-definition-alist' List of footnotes definitions in
1811 original buffer and current parse tree.
1813 `:headline-offset' Offset between true level of headlines and
1814 local level. An offset of -1 means a headline
1815 of level 2 should be considered as a level
1816 1 headline in the context.
1818 `:headline-numbering' Alist of all headlines as key an the
1819 associated numbering as value.
1821 `:ignore-list' List of elements that should be ignored during
1822 export.
1824 Return updated plist."
1825 ;; Install the parse tree in the communication channel, in order to
1826 ;; use `org-export-get-genealogy' and al.
1827 (setq info (plist-put info :parse-tree data))
1828 ;; Get the list of elements and objects to ignore, and put it into
1829 ;; `:ignore-list'. Do not overwrite any user ignore that might have
1830 ;; been done during parse tree filtering.
1831 (setq info
1832 (plist-put info
1833 :ignore-list
1834 (append (org-export--populate-ignore-list data info)
1835 (plist-get info :ignore-list))))
1836 ;; Compute `:headline-offset' in order to be able to use
1837 ;; `org-export-get-relative-level'.
1838 (setq info
1839 (plist-put info
1840 :headline-offset
1841 (- 1 (org-export--get-min-level data info))))
1842 ;; Update footnotes definitions list with definitions in parse tree.
1843 ;; This is required since buffer expansion might have modified
1844 ;; boundaries of footnote definitions contained in the parse tree.
1845 ;; This way, definitions in `footnote-definition-alist' are bound to
1846 ;; match those in the parse tree.
1847 (let ((defs (plist-get info :footnote-definition-alist)))
1848 (org-element-map data 'footnote-definition
1849 (lambda (fn)
1850 (push (cons (org-element-property :label fn)
1851 `(org-data nil ,@(org-element-contents fn)))
1852 defs)))
1853 (setq info (plist-put info :footnote-definition-alist defs)))
1854 ;; Properties order doesn't matter: get the rest of the tree
1855 ;; properties.
1856 (nconc
1857 `(:headline-numbering ,(org-export--collect-headline-numbering data info)
1858 :exported-data ,(make-hash-table :test 'eq :size 4001))
1859 info))
1861 (defun org-export--get-min-level (data options)
1862 "Return minimum exportable headline's level in DATA.
1863 DATA is parsed tree as returned by `org-element-parse-buffer'.
1864 OPTIONS is a plist holding export options."
1865 (catch 'exit
1866 (let ((min-level 10000))
1867 (mapc
1868 (lambda (blob)
1869 (when (and (eq (org-element-type blob) 'headline)
1870 (not (org-element-property :footnote-section-p blob))
1871 (not (memq blob (plist-get options :ignore-list))))
1872 (setq min-level (min (org-element-property :level blob) min-level)))
1873 (when (= min-level 1) (throw 'exit 1)))
1874 (org-element-contents data))
1875 ;; If no headline was found, for the sake of consistency, set
1876 ;; minimum level to 1 nonetheless.
1877 (if (= min-level 10000) 1 min-level))))
1879 (defun org-export--collect-headline-numbering (data options)
1880 "Return numbering of all exportable headlines in a parse tree.
1882 DATA is the parse tree. OPTIONS is the plist holding export
1883 options.
1885 Return an alist whose key is a headline and value is its
1886 associated numbering \(in the shape of a list of numbers\) or nil
1887 for a footnotes section."
1888 (let ((numbering (make-vector org-export-max-depth 0)))
1889 (org-element-map data 'headline
1890 (lambda (headline)
1891 (unless (org-element-property :footnote-section-p headline)
1892 (let ((relative-level
1893 (1- (org-export-get-relative-level headline options))))
1894 (cons
1895 headline
1896 (loop for n across numbering
1897 for idx from 0 to org-export-max-depth
1898 when (< idx relative-level) collect n
1899 when (= idx relative-level) collect (aset numbering idx (1+ n))
1900 when (> idx relative-level) do (aset numbering idx 0))))))
1901 options)))
1903 (defun org-export--populate-ignore-list (data options)
1904 "Return list of elements and objects to ignore during export.
1905 DATA is the parse tree to traverse. OPTIONS is the plist holding
1906 export options."
1907 (let* (ignore
1908 walk-data
1909 ;; First find trees containing a select tag, if any.
1910 (selected (org-export--selected-trees data options))
1911 (walk-data
1912 (lambda (data)
1913 ;; Collect ignored elements or objects into IGNORE-LIST.
1914 (let ((type (org-element-type data)))
1915 (if (org-export--skip-p data options selected) (push data ignore)
1916 (if (and (eq type 'headline)
1917 (eq (plist-get options :with-archived-trees) 'headline)
1918 (org-element-property :archivedp data))
1919 ;; If headline is archived but tree below has
1920 ;; to be skipped, add it to ignore list.
1921 (mapc (lambda (e) (push e ignore))
1922 (org-element-contents data))
1923 ;; Move into secondary string, if any.
1924 (let ((sec-prop
1925 (cdr (assq type org-element-secondary-value-alist))))
1926 (when sec-prop
1927 (mapc walk-data (org-element-property sec-prop data))))
1928 ;; Move into recursive objects/elements.
1929 (mapc walk-data (org-element-contents data))))))))
1930 ;; Main call.
1931 (funcall walk-data data)
1932 ;; Return value.
1933 ignore))
1935 (defun org-export--selected-trees (data info)
1936 "Return list of headlines and inlinetasks with a select tag in their tree.
1937 DATA is parsed data as returned by `org-element-parse-buffer'.
1938 INFO is a plist holding export options."
1939 (let* (selected-trees
1940 walk-data ; For byte-compiler.
1941 (walk-data
1942 (function
1943 (lambda (data genealogy)
1944 (let ((type (org-element-type data)))
1945 (cond
1946 ((memq type '(headline inlinetask))
1947 (let ((tags (org-element-property :tags data)))
1948 (if (loop for tag in (plist-get info :select-tags)
1949 thereis (member tag tags))
1950 ;; When a select tag is found, mark full
1951 ;; genealogy and every headline within the tree
1952 ;; as acceptable.
1953 (setq selected-trees
1954 (append
1955 genealogy
1956 (org-element-map data '(headline inlinetask)
1957 'identity)
1958 selected-trees))
1959 ;; If at a headline, continue searching in tree,
1960 ;; recursively.
1961 (when (eq type 'headline)
1962 (mapc (lambda (el)
1963 (funcall walk-data el (cons data genealogy)))
1964 (org-element-contents data))))))
1965 ((or (eq type 'org-data)
1966 (memq type org-element-greater-elements))
1967 (mapc (lambda (el) (funcall walk-data el genealogy))
1968 (org-element-contents data)))))))))
1969 (funcall walk-data data nil)
1970 selected-trees))
1972 (defun org-export--skip-p (blob options selected)
1973 "Non-nil when element or object BLOB should be skipped during export.
1974 OPTIONS is the plist holding export options. SELECTED, when
1975 non-nil, is a list of headlines or inlinetasks belonging to
1976 a tree with a select tag."
1977 (case (org-element-type blob)
1978 (clock (not (plist-get options :with-clocks)))
1979 (drawer
1980 (let ((with-drawers-p (plist-get options :with-drawers)))
1981 (or (not with-drawers-p)
1982 (and (consp with-drawers-p)
1983 ;; If `:with-drawers' value starts with `not', ignore
1984 ;; every drawer whose name belong to that list.
1985 ;; Otherwise, ignore drawers whose name isn't in that
1986 ;; list.
1987 (let ((name (org-element-property :drawer-name blob)))
1988 (if (eq (car with-drawers-p) 'not)
1989 (member-ignore-case name (cdr with-drawers-p))
1990 (not (member-ignore-case name with-drawers-p))))))))
1991 ((headline inlinetask)
1992 (let ((with-tasks (plist-get options :with-tasks))
1993 (todo (org-element-property :todo-keyword blob))
1994 (todo-type (org-element-property :todo-type blob))
1995 (archived (plist-get options :with-archived-trees))
1996 (tags (org-element-property :tags blob)))
1998 (and (eq (org-element-type blob) 'inlinetask)
1999 (not (plist-get options :with-inlinetasks)))
2000 ;; Ignore subtrees with an exclude tag.
2001 (loop for k in (plist-get options :exclude-tags)
2002 thereis (member k tags))
2003 ;; When a select tag is present in the buffer, ignore any tree
2004 ;; without it.
2005 (and selected (not (memq blob selected)))
2006 ;; Ignore commented sub-trees.
2007 (org-element-property :commentedp blob)
2008 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
2009 (and (not archived) (org-element-property :archivedp blob))
2010 ;; Ignore tasks, if specified by `:with-tasks' property.
2011 (and todo
2012 (or (not with-tasks)
2013 (and (memq with-tasks '(todo done))
2014 (not (eq todo-type with-tasks)))
2015 (and (consp with-tasks) (not (member todo with-tasks))))))))
2016 ((latex-environment latex-fragment) (not (plist-get options :with-latex)))
2017 (planning (not (plist-get options :with-planning)))
2018 (statistics-cookie (not (plist-get options :with-statistics-cookies)))
2019 (table-cell
2020 (and (org-export-table-has-special-column-p
2021 (org-export-get-parent-table blob))
2022 (not (org-export-get-previous-element blob options))))
2023 (table-row (org-export-table-row-is-special-p blob options))
2024 (timestamp
2025 (case (plist-get options :with-timestamps)
2026 ;; No timestamp allowed.
2027 ('nil t)
2028 ;; Only active timestamps allowed and the current one isn't
2029 ;; active.
2030 (active
2031 (not (memq (org-element-property :type blob)
2032 '(active active-range))))
2033 ;; Only inactive timestamps allowed and the current one isn't
2034 ;; inactive.
2035 (inactive
2036 (not (memq (org-element-property :type blob)
2037 '(inactive inactive-range))))))))
2040 ;;; The Transcoder
2042 ;; `org-export-data' reads a parse tree (obtained with, i.e.
2043 ;; `org-element-parse-buffer') and transcodes it into a specified
2044 ;; back-end output. It takes care of filtering out elements or
2045 ;; objects according to export options and organizing the output blank
2046 ;; lines and white space are preserved. The function memoizes its
2047 ;; results, so it is cheap to call it within translators.
2049 ;; It is possible to modify locally the back-end used by
2050 ;; `org-export-data' or even use a temporary back-end by using
2051 ;; `org-export-data-with-translations' and
2052 ;; `org-export-data-with-backend'.
2054 ;; Internally, three functions handle the filtering of objects and
2055 ;; elements during the export. In particular,
2056 ;; `org-export-ignore-element' marks an element or object so future
2057 ;; parse tree traversals skip it, `org-export--interpret-p' tells which
2058 ;; elements or objects should be seen as real Org syntax and
2059 ;; `org-export-expand' transforms the others back into their original
2060 ;; shape
2062 ;; `org-export-transcoder' is an accessor returning appropriate
2063 ;; translator function for a given element or object.
2065 (defun org-export-transcoder (blob info)
2066 "Return appropriate transcoder for BLOB.
2067 INFO is a plist containing export directives."
2068 (let ((type (org-element-type blob)))
2069 ;; Return contents only for complete parse trees.
2070 (if (eq type 'org-data) (lambda (blob contents info) contents)
2071 (let ((transcoder (cdr (assq type (plist-get info :translate-alist)))))
2072 (and (functionp transcoder) transcoder)))))
2074 (defun org-export-data (data info)
2075 "Convert DATA into current back-end format.
2077 DATA is a parse tree, an element or an object or a secondary
2078 string. INFO is a plist holding export options.
2080 Return transcoded string."
2081 (let ((memo (gethash data (plist-get info :exported-data) 'no-memo)))
2082 (if (not (eq memo 'no-memo)) memo
2083 (let* ((type (org-element-type data))
2084 (results
2085 (cond
2086 ;; Ignored element/object.
2087 ((memq data (plist-get info :ignore-list)) nil)
2088 ;; Plain text.
2089 ((eq type 'plain-text)
2090 (org-export-filter-apply-functions
2091 (plist-get info :filter-plain-text)
2092 (let ((transcoder (org-export-transcoder data info)))
2093 (if transcoder (funcall transcoder data info) data))
2094 info))
2095 ;; Uninterpreted element/object: change it back to Org
2096 ;; syntax and export again resulting raw string.
2097 ((not (org-export--interpret-p data info))
2098 (org-export-data
2099 (org-export-expand
2100 data
2101 (mapconcat (lambda (blob) (org-export-data blob info))
2102 (org-element-contents data)
2103 ""))
2104 info))
2105 ;; Secondary string.
2106 ((not type)
2107 (mapconcat (lambda (obj) (org-export-data obj info)) data ""))
2108 ;; Element/Object without contents or, as a special case,
2109 ;; headline with archive tag and archived trees restricted
2110 ;; to title only.
2111 ((or (not (org-element-contents data))
2112 (and (eq type 'headline)
2113 (eq (plist-get info :with-archived-trees) 'headline)
2114 (org-element-property :archivedp data)))
2115 (let ((transcoder (org-export-transcoder data info)))
2116 (or (and (functionp transcoder)
2117 (funcall transcoder data nil info))
2118 ;; Export snippets never return a nil value so
2119 ;; that white spaces following them are never
2120 ;; ignored.
2121 (and (eq type 'export-snippet) ""))))
2122 ;; Element/Object with contents.
2124 (let ((transcoder (org-export-transcoder data info)))
2125 (when transcoder
2126 (let* ((greaterp (memq type org-element-greater-elements))
2127 (objectp
2128 (and (not greaterp)
2129 (memq type org-element-recursive-objects)))
2130 (contents
2131 (mapconcat
2132 (lambda (element) (org-export-data element info))
2133 (org-element-contents
2134 (if (or greaterp objectp) data
2135 ;; Elements directly containing objects
2136 ;; must have their indentation normalized
2137 ;; first.
2138 (org-element-normalize-contents
2139 data
2140 ;; When normalizing contents of the first
2141 ;; paragraph in an item or a footnote
2142 ;; definition, ignore first line's
2143 ;; indentation: there is none and it
2144 ;; might be misleading.
2145 (when (eq type 'paragraph)
2146 (let ((parent (org-export-get-parent data)))
2147 (and
2148 (eq (car (org-element-contents parent))
2149 data)
2150 (memq (org-element-type parent)
2151 '(footnote-definition item))))))))
2152 "")))
2153 (funcall transcoder data
2154 (if (not greaterp) contents
2155 (org-element-normalize-string contents))
2156 info))))))))
2157 ;; Final result will be memoized before being returned.
2158 (puthash
2159 data
2160 (cond
2161 ((not results) nil)
2162 ((memq type '(org-data plain-text nil)) results)
2163 ;; Append the same white space between elements or objects as in
2164 ;; the original buffer, and call appropriate filters.
2166 (let ((results
2167 (org-export-filter-apply-functions
2168 (plist-get info (intern (format ":filter-%s" type)))
2169 (let ((post-blank (or (org-element-property :post-blank data)
2170 0)))
2171 (if (memq type org-element-all-elements)
2172 (concat (org-element-normalize-string results)
2173 (make-string post-blank ?\n))
2174 (concat results (make-string post-blank ? ))))
2175 info)))
2176 results)))
2177 (plist-get info :exported-data))))))
2179 (defun org-export-data-with-translations (data translations info)
2180 "Convert DATA into another format using a given translation table.
2181 DATA is an element, an object, a secondary string or a string.
2182 TRANSLATIONS is an alist between element or object types and
2183 a functions handling them. See `org-export-define-backend' for
2184 more information. INFO is a plist used as a communication
2185 channel."
2186 (org-export-data
2187 data
2188 ;; Set-up a new communication channel with TRANSLATIONS as the
2189 ;; translate table and a new hash table for memoization.
2190 (org-combine-plists
2191 info
2192 (list :translate-alist translations
2193 ;; Size of the hash table is reduced since this function
2194 ;; will probably be used on short trees.
2195 :exported-data (make-hash-table :test 'eq :size 401)))))
2197 (defun org-export-data-with-backend (data backend info)
2198 "Convert DATA into BACKEND format.
2200 DATA is an element, an object, a secondary string or a string.
2201 BACKEND is a symbol. INFO is a plist used as a communication
2202 channel.
2204 Unlike to `org-export-with-backend', this function will
2205 recursively convert DATA using BACKEND translation table."
2206 (org-export-barf-if-invalid-backend backend)
2207 (org-export-data-with-translations
2208 data (org-export-backend-translate-table backend) info))
2210 (defun org-export--interpret-p (blob info)
2211 "Non-nil if element or object BLOB should be interpreted during export.
2212 If nil, BLOB will appear as raw Org syntax. Check is done
2213 according to export options INFO, stored as a plist."
2214 (case (org-element-type blob)
2215 ;; ... entities...
2216 (entity (plist-get info :with-entities))
2217 ;; ... emphasis...
2218 ((bold italic strike-through underline)
2219 (plist-get info :with-emphasize))
2220 ;; ... fixed-width areas.
2221 (fixed-width (plist-get info :with-fixed-width))
2222 ;; ... footnotes...
2223 ((footnote-definition footnote-reference)
2224 (plist-get info :with-footnotes))
2225 ;; ... LaTeX environments and fragments...
2226 ((latex-environment latex-fragment)
2227 (let ((with-latex-p (plist-get info :with-latex)))
2228 (and with-latex-p (not (eq with-latex-p 'verbatim)))))
2229 ;; ... sub/superscripts...
2230 ((subscript superscript)
2231 (let ((sub/super-p (plist-get info :with-sub-superscript)))
2232 (if (eq sub/super-p '{})
2233 (org-element-property :use-brackets-p blob)
2234 sub/super-p)))
2235 ;; ... tables...
2236 (table (plist-get info :with-tables))
2237 (otherwise t)))
2239 (defun org-export-expand (blob contents)
2240 "Expand a parsed element or object to its original state.
2241 BLOB is either an element or an object. CONTENTS is its
2242 contents, as a string or nil."
2243 (funcall
2244 (intern (format "org-element-%s-interpreter" (org-element-type blob)))
2245 blob contents))
2247 (defun org-export-ignore-element (element info)
2248 "Add ELEMENT to `:ignore-list' in INFO.
2250 Any element in `:ignore-list' will be skipped when using
2251 `org-element-map'. INFO is modified by side effects."
2252 (plist-put info :ignore-list (cons element (plist-get info :ignore-list))))
2256 ;;; The Filter System
2258 ;; Filters allow end-users to tweak easily the transcoded output.
2259 ;; They are the functional counterpart of hooks, as every filter in
2260 ;; a set is applied to the return value of the previous one.
2262 ;; Every set is back-end agnostic. Although, a filter is always
2263 ;; called, in addition to the string it applies to, with the back-end
2264 ;; used as argument, so it's easy for the end-user to add back-end
2265 ;; specific filters in the set. The communication channel, as
2266 ;; a plist, is required as the third argument.
2268 ;; From the developer side, filters sets can be installed in the
2269 ;; process with the help of `org-export-define-backend', which
2270 ;; internally stores filters as an alist. Each association has a key
2271 ;; among the following symbols and a function or a list of functions
2272 ;; as value.
2274 ;; - `:filter-options' applies to the property list containing export
2275 ;; options. Unlike to other filters, functions in this list accept
2276 ;; two arguments instead of three: the property list containing
2277 ;; export options and the back-end. Users can set its value through
2278 ;; `org-export-filter-options-functions' variable.
2280 ;; - `:filter-parse-tree' applies directly to the complete parsed
2281 ;; tree. Users can set it through
2282 ;; `org-export-filter-parse-tree-functions' variable.
2284 ;; - `:filter-final-output' applies to the final transcoded string.
2285 ;; Users can set it with `org-export-filter-final-output-functions'
2286 ;; variable
2288 ;; - `:filter-plain-text' applies to any string not recognized as Org
2289 ;; syntax. `org-export-filter-plain-text-functions' allows users to
2290 ;; configure it.
2292 ;; - `:filter-TYPE' applies on the string returned after an element or
2293 ;; object of type TYPE has been transcoded. A user can modify
2294 ;; `org-export-filter-TYPE-functions'
2296 ;; All filters sets are applied with
2297 ;; `org-export-filter-apply-functions' function. Filters in a set are
2298 ;; applied in a LIFO fashion. It allows developers to be sure that
2299 ;; their filters will be applied first.
2301 ;; Filters properties are installed in communication channel with
2302 ;; `org-export-install-filters' function.
2304 ;; Eventually, two hooks (`org-export-before-processing-hook' and
2305 ;; `org-export-before-parsing-hook') are run at the beginning of the
2306 ;; export process and just before parsing to allow for heavy structure
2307 ;; modifications.
2310 ;;;; Hooks
2312 (defvar org-export-before-processing-hook nil
2313 "Hook run at the beginning of the export process.
2315 This is run before include keywords and macros are expanded and
2316 Babel code blocks executed, on a copy of the original buffer
2317 being exported. Visibility and narrowing are preserved. Point
2318 is at the beginning of the buffer.
2320 Every function in this hook will be called with one argument: the
2321 back-end currently used, as a symbol.")
2323 (defvar org-export-before-parsing-hook nil
2324 "Hook run before parsing an export buffer.
2326 This is run after include keywords and macros have been expanded
2327 and Babel code blocks executed, on a copy of the original buffer
2328 being exported. Visibility and narrowing are preserved. Point
2329 is at the beginning of the buffer.
2331 Every function in this hook will be called with one argument: the
2332 back-end currently used, as a symbol.")
2335 ;;;; Special Filters
2337 (defvar org-export-filter-options-functions nil
2338 "List of functions applied to the export options.
2339 Each filter is called with two arguments: the export options, as
2340 a plist, and the back-end, as a symbol. It must return
2341 a property list containing export options.")
2343 (defvar org-export-filter-parse-tree-functions nil
2344 "List of functions applied to the parsed tree.
2345 Each filter is called with three arguments: the parse tree, as
2346 returned by `org-element-parse-buffer', the back-end, as
2347 a symbol, and the communication channel, as a plist. It must
2348 return the modified parse tree to transcode.")
2350 (defvar org-export-filter-plain-text-functions nil
2351 "List of functions applied to plain text.
2352 Each filter is called with three arguments: a string which
2353 contains no Org syntax, the back-end, as a symbol, and the
2354 communication channel, as a plist. It must return a string or
2355 nil.")
2357 (defvar org-export-filter-final-output-functions nil
2358 "List of functions applied to the transcoded string.
2359 Each filter is called with three arguments: the full transcoded
2360 string, the back-end, as a symbol, and the communication channel,
2361 as a plist. It must return a string that will be used as the
2362 final export output.")
2365 ;;;; Elements Filters
2367 (defvar org-export-filter-babel-call-functions nil
2368 "List of functions applied to a transcoded babel-call.
2369 Each filter is called with three arguments: the transcoded data,
2370 as a string, the back-end, as a symbol, and the communication
2371 channel, as a plist. It must return a string or nil.")
2373 (defvar org-export-filter-center-block-functions nil
2374 "List of functions applied to a transcoded center block.
2375 Each filter is called with three arguments: the transcoded data,
2376 as a string, the back-end, as a symbol, and the communication
2377 channel, as a plist. It must return a string or nil.")
2379 (defvar org-export-filter-clock-functions nil
2380 "List of functions applied to a transcoded clock.
2381 Each filter is called with three arguments: the transcoded data,
2382 as a string, the back-end, as a symbol, and the communication
2383 channel, as a plist. It must return a string or nil.")
2385 (defvar org-export-filter-comment-functions nil
2386 "List of functions applied to a transcoded comment.
2387 Each filter is called with three arguments: the transcoded data,
2388 as a string, the back-end, as a symbol, and the communication
2389 channel, as a plist. It must return a string or nil.")
2391 (defvar org-export-filter-comment-block-functions nil
2392 "List of functions applied to a transcoded comment-block.
2393 Each filter is called with three arguments: the transcoded data,
2394 as a string, the back-end, as a symbol, and the communication
2395 channel, as a plist. It must return a string or nil.")
2397 (defvar org-export-filter-diary-sexp-functions nil
2398 "List of functions applied to a transcoded diary-sexp.
2399 Each filter is called with three arguments: the transcoded data,
2400 as a string, the back-end, as a symbol, and the communication
2401 channel, as a plist. It must return a string or nil.")
2403 (defvar org-export-filter-drawer-functions nil
2404 "List of functions applied to a transcoded drawer.
2405 Each filter is called with three arguments: the transcoded data,
2406 as a string, the back-end, as a symbol, and the communication
2407 channel, as a plist. It must return a string or nil.")
2409 (defvar org-export-filter-dynamic-block-functions nil
2410 "List of functions applied to a transcoded dynamic-block.
2411 Each filter is called with three arguments: the transcoded data,
2412 as a string, the back-end, as a symbol, and the communication
2413 channel, as a plist. It must return a string or nil.")
2415 (defvar org-export-filter-example-block-functions nil
2416 "List of functions applied to a transcoded example-block.
2417 Each filter is called with three arguments: the transcoded data,
2418 as a string, the back-end, as a symbol, and the communication
2419 channel, as a plist. It must return a string or nil.")
2421 (defvar org-export-filter-export-block-functions nil
2422 "List of functions applied to a transcoded export-block.
2423 Each filter is called with three arguments: the transcoded data,
2424 as a string, the back-end, as a symbol, and the communication
2425 channel, as a plist. It must return a string or nil.")
2427 (defvar org-export-filter-fixed-width-functions nil
2428 "List of functions applied to a transcoded fixed-width.
2429 Each filter is called with three arguments: the transcoded data,
2430 as a string, the back-end, as a symbol, and the communication
2431 channel, as a plist. It must return a string or nil.")
2433 (defvar org-export-filter-footnote-definition-functions nil
2434 "List of functions applied to a transcoded footnote-definition.
2435 Each filter is called with three arguments: the transcoded data,
2436 as a string, the back-end, as a symbol, and the communication
2437 channel, as a plist. It must return a string or nil.")
2439 (defvar org-export-filter-headline-functions nil
2440 "List of functions applied to a transcoded headline.
2441 Each filter is called with three arguments: the transcoded data,
2442 as a string, the back-end, as a symbol, and the communication
2443 channel, as a plist. It must return a string or nil.")
2445 (defvar org-export-filter-horizontal-rule-functions nil
2446 "List of functions applied to a transcoded horizontal-rule.
2447 Each filter is called with three arguments: the transcoded data,
2448 as a string, the back-end, as a symbol, and the communication
2449 channel, as a plist. It must return a string or nil.")
2451 (defvar org-export-filter-inlinetask-functions nil
2452 "List of functions applied to a transcoded inlinetask.
2453 Each filter is called with three arguments: the transcoded data,
2454 as a string, the back-end, as a symbol, and the communication
2455 channel, as a plist. It must return a string or nil.")
2457 (defvar org-export-filter-item-functions nil
2458 "List of functions applied to a transcoded item.
2459 Each filter is called with three arguments: the transcoded data,
2460 as a string, the back-end, as a symbol, and the communication
2461 channel, as a plist. It must return a string or nil.")
2463 (defvar org-export-filter-keyword-functions nil
2464 "List of functions applied to a transcoded keyword.
2465 Each filter is called with three arguments: the transcoded data,
2466 as a string, the back-end, as a symbol, and the communication
2467 channel, as a plist. It must return a string or nil.")
2469 (defvar org-export-filter-latex-environment-functions nil
2470 "List of functions applied to a transcoded latex-environment.
2471 Each filter is called with three arguments: the transcoded data,
2472 as a string, the back-end, as a symbol, and the communication
2473 channel, as a plist. It must return a string or nil.")
2475 (defvar org-export-filter-node-property-functions nil
2476 "List of functions applied to a transcoded node-property.
2477 Each filter is called with three arguments: the transcoded data,
2478 as a string, the back-end, as a symbol, and the communication
2479 channel, as a plist. It must return a string or nil.")
2481 (defvar org-export-filter-paragraph-functions nil
2482 "List of functions applied to a transcoded paragraph.
2483 Each filter is called with three arguments: the transcoded data,
2484 as a string, the back-end, as a symbol, and the communication
2485 channel, as a plist. It must return a string or nil.")
2487 (defvar org-export-filter-plain-list-functions nil
2488 "List of functions applied to a transcoded plain-list.
2489 Each filter is called with three arguments: the transcoded data,
2490 as a string, the back-end, as a symbol, and the communication
2491 channel, as a plist. It must return a string or nil.")
2493 (defvar org-export-filter-planning-functions nil
2494 "List of functions applied to a transcoded planning.
2495 Each filter is called with three arguments: the transcoded data,
2496 as a string, the back-end, as a symbol, and the communication
2497 channel, as a plist. It must return a string or nil.")
2499 (defvar org-export-filter-property-drawer-functions nil
2500 "List of functions applied to a transcoded property-drawer.
2501 Each filter is called with three arguments: the transcoded data,
2502 as a string, the back-end, as a symbol, and the communication
2503 channel, as a plist. It must return a string or nil.")
2505 (defvar org-export-filter-quote-block-functions nil
2506 "List of functions applied to a transcoded quote block.
2507 Each filter is called with three arguments: the transcoded quote
2508 data, as a string, the back-end, as a symbol, and the
2509 communication channel, as a plist. It must return a string or
2510 nil.")
2512 (defvar org-export-filter-quote-section-functions nil
2513 "List of functions applied to a transcoded quote-section.
2514 Each filter is called with three arguments: the transcoded data,
2515 as a string, the back-end, as a symbol, and the communication
2516 channel, as a plist. It must return a string or nil.")
2518 (defvar org-export-filter-section-functions nil
2519 "List of functions applied to a transcoded section.
2520 Each filter is called with three arguments: the transcoded data,
2521 as a string, the back-end, as a symbol, and the communication
2522 channel, as a plist. It must return a string or nil.")
2524 (defvar org-export-filter-special-block-functions nil
2525 "List of functions applied to a transcoded special block.
2526 Each filter is called with three arguments: the transcoded data,
2527 as a string, the back-end, as a symbol, and the communication
2528 channel, as a plist. It must return a string or nil.")
2530 (defvar org-export-filter-src-block-functions nil
2531 "List of functions applied to a transcoded src-block.
2532 Each filter is called with three arguments: the transcoded data,
2533 as a string, the back-end, as a symbol, and the communication
2534 channel, as a plist. It must return a string or nil.")
2536 (defvar org-export-filter-table-functions nil
2537 "List of functions applied to a transcoded table.
2538 Each filter is called with three arguments: the transcoded data,
2539 as a string, the back-end, as a symbol, and the communication
2540 channel, as a plist. It must return a string or nil.")
2542 (defvar org-export-filter-table-cell-functions nil
2543 "List of functions applied to a transcoded table-cell.
2544 Each filter is called with three arguments: the transcoded data,
2545 as a string, the back-end, as a symbol, and the communication
2546 channel, as a plist. It must return a string or nil.")
2548 (defvar org-export-filter-table-row-functions nil
2549 "List of functions applied to a transcoded table-row.
2550 Each filter is called with three arguments: the transcoded data,
2551 as a string, the back-end, as a symbol, and the communication
2552 channel, as a plist. It must return a string or nil.")
2554 (defvar org-export-filter-verse-block-functions nil
2555 "List of functions applied to a transcoded verse block.
2556 Each filter is called with three arguments: the transcoded data,
2557 as a string, the back-end, as a symbol, and the communication
2558 channel, as a plist. It must return a string or nil.")
2561 ;;;; Objects Filters
2563 (defvar org-export-filter-bold-functions nil
2564 "List of functions applied to transcoded bold text.
2565 Each filter is called with three arguments: the transcoded data,
2566 as a string, the back-end, as a symbol, and the communication
2567 channel, as a plist. It must return a string or nil.")
2569 (defvar org-export-filter-code-functions nil
2570 "List of functions applied to transcoded code text.
2571 Each filter is called with three arguments: the transcoded data,
2572 as a string, the back-end, as a symbol, and the communication
2573 channel, as a plist. It must return a string or nil.")
2575 (defvar org-export-filter-entity-functions nil
2576 "List of functions applied to a transcoded entity.
2577 Each filter is called with three arguments: the transcoded data,
2578 as a string, the back-end, as a symbol, and the communication
2579 channel, as a plist. It must return a string or nil.")
2581 (defvar org-export-filter-export-snippet-functions nil
2582 "List of functions applied to a transcoded export-snippet.
2583 Each filter is called with three arguments: the transcoded data,
2584 as a string, the back-end, as a symbol, and the communication
2585 channel, as a plist. It must return a string or nil.")
2587 (defvar org-export-filter-footnote-reference-functions nil
2588 "List of functions applied to a transcoded footnote-reference.
2589 Each filter is called with three arguments: the transcoded data,
2590 as a string, the back-end, as a symbol, and the communication
2591 channel, as a plist. It must return a string or nil.")
2593 (defvar org-export-filter-inline-babel-call-functions nil
2594 "List of functions applied to a transcoded inline-babel-call.
2595 Each filter is called with three arguments: the transcoded data,
2596 as a string, the back-end, as a symbol, and the communication
2597 channel, as a plist. It must return a string or nil.")
2599 (defvar org-export-filter-inline-src-block-functions nil
2600 "List of functions applied to a transcoded inline-src-block.
2601 Each filter is called with three arguments: the transcoded data,
2602 as a string, the back-end, as a symbol, and the communication
2603 channel, as a plist. It must return a string or nil.")
2605 (defvar org-export-filter-italic-functions nil
2606 "List of functions applied to transcoded italic text.
2607 Each filter is called with three arguments: the transcoded data,
2608 as a string, the back-end, as a symbol, and the communication
2609 channel, as a plist. It must return a string or nil.")
2611 (defvar org-export-filter-latex-fragment-functions nil
2612 "List of functions applied to a transcoded latex-fragment.
2613 Each filter is called with three arguments: the transcoded data,
2614 as a string, the back-end, as a symbol, and the communication
2615 channel, as a plist. It must return a string or nil.")
2617 (defvar org-export-filter-line-break-functions nil
2618 "List of functions applied to a transcoded line-break.
2619 Each filter is called with three arguments: the transcoded data,
2620 as a string, the back-end, as a symbol, and the communication
2621 channel, as a plist. It must return a string or nil.")
2623 (defvar org-export-filter-link-functions nil
2624 "List of functions applied to a transcoded link.
2625 Each filter is called with three arguments: the transcoded data,
2626 as a string, the back-end, as a symbol, and the communication
2627 channel, as a plist. It must return a string or nil.")
2629 (defvar org-export-filter-radio-target-functions nil
2630 "List of functions applied to a transcoded radio-target.
2631 Each filter is called with three arguments: the transcoded data,
2632 as a string, the back-end, as a symbol, and the communication
2633 channel, as a plist. It must return a string or nil.")
2635 (defvar org-export-filter-statistics-cookie-functions nil
2636 "List of functions applied to a transcoded statistics-cookie.
2637 Each filter is called with three arguments: the transcoded data,
2638 as a string, the back-end, as a symbol, and the communication
2639 channel, as a plist. It must return a string or nil.")
2641 (defvar org-export-filter-strike-through-functions nil
2642 "List of functions applied to transcoded strike-through text.
2643 Each filter is called with three arguments: the transcoded data,
2644 as a string, the back-end, as a symbol, and the communication
2645 channel, as a plist. It must return a string or nil.")
2647 (defvar org-export-filter-subscript-functions nil
2648 "List of functions applied to a transcoded subscript.
2649 Each filter is called with three arguments: the transcoded data,
2650 as a string, the back-end, as a symbol, and the communication
2651 channel, as a plist. It must return a string or nil.")
2653 (defvar org-export-filter-superscript-functions nil
2654 "List of functions applied to a transcoded superscript.
2655 Each filter is called with three arguments: the transcoded data,
2656 as a string, the back-end, as a symbol, and the communication
2657 channel, as a plist. It must return a string or nil.")
2659 (defvar org-export-filter-target-functions nil
2660 "List of functions applied to a transcoded target.
2661 Each filter is called with three arguments: the transcoded data,
2662 as a string, the back-end, as a symbol, and the communication
2663 channel, as a plist. It must return a string or nil.")
2665 (defvar org-export-filter-timestamp-functions nil
2666 "List of functions applied to a transcoded timestamp.
2667 Each filter is called with three arguments: the transcoded data,
2668 as a string, the back-end, as a symbol, and the communication
2669 channel, as a plist. It must return a string or nil.")
2671 (defvar org-export-filter-underline-functions nil
2672 "List of functions applied to transcoded underline text.
2673 Each filter is called with three arguments: the transcoded data,
2674 as a string, the back-end, as a symbol, and the communication
2675 channel, as a plist. It must return a string or nil.")
2677 (defvar org-export-filter-verbatim-functions nil
2678 "List of functions applied to transcoded verbatim text.
2679 Each filter is called with three arguments: the transcoded data,
2680 as a string, the back-end, as a symbol, and the communication
2681 channel, as a plist. It must return a string or nil.")
2684 ;;;; Filters Tools
2686 ;; Internal function `org-export-install-filters' installs filters
2687 ;; hard-coded in back-ends (developer filters) and filters from global
2688 ;; variables (user filters) in the communication channel.
2690 ;; Internal function `org-export-filter-apply-functions' takes care
2691 ;; about applying each filter in order to a given data. It ignores
2692 ;; filters returning a nil value but stops whenever a filter returns
2693 ;; an empty string.
2695 (defun org-export-filter-apply-functions (filters value info)
2696 "Call every function in FILTERS.
2698 Functions are called with arguments VALUE, current export
2699 back-end and INFO. A function returning a nil value will be
2700 skipped. If it returns the empty string, the process ends and
2701 VALUE is ignored.
2703 Call is done in a LIFO fashion, to be sure that developer
2704 specified filters, if any, are called first."
2705 (catch 'exit
2706 (dolist (filter filters value)
2707 (let ((result (funcall filter value (plist-get info :back-end) info)))
2708 (cond ((not result) value)
2709 ((equal value "") (throw 'exit nil))
2710 (t (setq value result)))))))
2712 (defun org-export-install-filters (info)
2713 "Install filters properties in communication channel.
2714 INFO is a plist containing the current communication channel.
2715 Return the updated communication channel."
2716 (let (plist)
2717 ;; Install user-defined filters with `org-export-filters-alist'
2718 ;; and filters already in INFO (through ext-plist mechanism).
2719 (mapc (lambda (p)
2720 (let* ((prop (car p))
2721 (info-value (plist-get info prop))
2722 (default-value (symbol-value (cdr p))))
2723 (setq plist
2724 (plist-put plist prop
2725 ;; Filters in INFO will be called
2726 ;; before those user provided.
2727 (append (if (listp info-value) info-value
2728 (list info-value))
2729 default-value)))))
2730 org-export-filters-alist)
2731 ;; Prepend back-end specific filters to that list.
2732 (mapc (lambda (p)
2733 ;; Single values get consed, lists are appended.
2734 (let ((key (car p)) (value (cdr p)))
2735 (when value
2736 (setq plist
2737 (plist-put
2738 plist key
2739 (if (atom value) (cons value (plist-get plist key))
2740 (append value (plist-get plist key))))))))
2741 (org-export-backend-filters (plist-get info :back-end)))
2742 ;; Return new communication channel.
2743 (org-combine-plists info plist)))
2747 ;;; Core functions
2749 ;; This is the room for the main function, `org-export-as', along with
2750 ;; its derivatives, `org-export-to-buffer', `org-export-to-file' and
2751 ;; `org-export-string-as'. They differ either by the way they output
2752 ;; the resulting code (for the first two) or by the input type (for
2753 ;; the latter). `org-export--copy-to-kill-ring-p' determines if
2754 ;; output of these function should be added to kill ring.
2756 ;; `org-export-output-file-name' is an auxiliary function meant to be
2757 ;; used with `org-export-to-file'. With a given extension, it tries
2758 ;; to provide a canonical file name to write export output to.
2760 ;; Note that `org-export-as' doesn't really parse the current buffer,
2761 ;; but a copy of it (with the same buffer-local variables and
2762 ;; visibility), where macros and include keywords are expanded and
2763 ;; Babel blocks are executed, if appropriate.
2764 ;; `org-export-with-buffer-copy' macro prepares that copy.
2766 ;; File inclusion is taken care of by
2767 ;; `org-export-expand-include-keyword' and
2768 ;; `org-export--prepare-file-contents'. Structure wise, including
2769 ;; a whole Org file in a buffer often makes little sense. For
2770 ;; example, if the file contains a headline and the include keyword
2771 ;; was within an item, the item should contain the headline. That's
2772 ;; why file inclusion should be done before any structure can be
2773 ;; associated to the file, that is before parsing.
2775 ;; `org-export-insert-default-template' is a command to insert
2776 ;; a default template (or a back-end specific template) at point or in
2777 ;; current subtree.
2779 (defun org-export-copy-buffer ()
2780 "Return a copy of the current buffer.
2781 The copy preserves Org buffer-local variables, visibility and
2782 narrowing."
2783 (let ((copy-buffer-fun (org-export--generate-copy-script (current-buffer)))
2784 (new-buf (generate-new-buffer (buffer-name))))
2785 (with-current-buffer new-buf
2786 (funcall copy-buffer-fun)
2787 (set-buffer-modified-p nil))
2788 new-buf))
2790 (defmacro org-export-with-buffer-copy (&rest body)
2791 "Apply BODY in a copy of the current buffer.
2792 The copy preserves local variables, visibility and contents of
2793 the original buffer. Point is at the beginning of the buffer
2794 when BODY is applied."
2795 (declare (debug t))
2796 (org-with-gensyms (buf-copy)
2797 `(let ((,buf-copy (org-export-copy-buffer)))
2798 (unwind-protect
2799 (with-current-buffer ,buf-copy
2800 (goto-char (point-min))
2801 (progn ,@body))
2802 (and (buffer-live-p ,buf-copy)
2803 ;; Kill copy without confirmation.
2804 (progn (with-current-buffer ,buf-copy
2805 (restore-buffer-modified-p nil))
2806 (kill-buffer ,buf-copy)))))))
2808 (defun org-export--generate-copy-script (buffer)
2809 "Generate a function duplicating BUFFER.
2811 The copy will preserve local variables, visibility, contents and
2812 narrowing of the original buffer. If a region was active in
2813 BUFFER, contents will be narrowed to that region instead.
2815 The resulting function can be evaled at a later time, from
2816 another buffer, effectively cloning the original buffer there.
2818 The function assumes BUFFER's major mode is `org-mode'."
2819 (with-current-buffer buffer
2820 `(lambda ()
2821 (let ((inhibit-modification-hooks t))
2822 ;; Set major mode. Ignore `org-mode-hook' as it has been run
2823 ;; already in BUFFER.
2824 (let ((org-mode-hook nil) (org-inhibit-startup t)) (org-mode))
2825 ;; Copy specific buffer local variables and variables set
2826 ;; through BIND keywords.
2827 ,@(let ((bound-variables (org-export--list-bound-variables))
2828 vars)
2829 (dolist (entry (buffer-local-variables (buffer-base-buffer)) vars)
2830 (when (consp entry)
2831 (let ((var (car entry))
2832 (val (cdr entry)))
2833 (and (not (eq var 'org-font-lock-keywords))
2834 (or (memq var
2835 '(default-directory
2836 buffer-file-name
2837 buffer-file-coding-system))
2838 (assq var bound-variables)
2839 (string-match "^\\(org-\\|orgtbl-\\)"
2840 (symbol-name var)))
2841 ;; Skip unreadable values, as they cannot be
2842 ;; sent to external process.
2843 (or (not val) (ignore-errors (read (format "%S" val))))
2844 (push `(set (make-local-variable (quote ,var))
2845 (quote ,val))
2846 vars))))))
2847 ;; Whole buffer contents.
2848 (insert
2849 ,(org-with-wide-buffer
2850 (buffer-substring-no-properties
2851 (point-min) (point-max))))
2852 ;; Narrowing.
2853 ,(if (org-region-active-p)
2854 `(narrow-to-region ,(region-beginning) ,(region-end))
2855 `(narrow-to-region ,(point-min) ,(point-max)))
2856 ;; Current position of point.
2857 (goto-char ,(point))
2858 ;; Overlays with invisible property.
2859 ,@(let (ov-set)
2860 (mapc
2861 (lambda (ov)
2862 (let ((invis-prop (overlay-get ov 'invisible)))
2863 (when invis-prop
2864 (push `(overlay-put
2865 (make-overlay ,(overlay-start ov)
2866 ,(overlay-end ov))
2867 'invisible (quote ,invis-prop))
2868 ov-set))))
2869 (overlays-in (point-min) (point-max)))
2870 ov-set)))))
2872 ;;;###autoload
2873 (defun org-export-as
2874 (backend &optional subtreep visible-only body-only ext-plist)
2875 "Transcode current Org buffer into BACKEND code.
2877 If narrowing is active in the current buffer, only transcode its
2878 narrowed part.
2880 If a region is active, transcode that region.
2882 When optional argument SUBTREEP is non-nil, transcode the
2883 sub-tree at point, extracting information from the headline
2884 properties first.
2886 When optional argument VISIBLE-ONLY is non-nil, don't export
2887 contents of hidden elements.
2889 When optional argument BODY-ONLY is non-nil, only return body
2890 code, without surrounding template.
2892 Optional argument EXT-PLIST, when provided, is a property list
2893 with external parameters overriding Org default settings, but
2894 still inferior to file-local settings.
2896 Return code as a string."
2897 (org-export-barf-if-invalid-backend backend)
2898 (save-excursion
2899 (save-restriction
2900 ;; Narrow buffer to an appropriate region or subtree for
2901 ;; parsing. If parsing subtree, be sure to remove main headline
2902 ;; too.
2903 (cond ((org-region-active-p)
2904 (narrow-to-region (region-beginning) (region-end)))
2905 (subtreep
2906 (org-narrow-to-subtree)
2907 (goto-char (point-min))
2908 (forward-line)
2909 (narrow-to-region (point) (point-max))))
2910 ;; Initialize communication channel with original buffer
2911 ;; attributes, unavailable in its copy.
2912 (let ((info (org-combine-plists
2913 (list :export-options
2914 (delq nil
2915 (list (and subtreep 'subtree)
2916 (and visible-only 'visible-only)
2917 (and body-only 'body-only))))
2918 (org-export--get-buffer-attributes)))
2919 tree)
2920 ;; Update communication channel and get parse tree. Buffer
2921 ;; isn't parsed directly. Instead, a temporary copy is
2922 ;; created, where include keywords, macros are expanded and
2923 ;; code blocks are evaluated.
2924 (org-export-with-buffer-copy
2925 ;; Run first hook with current back-end as argument.
2926 (run-hook-with-args 'org-export-before-processing-hook backend)
2927 (org-export-expand-include-keyword)
2928 ;; Update macro templates since #+INCLUDE keywords might have
2929 ;; added some new ones.
2930 (org-macro-initialize-templates)
2931 (org-macro-replace-all org-macro-templates)
2932 (org-export-execute-babel-code)
2933 ;; Update radio targets since keyword inclusion might have
2934 ;; added some more.
2935 (org-update-radio-target-regexp)
2936 ;; Run last hook with current back-end as argument.
2937 (goto-char (point-min))
2938 (save-excursion
2939 (run-hook-with-args 'org-export-before-parsing-hook backend))
2940 ;; Update communication channel with environment. Also
2941 ;; install user's and developer's filters.
2942 (setq info
2943 (org-export-install-filters
2944 (org-combine-plists
2945 info (org-export-get-environment backend subtreep ext-plist))))
2946 ;; Expand export-specific set of macros: {{{author}}},
2947 ;; {{{date}}}, {{{email}}} and {{{title}}}. It must be done
2948 ;; once regular macros have been expanded, since document
2949 ;; keywords may contain one of them.
2950 (org-macro-replace-all
2951 (list (cons "author"
2952 (org-element-interpret-data (plist-get info :author)))
2953 (cons "date"
2954 (org-element-interpret-data (plist-get info :date)))
2955 ;; EMAIL is not a parsed keyword: store it as-is.
2956 (cons "email" (or (plist-get info :email) ""))
2957 (cons "title"
2958 (org-element-interpret-data (plist-get info :title)))))
2959 ;; Call options filters and update export options. We do not
2960 ;; use `org-export-filter-apply-functions' here since the
2961 ;; arity of such filters is different.
2962 (dolist (filter (plist-get info :filter-options))
2963 (let ((result (funcall filter info backend)))
2964 (when result (setq info result))))
2965 ;; Parse buffer and call parse-tree filter on it.
2966 (setq tree
2967 (org-export-filter-apply-functions
2968 (plist-get info :filter-parse-tree)
2969 (org-element-parse-buffer nil visible-only) info))
2970 ;; Now tree is complete, compute its properties and add them
2971 ;; to communication channel.
2972 (setq info
2973 (org-combine-plists
2974 info (org-export-collect-tree-properties tree info)))
2975 ;; Eventually transcode TREE. Wrap the resulting string into
2976 ;; a template.
2977 (let* ((body (org-element-normalize-string
2978 (or (org-export-data tree info) "")))
2979 (inner-template (cdr (assq 'inner-template
2980 (plist-get info :translate-alist))))
2981 (full-body (if (not (functionp inner-template)) body
2982 (funcall inner-template body info)))
2983 (template (cdr (assq 'template
2984 (plist-get info :translate-alist)))))
2985 ;; Remove all text properties since they cannot be
2986 ;; retrieved from an external process. Finally call
2987 ;; final-output filter and return result.
2988 (org-no-properties
2989 (org-export-filter-apply-functions
2990 (plist-get info :filter-final-output)
2991 (if (or (not (functionp template)) body-only) full-body
2992 (funcall template full-body info))
2993 info))))))))
2995 ;;;###autoload
2996 (defun org-export-to-buffer
2997 (backend buffer &optional subtreep visible-only body-only ext-plist)
2998 "Call `org-export-as' with output to a specified buffer.
3000 BACKEND is the back-end used for transcoding, as a symbol.
3002 BUFFER is the output buffer. If it already exists, it will be
3003 erased first, otherwise, it will be created.
3005 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
3006 EXT-PLIST are similar to those used in `org-export-as', which
3007 see.
3009 Depending on `org-export-copy-to-kill-ring', add buffer contents
3010 to kill ring. Return buffer."
3011 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist))
3012 (buffer (get-buffer-create buffer)))
3013 (with-current-buffer buffer
3014 (erase-buffer)
3015 (insert out)
3016 (goto-char (point-min)))
3017 ;; Maybe add buffer contents to kill ring.
3018 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p out))
3019 (org-kill-new out))
3020 ;; Return buffer.
3021 buffer))
3023 ;;;###autoload
3024 (defun org-export-to-file
3025 (backend file &optional subtreep visible-only body-only ext-plist)
3026 "Call `org-export-as' with output to a specified file.
3028 BACKEND is the back-end used for transcoding, as a symbol. FILE
3029 is the name of the output file, as a string.
3031 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
3032 EXT-PLIST are similar to those used in `org-export-as', which
3033 see.
3035 Depending on `org-export-copy-to-kill-ring', add file contents
3036 to kill ring. Return output file's name."
3037 ;; Checks for FILE permissions. `write-file' would do the same, but
3038 ;; we'd rather avoid needless transcoding of parse tree.
3039 (unless (file-writable-p file) (error "Output file not writable"))
3040 ;; Insert contents to a temporary buffer and write it to FILE.
3041 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist)))
3042 (with-temp-buffer
3043 (insert out)
3044 (let ((coding-system-for-write org-export-coding-system))
3045 (write-file file)))
3046 ;; Maybe add file contents to kill ring.
3047 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p out))
3048 (org-kill-new out)))
3049 ;; Return full path.
3050 file)
3052 ;;;###autoload
3053 (defun org-export-string-as (string backend &optional body-only ext-plist)
3054 "Transcode STRING into BACKEND code.
3056 When optional argument BODY-ONLY is non-nil, only return body
3057 code, without preamble nor postamble.
3059 Optional argument EXT-PLIST, when provided, is a property list
3060 with external parameters overriding Org default settings, but
3061 still inferior to file-local settings.
3063 Return code as a string."
3064 (with-temp-buffer
3065 (insert string)
3066 (let ((org-inhibit-startup t)) (org-mode))
3067 (org-export-as backend nil nil body-only ext-plist)))
3069 ;;;###autoload
3070 (defun org-export-replace-region-by (backend)
3071 "Replace the active region by its export to BACKEND."
3072 (if (not (org-region-active-p))
3073 (user-error "No active region to replace")
3074 (let* ((beg (region-beginning))
3075 (end (region-end))
3076 (str (buffer-substring beg end)) rpl)
3077 (setq rpl (org-export-string-as str backend t))
3078 (delete-region beg end)
3079 (insert rpl))))
3081 ;;;###autoload
3082 (defun org-export-insert-default-template (&optional backend subtreep)
3083 "Insert all export keywords with default values at beginning of line.
3085 BACKEND is a symbol representing the export back-end for which
3086 specific export options should be added to the template, or
3087 `default' for default template. When it is nil, the user will be
3088 prompted for a category.
3090 If SUBTREEP is non-nil, export configuration will be set up
3091 locally for the subtree through node properties."
3092 (interactive)
3093 (unless (derived-mode-p 'org-mode) (user-error "Not in an Org mode buffer"))
3094 (when (and subtreep (org-before-first-heading-p))
3095 (user-error "No subtree to set export options for"))
3096 (let ((node (and subtreep (save-excursion (org-back-to-heading t) (point))))
3097 (backend (or backend
3098 (intern
3099 (org-completing-read
3100 "Options category: "
3101 (cons "default"
3102 (mapcar (lambda (b) (symbol-name (car b)))
3103 org-export-registered-backends))))))
3104 options keywords)
3105 ;; Populate OPTIONS and KEYWORDS.
3106 (dolist (entry (if (eq backend 'default) org-export-options-alist
3107 (org-export-backend-options backend)))
3108 (let ((keyword (nth 1 entry))
3109 (option (nth 2 entry)))
3110 (cond
3111 (keyword (unless (assoc keyword keywords)
3112 (let ((value
3113 (if (eq (nth 4 entry) 'split)
3114 (mapconcat 'identity (eval (nth 3 entry)) " ")
3115 (eval (nth 3 entry)))))
3116 (push (cons keyword value) keywords))))
3117 (option (unless (assoc option options)
3118 (push (cons option (eval (nth 3 entry))) options))))))
3119 ;; Move to an appropriate location in order to insert options.
3120 (unless subtreep (beginning-of-line))
3121 ;; First get TITLE, DATE, AUTHOR and EMAIL if they belong to the
3122 ;; list of available keywords.
3123 (when (assoc "TITLE" keywords)
3124 (let ((title
3125 (or (let ((visited-file (buffer-file-name (buffer-base-buffer))))
3126 (and visited-file
3127 (file-name-sans-extension
3128 (file-name-nondirectory visited-file))))
3129 (buffer-name (buffer-base-buffer)))))
3130 (if (not subtreep) (insert (format "#+TITLE: %s\n" title))
3131 (org-entry-put node "EXPORT_TITLE" title))))
3132 (when (assoc "DATE" keywords)
3133 (let ((date (with-temp-buffer (org-insert-time-stamp (current-time)))))
3134 (if (not subtreep) (insert "#+DATE: " date "\n")
3135 (org-entry-put node "EXPORT_DATE" date))))
3136 (when (assoc "AUTHOR" keywords)
3137 (let ((author (cdr (assoc "AUTHOR" keywords))))
3138 (if subtreep (org-entry-put node "EXPORT_AUTHOR" author)
3139 (insert
3140 (format "#+AUTHOR:%s\n"
3141 (if (not (org-string-nw-p author)) ""
3142 (concat " " author)))))))
3143 (when (assoc "EMAIL" keywords)
3144 (let ((email (cdr (assoc "EMAIL" keywords))))
3145 (if subtreep (org-entry-put node "EXPORT_EMAIL" email)
3146 (insert
3147 (format "#+EMAIL:%s\n"
3148 (if (not (org-string-nw-p email)) ""
3149 (concat " " email)))))))
3150 ;; Then (multiple) OPTIONS lines. Never go past fill-column.
3151 (when options
3152 (let ((items
3153 (mapcar
3154 (lambda (opt)
3155 (format "%s:%s" (car opt) (format "%s" (cdr opt))))
3156 (sort options (lambda (k1 k2) (string< (car k1) (car k2)))))))
3157 (if subtreep
3158 (org-entry-put
3159 node "EXPORT_OPTIONS" (mapconcat 'identity items " "))
3160 (while items
3161 (insert "#+OPTIONS:")
3162 (let ((width 10))
3163 (while (and items
3164 (< (+ width (length (car items)) 1) fill-column))
3165 (let ((item (pop items)))
3166 (insert " " item)
3167 (incf width (1+ (length item))))))
3168 (insert "\n")))))
3169 ;; And the rest of keywords.
3170 (dolist (key (sort keywords (lambda (k1 k2) (string< (car k1) (car k2)))))
3171 (unless (member (car key) '("TITLE" "DATE" "AUTHOR" "EMAIL"))
3172 (let ((val (cdr key)))
3173 (if subtreep (org-entry-put node (concat "EXPORT_" (car key)) val)
3174 (insert
3175 (format "#+%s:%s\n"
3176 (car key)
3177 (if (org-string-nw-p val) (format " %s" val) "")))))))))
3179 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
3180 "Return output file's name according to buffer specifications.
3182 EXTENSION is a string representing the output file extension,
3183 with the leading dot.
3185 With a non-nil optional argument SUBTREEP, try to determine
3186 output file's name by looking for \"EXPORT_FILE_NAME\" property
3187 of subtree at point.
3189 When optional argument PUB-DIR is set, use it as the publishing
3190 directory.
3192 When optional argument VISIBLE-ONLY is non-nil, don't export
3193 contents of hidden elements.
3195 Return file name as a string."
3196 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
3197 (base-name
3198 ;; File name may come from EXPORT_FILE_NAME subtree
3199 ;; property, assuming point is at beginning of said
3200 ;; sub-tree.
3201 (file-name-sans-extension
3202 (or (and subtreep
3203 (org-entry-get
3204 (save-excursion
3205 (ignore-errors (org-back-to-heading) (point)))
3206 "EXPORT_FILE_NAME" t))
3207 ;; File name may be extracted from buffer's associated
3208 ;; file, if any.
3209 (and visited-file (file-name-nondirectory visited-file))
3210 ;; Can't determine file name on our own: Ask user.
3211 (let ((read-file-name-function
3212 (and org-completion-use-ido 'ido-read-file-name)))
3213 (read-file-name
3214 "Output file: " pub-dir nil nil nil
3215 (lambda (name)
3216 (string= (file-name-extension name t) extension)))))))
3217 (output-file
3218 ;; Build file name. Enforce EXTENSION over whatever user
3219 ;; may have come up with. PUB-DIR, if defined, always has
3220 ;; precedence over any provided path.
3221 (cond
3222 (pub-dir
3223 (concat (file-name-as-directory pub-dir)
3224 (file-name-nondirectory base-name)
3225 extension))
3226 ((file-name-absolute-p base-name) (concat base-name extension))
3227 (t (concat (file-name-as-directory ".") base-name extension)))))
3228 ;; If writing to OUTPUT-FILE would overwrite original file, append
3229 ;; EXTENSION another time to final name.
3230 (if (and visited-file (org-file-equal-p visited-file output-file))
3231 (concat output-file extension)
3232 output-file)))
3234 (defun org-export-expand-include-keyword (&optional included dir)
3235 "Expand every include keyword in buffer.
3236 Optional argument INCLUDED is a list of included file names along
3237 with their line restriction, when appropriate. It is used to
3238 avoid infinite recursion. Optional argument DIR is the current
3239 working directory. It is used to properly resolve relative
3240 paths."
3241 (let ((case-fold-search t))
3242 (goto-char (point-min))
3243 (while (re-search-forward "^[ \t]*#\\+INCLUDE: +\\(.*\\)[ \t]*$" nil t)
3244 (when (eq (org-element-type (save-match-data (org-element-at-point)))
3245 'keyword)
3246 (beginning-of-line)
3247 ;; Extract arguments from keyword's value.
3248 (let* ((value (match-string 1))
3249 (ind (org-get-indentation))
3250 (file (and (string-match "^\"\\(\\S-+\\)\"" value)
3251 (prog1 (expand-file-name (match-string 1 value) dir)
3252 (setq value (replace-match "" nil nil value)))))
3253 (lines
3254 (and (string-match
3255 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\"" value)
3256 (prog1 (match-string 1 value)
3257 (setq value (replace-match "" nil nil value)))))
3258 (env (cond ((string-match "\\<example\\>" value) 'example)
3259 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
3260 (match-string 1 value))))
3261 ;; Minimal level of included file defaults to the child
3262 ;; level of the current headline, if any, or one. It
3263 ;; only applies is the file is meant to be included as
3264 ;; an Org one.
3265 (minlevel
3266 (and (not env)
3267 (if (string-match ":minlevel +\\([0-9]+\\)" value)
3268 (prog1 (string-to-number (match-string 1 value))
3269 (setq value (replace-match "" nil nil value)))
3270 (let ((cur (org-current-level)))
3271 (if cur (1+ (org-reduced-level cur)) 1))))))
3272 ;; Remove keyword.
3273 (delete-region (point) (progn (forward-line) (point)))
3274 (cond
3275 ((not file) (error "Invalid syntax in INCLUDE keyword"))
3276 ((not (file-readable-p file)) (error "Cannot include file %s" file))
3277 ;; Check if files has already been parsed. Look after
3278 ;; inclusion lines too, as different parts of the same file
3279 ;; can be included too.
3280 ((member (list file lines) included)
3281 (error "Recursive file inclusion: %s" file))
3283 (cond
3284 ((eq env 'example)
3285 (insert
3286 (let ((ind-str (make-string ind ? ))
3287 (contents
3288 (org-escape-code-in-string
3289 (org-export--prepare-file-contents file lines))))
3290 (format "%s#+BEGIN_EXAMPLE\n%s%s#+END_EXAMPLE\n"
3291 ind-str contents ind-str))))
3292 ((stringp env)
3293 (insert
3294 (let ((ind-str (make-string ind ? ))
3295 (contents
3296 (org-escape-code-in-string
3297 (org-export--prepare-file-contents file lines))))
3298 (format "%s#+BEGIN_SRC %s\n%s%s#+END_SRC\n"
3299 ind-str env contents ind-str))))
3301 (insert
3302 (with-temp-buffer
3303 (let ((org-inhibit-startup t)) (org-mode))
3304 (insert
3305 (org-export--prepare-file-contents file lines ind minlevel))
3306 (org-export-expand-include-keyword
3307 (cons (list file lines) included)
3308 (file-name-directory file))
3309 (buffer-string))))))))))))
3311 (defun org-export--prepare-file-contents (file &optional lines ind minlevel)
3312 "Prepare the contents of FILE for inclusion and return them as a string.
3314 When optional argument LINES is a string specifying a range of
3315 lines, include only those lines.
3317 Optional argument IND, when non-nil, is an integer specifying the
3318 global indentation of returned contents. Since its purpose is to
3319 allow an included file to stay in the same environment it was
3320 created \(i.e. a list item), it doesn't apply past the first
3321 headline encountered.
3323 Optional argument MINLEVEL, when non-nil, is an integer
3324 specifying the level that any top-level headline in the included
3325 file should have."
3326 (with-temp-buffer
3327 (insert-file-contents file)
3328 (when lines
3329 (let* ((lines (split-string lines "-"))
3330 (lbeg (string-to-number (car lines)))
3331 (lend (string-to-number (cadr lines)))
3332 (beg (if (zerop lbeg) (point-min)
3333 (goto-char (point-min))
3334 (forward-line (1- lbeg))
3335 (point)))
3336 (end (if (zerop lend) (point-max)
3337 (goto-char (point-min))
3338 (forward-line (1- lend))
3339 (point))))
3340 (narrow-to-region beg end)))
3341 ;; Remove blank lines at beginning and end of contents. The logic
3342 ;; behind that removal is that blank lines around include keyword
3343 ;; override blank lines in included file.
3344 (goto-char (point-min))
3345 (org-skip-whitespace)
3346 (beginning-of-line)
3347 (delete-region (point-min) (point))
3348 (goto-char (point-max))
3349 (skip-chars-backward " \r\t\n")
3350 (forward-line)
3351 (delete-region (point) (point-max))
3352 ;; If IND is set, preserve indentation of include keyword until
3353 ;; the first headline encountered.
3354 (when ind
3355 (unless (eq major-mode 'org-mode)
3356 (let ((org-inhibit-startup t)) (org-mode)))
3357 (goto-char (point-min))
3358 (let ((ind-str (make-string ind ? )))
3359 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
3360 ;; Do not move footnote definitions out of column 0.
3361 (unless (and (looking-at org-footnote-definition-re)
3362 (eq (org-element-type (org-element-at-point))
3363 'footnote-definition))
3364 (insert ind-str))
3365 (forward-line))))
3366 ;; When MINLEVEL is specified, compute minimal level for headlines
3367 ;; in the file (CUR-MIN), and remove stars to each headline so
3368 ;; that headlines with minimal level have a level of MINLEVEL.
3369 (when minlevel
3370 (unless (eq major-mode 'org-mode)
3371 (let ((org-inhibit-startup t)) (org-mode)))
3372 (org-with-limited-levels
3373 (let ((levels (org-map-entries
3374 (lambda () (org-reduced-level (org-current-level))))))
3375 (when levels
3376 (let ((offset (- minlevel (apply 'min levels))))
3377 (unless (zerop offset)
3378 (when org-odd-levels-only (setq offset (* offset 2)))
3379 ;; Only change stars, don't bother moving whole
3380 ;; sections.
3381 (org-map-entries
3382 (lambda () (if (< offset 0) (delete-char (abs offset))
3383 (insert (make-string offset ?*)))))))))))
3384 (org-element-normalize-string (buffer-string))))
3386 (defun org-export-execute-babel-code ()
3387 "Execute every Babel code in the visible part of current buffer."
3388 ;; Get a pristine copy of current buffer so Babel references can be
3389 ;; properly resolved.
3390 (let ((reference (org-export-copy-buffer)))
3391 (unwind-protect (let ((org-current-export-file reference))
3392 (org-babel-exp-process-buffer))
3393 (kill-buffer reference))))
3395 (defun org-export--copy-to-kill-ring-p ()
3396 "Return a non-nil value when output should be added to the kill ring.
3397 See also `org-export-copy-to-kill-ring'."
3398 (if (eq org-export-copy-to-kill-ring 'if-interactive)
3399 (not (or executing-kbd-macro noninteractive))
3400 (eq org-export-copy-to-kill-ring t)))
3404 ;;; Tools For Back-Ends
3406 ;; A whole set of tools is available to help build new exporters. Any
3407 ;; function general enough to have its use across many back-ends
3408 ;; should be added here.
3410 ;;;; For Affiliated Keywords
3412 ;; `org-export-read-attribute' reads a property from a given element
3413 ;; as a plist. It can be used to normalize affiliated keywords'
3414 ;; syntax.
3416 ;; Since captions can span over multiple lines and accept dual values,
3417 ;; their internal representation is a bit tricky. Therefore,
3418 ;; `org-export-get-caption' transparently returns a given element's
3419 ;; caption as a secondary string.
3421 (defun org-export-read-attribute (attribute element &optional property)
3422 "Turn ATTRIBUTE property from ELEMENT into a plist.
3424 When optional argument PROPERTY is non-nil, return the value of
3425 that property within attributes.
3427 This function assumes attributes are defined as \":keyword
3428 value\" pairs. It is appropriate for `:attr_html' like
3429 properties.
3431 All values will become strings except the empty string and
3432 \"nil\", which will become nil. Also, values containing only
3433 double quotes will be read as-is, which means that \"\" value
3434 will become the empty string."
3435 (let* ((prepare-value
3436 (lambda (str)
3437 (cond ((member str '(nil "" "nil")) nil)
3438 ((string-match "^\"\\(\"+\\)?\"$" str)
3439 (or (match-string 1 str) ""))
3440 (t str))))
3441 (attributes
3442 (let ((value (org-element-property attribute element)))
3443 (when value
3444 (let ((s (mapconcat 'identity value " ")) result)
3445 (while (string-match
3446 "\\(?:^\\|[ \t]+\\)\\(:[-a-zA-Z0-9_]+\\)\\([ \t]+\\|$\\)"
3448 (let ((value (substring s 0 (match-beginning 0))))
3449 (push (funcall prepare-value value) result))
3450 (push (intern (match-string 1 s)) result)
3451 (setq s (substring s (match-end 0))))
3452 ;; Ignore any string before first property with `cdr'.
3453 (cdr (nreverse (cons (funcall prepare-value s) result))))))))
3454 (if property (plist-get attributes property) attributes)))
3456 (defun org-export-get-caption (element &optional shortp)
3457 "Return caption from ELEMENT as a secondary string.
3459 When optional argument SHORTP is non-nil, return short caption,
3460 as a secondary string, instead.
3462 Caption lines are separated by a white space."
3463 (let ((full-caption (org-element-property :caption element)) caption)
3464 (dolist (line full-caption (cdr caption))
3465 (let ((cap (funcall (if shortp 'cdr 'car) line)))
3466 (when cap
3467 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
3470 ;;;; For Derived Back-ends
3472 ;; `org-export-with-backend' is a function allowing to locally use
3473 ;; another back-end to transcode some object or element. In a derived
3474 ;; back-end, it may be used as a fall-back function once all specific
3475 ;; cases have been treated.
3477 (defun org-export-with-backend (back-end data &optional contents info)
3478 "Call a transcoder from BACK-END on DATA.
3479 CONTENTS, when non-nil, is the transcoded contents of DATA
3480 element, as a string. INFO, when non-nil, is the communication
3481 channel used for export, as a plist.."
3482 (org-export-barf-if-invalid-backend back-end)
3483 (let ((type (org-element-type data)))
3484 (if (memq type '(nil org-data)) (error "No foreign transcoder available")
3485 (let ((transcoder
3486 (cdr (assq type (org-export-backend-translate-table back-end)))))
3487 (if (functionp transcoder) (funcall transcoder data contents info)
3488 (error "No foreign transcoder available"))))))
3491 ;;;; For Export Snippets
3493 ;; Every export snippet is transmitted to the back-end. Though, the
3494 ;; latter will only retain one type of export-snippet, ignoring
3495 ;; others, based on the former's target back-end. The function
3496 ;; `org-export-snippet-backend' returns that back-end for a given
3497 ;; export-snippet.
3499 (defun org-export-snippet-backend (export-snippet)
3500 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3501 Translation, with `org-export-snippet-translation-alist', is
3502 applied."
3503 (let ((back-end (org-element-property :back-end export-snippet)))
3504 (intern
3505 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3506 back-end))))
3509 ;;;; For Footnotes
3511 ;; `org-export-collect-footnote-definitions' is a tool to list
3512 ;; actually used footnotes definitions in the whole parse tree, or in
3513 ;; a headline, in order to add footnote listings throughout the
3514 ;; transcoded data.
3516 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3517 ;; back-ends, when they need to attach the footnote definition only to
3518 ;; the first occurrence of the corresponding label.
3520 ;; `org-export-get-footnote-definition' and
3521 ;; `org-export-get-footnote-number' provide easier access to
3522 ;; additional information relative to a footnote reference.
3524 (defun org-export-collect-footnote-definitions (data info)
3525 "Return an alist between footnote numbers, labels and definitions.
3527 DATA is the parse tree from which definitions are collected.
3528 INFO is the plist used as a communication channel.
3530 Definitions are sorted by order of references. They either
3531 appear as Org data or as a secondary string for inlined
3532 footnotes. Unreferenced definitions are ignored."
3533 (let* (num-alist
3534 collect-fn ; for byte-compiler.
3535 (collect-fn
3536 (function
3537 (lambda (data)
3538 ;; Collect footnote number, label and definition in DATA.
3539 (org-element-map data 'footnote-reference
3540 (lambda (fn)
3541 (when (org-export-footnote-first-reference-p fn info)
3542 (let ((def (org-export-get-footnote-definition fn info)))
3543 (push
3544 (list (org-export-get-footnote-number fn info)
3545 (org-element-property :label fn)
3546 def)
3547 num-alist)
3548 ;; Also search in definition for nested footnotes.
3549 (when (eq (org-element-property :type fn) 'standard)
3550 (funcall collect-fn def)))))
3551 ;; Don't enter footnote definitions since it will happen
3552 ;; when their first reference is found.
3553 info nil 'footnote-definition)))))
3554 (funcall collect-fn (plist-get info :parse-tree))
3555 (reverse num-alist)))
3557 (defun org-export-footnote-first-reference-p (footnote-reference info)
3558 "Non-nil when a footnote reference is the first one for its label.
3560 FOOTNOTE-REFERENCE is the footnote reference being considered.
3561 INFO is the plist used as a communication channel."
3562 (let ((label (org-element-property :label footnote-reference)))
3563 ;; Anonymous footnotes are always a first reference.
3564 (if (not label) t
3565 ;; Otherwise, return the first footnote with the same LABEL and
3566 ;; test if it is equal to FOOTNOTE-REFERENCE.
3567 (let* (search-refs ; for byte-compiler.
3568 (search-refs
3569 (function
3570 (lambda (data)
3571 (org-element-map data 'footnote-reference
3572 (lambda (fn)
3573 (cond
3574 ((string= (org-element-property :label fn) label)
3575 (throw 'exit fn))
3576 ;; If FN isn't inlined, be sure to traverse its
3577 ;; definition before resuming search. See
3578 ;; comments in `org-export-get-footnote-number'
3579 ;; for more information.
3580 ((eq (org-element-property :type fn) 'standard)
3581 (funcall search-refs
3582 (org-export-get-footnote-definition fn info)))))
3583 ;; Don't enter footnote definitions since it will
3584 ;; happen when their first reference is found.
3585 info 'first-match 'footnote-definition)))))
3586 (eq (catch 'exit (funcall search-refs (plist-get info :parse-tree)))
3587 footnote-reference)))))
3589 (defun org-export-get-footnote-definition (footnote-reference info)
3590 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3591 INFO is the plist used as a communication channel. If no such
3592 definition can be found, return the \"DEFINITION NOT FOUND\"
3593 string."
3594 (let ((label (org-element-property :label footnote-reference)))
3595 (or (org-element-property :inline-definition footnote-reference)
3596 (cdr (assoc label (plist-get info :footnote-definition-alist)))
3597 "DEFINITION NOT FOUND.")))
3599 (defun org-export-get-footnote-number (footnote info)
3600 "Return number associated to a footnote.
3602 FOOTNOTE is either a footnote reference or a footnote definition.
3603 INFO is the plist used as a communication channel."
3604 (let* ((label (org-element-property :label footnote))
3605 seen-refs
3606 search-ref ; For byte-compiler.
3607 (search-ref
3608 (function
3609 (lambda (data)
3610 ;; Search footnote references through DATA, filling
3611 ;; SEEN-REFS along the way.
3612 (org-element-map data 'footnote-reference
3613 (lambda (fn)
3614 (let ((fn-lbl (org-element-property :label fn)))
3615 (cond
3616 ;; Anonymous footnote match: return number.
3617 ((and (not fn-lbl) (eq fn footnote))
3618 (throw 'exit (1+ (length seen-refs))))
3619 ;; Labels match: return number.
3620 ((and label (string= label fn-lbl))
3621 (throw 'exit (1+ (length seen-refs))))
3622 ;; Anonymous footnote: it's always a new one.
3623 ;; Also, be sure to return nil from the `cond' so
3624 ;; `first-match' doesn't get us out of the loop.
3625 ((not fn-lbl) (push 'inline seen-refs) nil)
3626 ;; Label not seen so far: add it so SEEN-REFS.
3628 ;; Also search for subsequent references in
3629 ;; footnote definition so numbering follows
3630 ;; reading logic. Note that we don't have to care
3631 ;; about inline definitions, since
3632 ;; `org-element-map' already traverses them at the
3633 ;; right time.
3635 ;; Once again, return nil to stay in the loop.
3636 ((not (member fn-lbl seen-refs))
3637 (push fn-lbl seen-refs)
3638 (funcall search-ref
3639 (org-export-get-footnote-definition fn info))
3640 nil))))
3641 ;; Don't enter footnote definitions since it will
3642 ;; happen when their first reference is found.
3643 info 'first-match 'footnote-definition)))))
3644 (catch 'exit (funcall search-ref (plist-get info :parse-tree)))))
3647 ;;;; For Headlines
3649 ;; `org-export-get-relative-level' is a shortcut to get headline
3650 ;; level, relatively to the lower headline level in the parsed tree.
3652 ;; `org-export-get-headline-number' returns the section number of an
3653 ;; headline, while `org-export-number-to-roman' allows to convert it
3654 ;; to roman numbers.
3656 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3657 ;; `org-export-last-sibling-p' are three useful predicates when it
3658 ;; comes to fulfill the `:headline-levels' property.
3660 ;; `org-export-get-tags', `org-export-get-category' and
3661 ;; `org-export-get-node-property' extract useful information from an
3662 ;; headline or a parent headline. They all handle inheritance.
3664 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3665 ;; as a secondary string, suitable for table of contents. It falls
3666 ;; back onto default title.
3668 (defun org-export-get-relative-level (headline info)
3669 "Return HEADLINE relative level within current parsed tree.
3670 INFO is a plist holding contextual information."
3671 (+ (org-element-property :level headline)
3672 (or (plist-get info :headline-offset) 0)))
3674 (defun org-export-low-level-p (headline info)
3675 "Non-nil when HEADLINE is considered as low level.
3677 INFO is a plist used as a communication channel.
3679 A low level headlines has a relative level greater than
3680 `:headline-levels' property value.
3682 Return value is the difference between HEADLINE relative level
3683 and the last level being considered as high enough, or nil."
3684 (let ((limit (plist-get info :headline-levels)))
3685 (when (wholenump limit)
3686 (let ((level (org-export-get-relative-level headline info)))
3687 (and (> level limit) (- level limit))))))
3689 (defun org-export-get-headline-number (headline info)
3690 "Return HEADLINE numbering as a list of numbers.
3691 INFO is a plist holding contextual information."
3692 (cdr (assoc headline (plist-get info :headline-numbering))))
3694 (defun org-export-numbered-headline-p (headline info)
3695 "Return a non-nil value if HEADLINE element should be numbered.
3696 INFO is a plist used as a communication channel."
3697 (let ((sec-num (plist-get info :section-numbers))
3698 (level (org-export-get-relative-level headline info)))
3699 (if (wholenump sec-num) (<= level sec-num) sec-num)))
3701 (defun org-export-number-to-roman (n)
3702 "Convert integer N into a roman numeral."
3703 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3704 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3705 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3706 ( 1 . "I")))
3707 (res ""))
3708 (if (<= n 0)
3709 (number-to-string n)
3710 (while roman
3711 (if (>= n (caar roman))
3712 (setq n (- n (caar roman))
3713 res (concat res (cdar roman)))
3714 (pop roman)))
3715 res)))
3717 (defun org-export-get-tags (element info &optional tags inherited)
3718 "Return list of tags associated to ELEMENT.
3720 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3721 is a plist used as a communication channel.
3723 Select tags (see `org-export-select-tags') and exclude tags (see
3724 `org-export-exclude-tags') are removed from the list.
3726 When non-nil, optional argument TAGS should be a list of strings.
3727 Any tag belonging to this list will also be removed.
3729 When optional argument INHERITED is non-nil, tags can also be
3730 inherited from parent headlines and FILETAGS keywords."
3731 (org-remove-if
3732 (lambda (tag) (or (member tag (plist-get info :select-tags))
3733 (member tag (plist-get info :exclude-tags))
3734 (member tag tags)))
3735 (if (not inherited) (org-element-property :tags element)
3736 ;; Build complete list of inherited tags.
3737 (let ((current-tag-list (org-element-property :tags element)))
3738 (mapc
3739 (lambda (parent)
3740 (mapc
3741 (lambda (tag)
3742 (when (and (memq (org-element-type parent) '(headline inlinetask))
3743 (not (member tag current-tag-list)))
3744 (push tag current-tag-list)))
3745 (org-element-property :tags parent)))
3746 (org-export-get-genealogy element))
3747 ;; Add FILETAGS keywords and return results.
3748 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3750 (defun org-export-get-node-property (property blob &optional inherited)
3751 "Return node PROPERTY value for BLOB.
3753 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
3754 element or object.
3756 If optional argument INHERITED is non-nil, the value can be
3757 inherited from a parent headline.
3759 Return value is a string or nil."
3760 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3761 (org-export-get-parent-headline blob))))
3762 (if (not inherited) (org-element-property property blob)
3763 (let ((parent headline) value)
3764 (catch 'found
3765 (while parent
3766 (when (plist-member (nth 1 parent) property)
3767 (throw 'found (org-element-property property parent)))
3768 (setq parent (org-element-property :parent parent))))))))
3770 (defun org-export-get-category (blob info)
3771 "Return category for element or object BLOB.
3773 INFO is a plist used as a communication channel.
3775 CATEGORY is automatically inherited from a parent headline, from
3776 #+CATEGORY: keyword or created out of original file name. If all
3777 fail, the fall-back value is \"???\"."
3778 (or (let ((headline (if (eq (org-element-type blob) 'headline) blob
3779 (org-export-get-parent-headline blob))))
3780 ;; Almost like `org-export-node-property', but we cannot trust
3781 ;; `plist-member' as every headline has a `:CATEGORY'
3782 ;; property, would it be nil or equal to "???" (which has the
3783 ;; same meaning).
3784 (let ((parent headline) value)
3785 (catch 'found
3786 (while parent
3787 (let ((category (org-element-property :CATEGORY parent)))
3788 (and category (not (equal "???" category))
3789 (throw 'found category)))
3790 (setq parent (org-element-property :parent parent))))))
3791 (org-element-map (plist-get info :parse-tree) 'keyword
3792 (lambda (kwd)
3793 (when (equal (org-element-property :key kwd) "CATEGORY")
3794 (org-element-property :value kwd)))
3795 info 'first-match)
3796 (let ((file (plist-get info :input-file)))
3797 (and file (file-name-sans-extension (file-name-nondirectory file))))
3798 "???"))
3800 (defun org-export-get-alt-title (headline info)
3801 "Return alternative title for HEADLINE, as a secondary string.
3802 INFO is a plist used as a communication channel. If no optional
3803 title is defined, fall-back to the regular title."
3804 (or (org-element-property :alt-title headline)
3805 (org-element-property :title headline)))
3807 (defun org-export-first-sibling-p (headline info)
3808 "Non-nil when HEADLINE is the first sibling in its sub-tree.
3809 INFO is a plist used as a communication channel."
3810 (not (eq (org-element-type (org-export-get-previous-element headline info))
3811 'headline)))
3813 (defun org-export-last-sibling-p (headline info)
3814 "Non-nil when HEADLINE is the last sibling in its sub-tree.
3815 INFO is a plist used as a communication channel."
3816 (not (org-export-get-next-element headline info)))
3819 ;;;; For Keywords
3821 ;; `org-export-get-date' returns a date appropriate for the document
3822 ;; to about to be exported. In particular, it takes care of
3823 ;; `org-export-date-timestamp-format'.
3825 (defun org-export-get-date (info &optional fmt)
3826 "Return date value for the current document.
3828 INFO is a plist used as a communication channel. FMT, when
3829 non-nil, is a time format string that will be applied on the date
3830 if it consists in a single timestamp object. It defaults to
3831 `org-export-date-timestamp-format' when nil.
3833 A proper date can be a secondary string, a string or nil. It is
3834 meant to be translated with `org-export-data' or alike."
3835 (let ((date (plist-get info :date))
3836 (fmt (or fmt org-export-date-timestamp-format)))
3837 (cond ((not date) nil)
3838 ((and fmt
3839 (not (cdr date))
3840 (eq (org-element-type (car date)) 'timestamp))
3841 (org-timestamp-format (car date) fmt))
3842 (t date))))
3845 ;;;; For Links
3847 ;; `org-export-solidify-link-text' turns a string into a safer version
3848 ;; for links, replacing most non-standard characters with hyphens.
3850 ;; `org-export-get-coderef-format' returns an appropriate format
3851 ;; string for coderefs.
3853 ;; `org-export-inline-image-p' returns a non-nil value when the link
3854 ;; provided should be considered as an inline image.
3856 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
3857 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
3858 ;; returns an appropriate unique identifier when found, or nil.
3860 ;; `org-export-resolve-id-link' returns the first headline with
3861 ;; specified id or custom-id in parse tree, the path to the external
3862 ;; file with the id or nil when neither was found.
3864 ;; `org-export-resolve-coderef' associates a reference to a line
3865 ;; number in the element it belongs, or returns the reference itself
3866 ;; when the element isn't numbered.
3868 (defun org-export-solidify-link-text (s)
3869 "Take link text S and make a safe target out of it."
3870 (save-match-data
3871 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-:]+") "-")))
3873 (defun org-export-get-coderef-format (path desc)
3874 "Return format string for code reference link.
3875 PATH is the link path. DESC is its description."
3876 (save-match-data
3877 (cond ((not desc) "%s")
3878 ((string-match (regexp-quote (concat "(" path ")")) desc)
3879 (replace-match "%s" t t desc))
3880 (t desc))))
3882 (defun org-export-inline-image-p (link &optional rules)
3883 "Non-nil if LINK object points to an inline image.
3885 Optional argument is a set of RULES defining inline images. It
3886 is an alist where associations have the following shape:
3888 \(TYPE . REGEXP)
3890 Applying a rule means apply REGEXP against LINK's path when its
3891 type is TYPE. The function will return a non-nil value if any of
3892 the provided rules is non-nil. The default rule is
3893 `org-export-default-inline-image-rule'.
3895 This only applies to links without a description."
3896 (and (not (org-element-contents link))
3897 (let ((case-fold-search t)
3898 (rules (or rules org-export-default-inline-image-rule)))
3899 (catch 'exit
3900 (mapc
3901 (lambda (rule)
3902 (and (string= (org-element-property :type link) (car rule))
3903 (string-match (cdr rule)
3904 (org-element-property :path link))
3905 (throw 'exit t)))
3906 rules)
3907 ;; Return nil if no rule matched.
3908 nil))))
3910 (defun org-export-resolve-coderef (ref info)
3911 "Resolve a code reference REF.
3913 INFO is a plist used as a communication channel.
3915 Return associated line number in source code, or REF itself,
3916 depending on src-block or example element's switches."
3917 (org-element-map (plist-get info :parse-tree) '(example-block src-block)
3918 (lambda (el)
3919 (with-temp-buffer
3920 (insert (org-trim (org-element-property :value el)))
3921 (let* ((label-fmt (regexp-quote
3922 (or (org-element-property :label-fmt el)
3923 org-coderef-label-format)))
3924 (ref-re
3925 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
3926 (replace-regexp-in-string "%s" ref label-fmt nil t))))
3927 ;; Element containing REF is found. Resolve it to either
3928 ;; a label or a line number, as needed.
3929 (when (re-search-backward ref-re nil t)
3930 (cond
3931 ((org-element-property :use-labels el) ref)
3932 ((eq (org-element-property :number-lines el) 'continued)
3933 (+ (org-export-get-loc el info) (line-number-at-pos)))
3934 (t (line-number-at-pos)))))))
3935 info 'first-match))
3937 (defun org-export-resolve-fuzzy-link (link info)
3938 "Return LINK destination.
3940 INFO is a plist holding contextual information.
3942 Return value can be an object, an element, or nil:
3944 - If LINK path matches a target object (i.e. <<path>>) return it.
3946 - If LINK path exactly matches the name affiliated keyword
3947 \(i.e. #+NAME: path) of an element, return that element.
3949 - If LINK path exactly matches any headline name, return that
3950 element. If more than one headline share that name, priority
3951 will be given to the one with the closest common ancestor, if
3952 any, or the first one in the parse tree otherwise.
3954 - Otherwise, return nil.
3956 Assume LINK type is \"fuzzy\". White spaces are not
3957 significant."
3958 (let* ((raw-path (org-element-property :path link))
3959 (match-title-p (eq (aref raw-path 0) ?*))
3960 ;; Split PATH at white spaces so matches are space
3961 ;; insensitive.
3962 (path (org-split-string
3963 (if match-title-p (substring raw-path 1) raw-path))))
3964 (cond
3965 ;; First try to find a matching "<<path>>" unless user specified
3966 ;; he was looking for a headline (path starts with a "*"
3967 ;; character).
3968 ((and (not match-title-p)
3969 (org-element-map (plist-get info :parse-tree) 'target
3970 (lambda (blob)
3971 (and (equal (org-split-string (org-element-property :value blob))
3972 path)
3973 blob))
3974 info t)))
3975 ;; Then try to find an element with a matching "#+NAME: path"
3976 ;; affiliated keyword.
3977 ((and (not match-title-p)
3978 (org-element-map (plist-get info :parse-tree)
3979 org-element-all-elements
3980 (lambda (el)
3981 (let ((name (org-element-property :name el)))
3982 (when (and name (equal (org-split-string name) path)) el)))
3983 info 'first-match)))
3984 ;; Last case: link either points to a headline or to nothingness.
3985 ;; Try to find the source, with priority given to headlines with
3986 ;; the closest common ancestor. If such candidate is found,
3987 ;; return it, otherwise return nil.
3989 (let ((find-headline
3990 (function
3991 ;; Return first headline whose `:raw-value' property is
3992 ;; NAME in parse tree DATA, or nil. Statistics cookies
3993 ;; are ignored.
3994 (lambda (name data)
3995 (org-element-map data 'headline
3996 (lambda (headline)
3997 (when (equal (org-split-string
3998 (replace-regexp-in-string
3999 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
4000 (org-element-property :raw-value headline)))
4001 name)
4002 headline))
4003 info 'first-match)))))
4004 ;; Search among headlines sharing an ancestor with link, from
4005 ;; closest to farthest.
4006 (or (catch 'exit
4007 (mapc
4008 (lambda (parent)
4009 (when (eq (org-element-type parent) 'headline)
4010 (let ((foundp (funcall find-headline path parent)))
4011 (when foundp (throw 'exit foundp)))))
4012 (org-export-get-genealogy link)) nil)
4013 ;; No match with a common ancestor: try full parse-tree.
4014 (funcall find-headline path (plist-get info :parse-tree))))))))
4016 (defun org-export-resolve-id-link (link info)
4017 "Return headline referenced as LINK destination.
4019 INFO is a plist used as a communication channel.
4021 Return value can be the headline element matched in current parse
4022 tree, a file name or nil. Assume LINK type is either \"id\" or
4023 \"custom-id\"."
4024 (let ((id (org-element-property :path link)))
4025 ;; First check if id is within the current parse tree.
4026 (or (org-element-map (plist-get info :parse-tree) 'headline
4027 (lambda (headline)
4028 (when (or (string= (org-element-property :ID headline) id)
4029 (string= (org-element-property :CUSTOM_ID headline) id))
4030 headline))
4031 info 'first-match)
4032 ;; Otherwise, look for external files.
4033 (cdr (assoc id (plist-get info :id-alist))))))
4035 (defun org-export-resolve-radio-link (link info)
4036 "Return radio-target object referenced as LINK destination.
4038 INFO is a plist used as a communication channel.
4040 Return value can be a radio-target object or nil. Assume LINK
4041 has type \"radio\"."
4042 (let ((path (org-element-property :path link)))
4043 (org-element-map (plist-get info :parse-tree) 'radio-target
4044 (lambda (radio)
4045 (and (compare-strings
4046 (org-element-property :value radio) 0 nil path 0 nil t)
4047 radio))
4048 info 'first-match)))
4051 ;;;; For References
4053 ;; `org-export-get-ordinal' associates a sequence number to any object
4054 ;; or element.
4056 (defun org-export-get-ordinal (element info &optional types predicate)
4057 "Return ordinal number of an element or object.
4059 ELEMENT is the element or object considered. INFO is the plist
4060 used as a communication channel.
4062 Optional argument TYPES, when non-nil, is a list of element or
4063 object types, as symbols, that should also be counted in.
4064 Otherwise, only provided element's type is considered.
4066 Optional argument PREDICATE is a function returning a non-nil
4067 value if the current element or object should be counted in. It
4068 accepts two arguments: the element or object being considered and
4069 the plist used as a communication channel. This allows to count
4070 only a certain type of objects (i.e. inline images).
4072 Return value is a list of numbers if ELEMENT is a headline or an
4073 item. It is nil for keywords. It represents the footnote number
4074 for footnote definitions and footnote references. If ELEMENT is
4075 a target, return the same value as if ELEMENT was the closest
4076 table, item or headline containing the target. In any other
4077 case, return the sequence number of ELEMENT among elements or
4078 objects of the same type."
4079 ;; Ordinal of a target object refer to the ordinal of the closest
4080 ;; table, item, or headline containing the object.
4081 (when (eq (org-element-type element) 'target)
4082 (setq element
4083 (loop for parent in (org-export-get-genealogy element)
4084 when
4085 (memq
4086 (org-element-type parent)
4087 '(footnote-definition footnote-reference headline item
4088 table))
4089 return parent)))
4090 (case (org-element-type element)
4091 ;; Special case 1: A headline returns its number as a list.
4092 (headline (org-export-get-headline-number element info))
4093 ;; Special case 2: An item returns its number as a list.
4094 (item (let ((struct (org-element-property :structure element)))
4095 (org-list-get-item-number
4096 (org-element-property :begin element)
4097 struct
4098 (org-list-prevs-alist struct)
4099 (org-list-parents-alist struct))))
4100 ((footnote-definition footnote-reference)
4101 (org-export-get-footnote-number element info))
4102 (otherwise
4103 (let ((counter 0))
4104 ;; Increment counter until ELEMENT is found again.
4105 (org-element-map (plist-get info :parse-tree)
4106 (or types (org-element-type element))
4107 (lambda (el)
4108 (cond
4109 ((eq element el) (1+ counter))
4110 ((not predicate) (incf counter) nil)
4111 ((funcall predicate el info) (incf counter) nil)))
4112 info 'first-match)))))
4115 ;;;; For Src-Blocks
4117 ;; `org-export-get-loc' counts number of code lines accumulated in
4118 ;; src-block or example-block elements with a "+n" switch until
4119 ;; a given element, excluded. Note: "-n" switches reset that count.
4121 ;; `org-export-unravel-code' extracts source code (along with a code
4122 ;; references alist) from an `element-block' or `src-block' type
4123 ;; element.
4125 ;; `org-export-format-code' applies a formatting function to each line
4126 ;; of code, providing relative line number and code reference when
4127 ;; appropriate. Since it doesn't access the original element from
4128 ;; which the source code is coming, it expects from the code calling
4129 ;; it to know if lines should be numbered and if code references
4130 ;; should appear.
4132 ;; Eventually, `org-export-format-code-default' is a higher-level
4133 ;; function (it makes use of the two previous functions) which handles
4134 ;; line numbering and code references inclusion, and returns source
4135 ;; code in a format suitable for plain text or verbatim output.
4137 (defun org-export-get-loc (element info)
4138 "Return accumulated lines of code up to ELEMENT.
4140 INFO is the plist used as a communication channel.
4142 ELEMENT is excluded from count."
4143 (let ((loc 0))
4144 (org-element-map (plist-get info :parse-tree)
4145 `(src-block example-block ,(org-element-type element))
4146 (lambda (el)
4147 (cond
4148 ;; ELEMENT is reached: Quit the loop.
4149 ((eq el element))
4150 ;; Only count lines from src-block and example-block elements
4151 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
4152 ((not (memq (org-element-type el) '(src-block example-block))) nil)
4153 ((let ((linums (org-element-property :number-lines el)))
4154 (when linums
4155 ;; Accumulate locs or reset them.
4156 (let ((lines (org-count-lines
4157 (org-trim (org-element-property :value el)))))
4158 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
4159 ;; Return nil to stay in the loop.
4160 nil)))
4161 info 'first-match)
4162 ;; Return value.
4163 loc))
4165 (defun org-export-unravel-code (element)
4166 "Clean source code and extract references out of it.
4168 ELEMENT has either a `src-block' an `example-block' type.
4170 Return a cons cell whose CAR is the source code, cleaned from any
4171 reference and protective comma and CDR is an alist between
4172 relative line number (integer) and name of code reference on that
4173 line (string)."
4174 (let* ((line 0) refs
4175 ;; Get code and clean it. Remove blank lines at its
4176 ;; beginning and end.
4177 (code (let ((c (replace-regexp-in-string
4178 "\\`\\([ \t]*\n\\)+" ""
4179 (replace-regexp-in-string
4180 "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
4181 (org-element-property :value element)))))
4182 ;; If appropriate, remove global indentation.
4183 (if (or org-src-preserve-indentation
4184 (org-element-property :preserve-indent element))
4186 (org-remove-indentation c))))
4187 ;; Get format used for references.
4188 (label-fmt (regexp-quote
4189 (or (org-element-property :label-fmt element)
4190 org-coderef-label-format)))
4191 ;; Build a regexp matching a loc with a reference.
4192 (with-ref-re
4193 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
4194 (replace-regexp-in-string
4195 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
4196 ;; Return value.
4197 (cons
4198 ;; Code with references removed.
4199 (org-element-normalize-string
4200 (mapconcat
4201 (lambda (loc)
4202 (incf line)
4203 (if (not (string-match with-ref-re loc)) loc
4204 ;; Ref line: remove ref, and signal its position in REFS.
4205 (push (cons line (match-string 3 loc)) refs)
4206 (replace-match "" nil nil loc 1)))
4207 (org-split-string code "\n") "\n"))
4208 ;; Reference alist.
4209 refs)))
4211 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4212 "Format CODE by applying FUN line-wise and return it.
4214 CODE is a string representing the code to format. FUN is
4215 a function. It must accept three arguments: a line of
4216 code (string), the current line number (integer) or nil and the
4217 reference associated to the current line (string) or nil.
4219 Optional argument NUM-LINES can be an integer representing the
4220 number of code lines accumulated until the current code. Line
4221 numbers passed to FUN will take it into account. If it is nil,
4222 FUN's second argument will always be nil. This number can be
4223 obtained with `org-export-get-loc' function.
4225 Optional argument REF-ALIST can be an alist between relative line
4226 number (i.e. ignoring NUM-LINES) and the name of the code
4227 reference on it. If it is nil, FUN's third argument will always
4228 be nil. It can be obtained through the use of
4229 `org-export-unravel-code' function."
4230 (let ((--locs (org-split-string code "\n"))
4231 (--line 0))
4232 (org-element-normalize-string
4233 (mapconcat
4234 (lambda (--loc)
4235 (incf --line)
4236 (let ((--ref (cdr (assq --line ref-alist))))
4237 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4238 --locs "\n"))))
4240 (defun org-export-format-code-default (element info)
4241 "Return source code from ELEMENT, formatted in a standard way.
4243 ELEMENT is either a `src-block' or `example-block' element. INFO
4244 is a plist used as a communication channel.
4246 This function takes care of line numbering and code references
4247 inclusion. Line numbers, when applicable, appear at the
4248 beginning of the line, separated from the code by two white
4249 spaces. Code references, on the other hand, appear flushed to
4250 the right, separated by six white spaces from the widest line of
4251 code."
4252 ;; Extract code and references.
4253 (let* ((code-info (org-export-unravel-code element))
4254 (code (car code-info))
4255 (code-lines (org-split-string code "\n")))
4256 (if (null code-lines) ""
4257 (let* ((refs (and (org-element-property :retain-labels element)
4258 (cdr code-info)))
4259 ;; Handle line numbering.
4260 (num-start (case (org-element-property :number-lines element)
4261 (continued (org-export-get-loc element info))
4262 (new 0)))
4263 (num-fmt
4264 (and num-start
4265 (format "%%%ds "
4266 (length (number-to-string
4267 (+ (length code-lines) num-start))))))
4268 ;; Prepare references display, if required. Any reference
4269 ;; should start six columns after the widest line of code,
4270 ;; wrapped with parenthesis.
4271 (max-width
4272 (+ (apply 'max (mapcar 'length code-lines))
4273 (if (not num-start) 0 (length (format num-fmt num-start))))))
4274 (org-export-format-code
4275 code
4276 (lambda (loc line-num ref)
4277 (let ((number-str (and num-fmt (format num-fmt line-num))))
4278 (concat
4279 number-str
4281 (and ref
4282 (concat (make-string
4283 (- (+ 6 max-width)
4284 (+ (length loc) (length number-str))) ? )
4285 (format "(%s)" ref))))))
4286 num-start refs)))))
4289 ;;;; For Tables
4291 ;; `org-export-table-has-special-column-p' and and
4292 ;; `org-export-table-row-is-special-p' are predicates used to look for
4293 ;; meta-information about the table structure.
4295 ;; `org-table-has-header-p' tells when the rows before the first rule
4296 ;; should be considered as table's header.
4298 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4299 ;; and `org-export-table-cell-borders' extract information from
4300 ;; a table-cell element.
4302 ;; `org-export-table-dimensions' gives the number on rows and columns
4303 ;; in the table, ignoring horizontal rules and special columns.
4304 ;; `org-export-table-cell-address', given a table-cell object, returns
4305 ;; the absolute address of a cell. On the other hand,
4306 ;; `org-export-get-table-cell-at' does the contrary.
4308 ;; `org-export-table-cell-starts-colgroup-p',
4309 ;; `org-export-table-cell-ends-colgroup-p',
4310 ;; `org-export-table-row-starts-rowgroup-p',
4311 ;; `org-export-table-row-ends-rowgroup-p',
4312 ;; `org-export-table-row-starts-header-p' and
4313 ;; `org-export-table-row-ends-header-p' indicate position of current
4314 ;; row or cell within the table.
4316 (defun org-export-table-has-special-column-p (table)
4317 "Non-nil when TABLE has a special column.
4318 All special columns will be ignored during export."
4319 ;; The table has a special column when every first cell of every row
4320 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4321 ;; "*" "_" and "^". Though, do not consider a first row containing
4322 ;; only empty cells as special.
4323 (let ((special-column-p 'empty))
4324 (catch 'exit
4325 (mapc
4326 (lambda (row)
4327 (when (eq (org-element-property :type row) 'standard)
4328 (let ((value (org-element-contents
4329 (car (org-element-contents row)))))
4330 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4331 (setq special-column-p 'special))
4332 ((not value))
4333 (t (throw 'exit nil))))))
4334 (org-element-contents table))
4335 (eq special-column-p 'special))))
4337 (defun org-export-table-has-header-p (table info)
4338 "Non-nil when TABLE has a header.
4340 INFO is a plist used as a communication channel.
4342 A table has a header when it contains at least two row groups."
4343 (let ((rowgroup 1) row-flag)
4344 (org-element-map table 'table-row
4345 (lambda (row)
4346 (cond
4347 ((> rowgroup 1) t)
4348 ((and row-flag (eq (org-element-property :type row) 'rule))
4349 (incf rowgroup) (setq row-flag nil))
4350 ((and (not row-flag) (eq (org-element-property :type row) 'standard))
4351 (setq row-flag t) nil)))
4352 info)))
4354 (defun org-export-table-row-is-special-p (table-row info)
4355 "Non-nil if TABLE-ROW is considered special.
4357 INFO is a plist used as the communication channel.
4359 All special rows will be ignored during export."
4360 (when (eq (org-element-property :type table-row) 'standard)
4361 (let ((first-cell (org-element-contents
4362 (car (org-element-contents table-row)))))
4363 ;; A row is special either when...
4365 ;; ... it starts with a field only containing "/",
4366 (equal first-cell '("/"))
4367 ;; ... the table contains a special column and the row start
4368 ;; with a marking character among, "^", "_", "$" or "!",
4369 (and (org-export-table-has-special-column-p
4370 (org-export-get-parent table-row))
4371 (member first-cell '(("^") ("_") ("$") ("!"))))
4372 ;; ... it contains only alignment cookies and empty cells.
4373 (let ((special-row-p 'empty))
4374 (catch 'exit
4375 (mapc
4376 (lambda (cell)
4377 (let ((value (org-element-contents cell)))
4378 ;; Since VALUE is a secondary string, the following
4379 ;; checks avoid expanding it with `org-export-data'.
4380 (cond ((not value))
4381 ((and (not (cdr value))
4382 (stringp (car value))
4383 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4384 (car value)))
4385 (setq special-row-p 'cookie))
4386 (t (throw 'exit nil)))))
4387 (org-element-contents table-row))
4388 (eq special-row-p 'cookie)))))))
4390 (defun org-export-table-row-group (table-row info)
4391 "Return TABLE-ROW's group.
4393 INFO is a plist used as the communication channel.
4395 Return value is the group number, as an integer, or nil for
4396 special rows and table rules. Group 1 is also table's header."
4397 (unless (or (eq (org-element-property :type table-row) 'rule)
4398 (org-export-table-row-is-special-p table-row info))
4399 (let ((group 0) row-flag)
4400 (catch 'found
4401 (mapc
4402 (lambda (row)
4403 (cond
4404 ((and (eq (org-element-property :type row) 'standard)
4405 (not (org-export-table-row-is-special-p row info)))
4406 (unless row-flag (incf group) (setq row-flag t)))
4407 ((eq (org-element-property :type row) 'rule)
4408 (setq row-flag nil)))
4409 (when (eq table-row row) (throw 'found group)))
4410 (org-element-contents (org-export-get-parent table-row)))))))
4412 (defun org-export-table-cell-width (table-cell info)
4413 "Return TABLE-CELL contents width.
4415 INFO is a plist used as the communication channel.
4417 Return value is the width given by the last width cookie in the
4418 same column as TABLE-CELL, or nil."
4419 (let* ((row (org-export-get-parent table-cell))
4420 (column (let ((cells (org-element-contents row)))
4421 (- (length cells) (length (memq table-cell cells)))))
4422 (table (org-export-get-parent-table table-cell))
4423 cookie-width)
4424 (mapc
4425 (lambda (row)
4426 (cond
4427 ;; In a special row, try to find a width cookie at COLUMN.
4428 ((org-export-table-row-is-special-p row info)
4429 (let ((value (org-element-contents
4430 (elt (org-element-contents row) column))))
4431 ;; The following checks avoid expanding unnecessarily the
4432 ;; cell with `org-export-data'
4433 (when (and value
4434 (not (cdr value))
4435 (stringp (car value))
4436 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" (car value))
4437 (match-string 1 (car value)))
4438 (setq cookie-width
4439 (string-to-number (match-string 1 (car value)))))))
4440 ;; Ignore table rules.
4441 ((eq (org-element-property :type row) 'rule))))
4442 (org-element-contents table))
4443 ;; Return value.
4444 cookie-width))
4446 (defun org-export-table-cell-alignment (table-cell info)
4447 "Return TABLE-CELL contents alignment.
4449 INFO is a plist used as the communication channel.
4451 Return alignment as specified by the last alignment cookie in the
4452 same column as TABLE-CELL. If no such cookie is found, a default
4453 alignment value will be deduced from fraction of numbers in the
4454 column (see `org-table-number-fraction' for more information).
4455 Possible values are `left', `right' and `center'."
4456 (let* ((row (org-export-get-parent table-cell))
4457 (column (let ((cells (org-element-contents row)))
4458 (- (length cells) (length (memq table-cell cells)))))
4459 (table (org-export-get-parent-table table-cell))
4460 (number-cells 0)
4461 (total-cells 0)
4462 cookie-align
4463 previous-cell-number-p)
4464 (mapc
4465 (lambda (row)
4466 (cond
4467 ;; In a special row, try to find an alignment cookie at
4468 ;; COLUMN.
4469 ((org-export-table-row-is-special-p row info)
4470 (let ((value (org-element-contents
4471 (elt (org-element-contents row) column))))
4472 ;; Since VALUE is a secondary string, the following checks
4473 ;; avoid useless expansion through `org-export-data'.
4474 (when (and value
4475 (not (cdr value))
4476 (stringp (car value))
4477 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4478 (car value))
4479 (match-string 1 (car value)))
4480 (setq cookie-align (match-string 1 (car value))))))
4481 ;; Ignore table rules.
4482 ((eq (org-element-property :type row) 'rule))
4483 ;; In a standard row, check if cell's contents are expressing
4484 ;; some kind of number. Increase NUMBER-CELLS accordingly.
4485 ;; Though, don't bother if an alignment cookie has already
4486 ;; defined cell's alignment.
4487 ((not cookie-align)
4488 (let ((value (org-export-data
4489 (org-element-contents
4490 (elt (org-element-contents row) column))
4491 info)))
4492 (incf total-cells)
4493 ;; Treat an empty cell as a number if it follows a number
4494 (if (not (or (string-match org-table-number-regexp value)
4495 (and (string= value "") previous-cell-number-p)))
4496 (setq previous-cell-number-p nil)
4497 (setq previous-cell-number-p t)
4498 (incf number-cells))))))
4499 (org-element-contents table))
4500 ;; Return value. Alignment specified by cookies has precedence
4501 ;; over alignment deduced from cells contents.
4502 (cond ((equal cookie-align "l") 'left)
4503 ((equal cookie-align "r") 'right)
4504 ((equal cookie-align "c") 'center)
4505 ((>= (/ (float number-cells) total-cells) org-table-number-fraction)
4506 'right)
4507 (t 'left))))
4509 (defun org-export-table-cell-borders (table-cell info)
4510 "Return TABLE-CELL borders.
4512 INFO is a plist used as a communication channel.
4514 Return value is a list of symbols, or nil. Possible values are:
4515 `top', `bottom', `above', `below', `left' and `right'. Note:
4516 `top' (resp. `bottom') only happen for a cell in the first
4517 row (resp. last row) of the table, ignoring table rules, if any.
4519 Returned borders ignore special rows."
4520 (let* ((row (org-export-get-parent table-cell))
4521 (table (org-export-get-parent-table table-cell))
4522 borders)
4523 ;; Top/above border? TABLE-CELL has a border above when a rule
4524 ;; used to demarcate row groups can be found above. Hence,
4525 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4526 ;; another regular row has to be found above that rule.
4527 (let (rule-flag)
4528 (catch 'exit
4529 (mapc (lambda (row)
4530 (cond ((eq (org-element-property :type row) 'rule)
4531 (setq rule-flag t))
4532 ((not (org-export-table-row-is-special-p row info))
4533 (if rule-flag (throw 'exit (push 'above borders))
4534 (throw 'exit nil)))))
4535 ;; Look at every row before the current one.
4536 (cdr (memq row (reverse (org-element-contents table)))))
4537 ;; No rule above, or rule found starts the table (ignoring any
4538 ;; special row): TABLE-CELL is at the top of the table.
4539 (when rule-flag (push 'above borders))
4540 (push 'top borders)))
4541 ;; Bottom/below border? TABLE-CELL has a border below when next
4542 ;; non-regular row below is a rule.
4543 (let (rule-flag)
4544 (catch 'exit
4545 (mapc (lambda (row)
4546 (cond ((eq (org-element-property :type row) 'rule)
4547 (setq rule-flag t))
4548 ((not (org-export-table-row-is-special-p row info))
4549 (if rule-flag (throw 'exit (push 'below borders))
4550 (throw 'exit nil)))))
4551 ;; Look at every row after the current one.
4552 (cdr (memq row (org-element-contents table))))
4553 ;; No rule below, or rule found ends the table (modulo some
4554 ;; special row): TABLE-CELL is at the bottom of the table.
4555 (when rule-flag (push 'below borders))
4556 (push 'bottom borders)))
4557 ;; Right/left borders? They can only be specified by column
4558 ;; groups. Column groups are defined in a row starting with "/".
4559 ;; Also a column groups row only contains "<", "<>", ">" or blank
4560 ;; cells.
4561 (catch 'exit
4562 (let ((column (let ((cells (org-element-contents row)))
4563 (- (length cells) (length (memq table-cell cells))))))
4564 (mapc
4565 (lambda (row)
4566 (unless (eq (org-element-property :type row) 'rule)
4567 (when (equal (org-element-contents
4568 (car (org-element-contents row)))
4569 '("/"))
4570 (let ((column-groups
4571 (mapcar
4572 (lambda (cell)
4573 (let ((value (org-element-contents cell)))
4574 (when (member value '(("<") ("<>") (">") nil))
4575 (car value))))
4576 (org-element-contents row))))
4577 ;; There's a left border when previous cell, if
4578 ;; any, ends a group, or current one starts one.
4579 (when (or (and (not (zerop column))
4580 (member (elt column-groups (1- column))
4581 '(">" "<>")))
4582 (member (elt column-groups column) '("<" "<>")))
4583 (push 'left borders))
4584 ;; There's a right border when next cell, if any,
4585 ;; starts a group, or current one ends one.
4586 (when (or (and (/= (1+ column) (length column-groups))
4587 (member (elt column-groups (1+ column))
4588 '("<" "<>")))
4589 (member (elt column-groups column) '(">" "<>")))
4590 (push 'right borders))
4591 (throw 'exit nil)))))
4592 ;; Table rows are read in reverse order so last column groups
4593 ;; row has precedence over any previous one.
4594 (reverse (org-element-contents table)))))
4595 ;; Return value.
4596 borders))
4598 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
4599 "Non-nil when TABLE-CELL is at the beginning of a row group.
4600 INFO is a plist used as a communication channel."
4601 ;; A cell starts a column group either when it is at the beginning
4602 ;; of a row (or after the special column, if any) or when it has
4603 ;; a left border.
4604 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
4605 'identity info 'first-match)
4606 table-cell)
4607 (memq 'left (org-export-table-cell-borders table-cell info))))
4609 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
4610 "Non-nil when TABLE-CELL is at the end of a row group.
4611 INFO is a plist used as a communication channel."
4612 ;; A cell ends a column group either when it is at the end of a row
4613 ;; or when it has a right border.
4614 (or (eq (car (last (org-element-contents
4615 (org-export-get-parent table-cell))))
4616 table-cell)
4617 (memq 'right (org-export-table-cell-borders table-cell info))))
4619 (defun org-export-table-row-starts-rowgroup-p (table-row info)
4620 "Non-nil when TABLE-ROW is at the beginning of a column group.
4621 INFO is a plist used as a communication channel."
4622 (unless (or (eq (org-element-property :type table-row) 'rule)
4623 (org-export-table-row-is-special-p table-row info))
4624 (let ((borders (org-export-table-cell-borders
4625 (car (org-element-contents table-row)) info)))
4626 (or (memq 'top borders) (memq 'above borders)))))
4628 (defun org-export-table-row-ends-rowgroup-p (table-row info)
4629 "Non-nil when TABLE-ROW is at the end of a column group.
4630 INFO is a plist used as a communication channel."
4631 (unless (or (eq (org-element-property :type table-row) 'rule)
4632 (org-export-table-row-is-special-p table-row info))
4633 (let ((borders (org-export-table-cell-borders
4634 (car (org-element-contents table-row)) info)))
4635 (or (memq 'bottom borders) (memq 'below borders)))))
4637 (defun org-export-table-row-starts-header-p (table-row info)
4638 "Non-nil when TABLE-ROW is the first table header's row.
4639 INFO is a plist used as a communication channel."
4640 (and (org-export-table-has-header-p
4641 (org-export-get-parent-table table-row) info)
4642 (org-export-table-row-starts-rowgroup-p table-row info)
4643 (= (org-export-table-row-group table-row info) 1)))
4645 (defun org-export-table-row-ends-header-p (table-row info)
4646 "Non-nil when TABLE-ROW is the last table header's row.
4647 INFO is a plist used as a communication channel."
4648 (and (org-export-table-has-header-p
4649 (org-export-get-parent-table table-row) info)
4650 (org-export-table-row-ends-rowgroup-p table-row info)
4651 (= (org-export-table-row-group table-row info) 1)))
4653 (defun org-export-table-row-number (table-row info)
4654 "Return TABLE-ROW number.
4655 INFO is a plist used as a communication channel. Return value is
4656 zero-based and ignores separators. The function returns nil for
4657 special colums and separators."
4658 (when (and (eq (org-element-property :type table-row) 'standard)
4659 (not (org-export-table-row-is-special-p table-row info)))
4660 (let ((number 0))
4661 (org-element-map (org-export-get-parent-table table-row) 'table-row
4662 (lambda (row)
4663 (cond ((eq row table-row) number)
4664 ((eq (org-element-property :type row) 'standard)
4665 (incf number) nil)))
4666 info 'first-match))))
4668 (defun org-export-table-dimensions (table info)
4669 "Return TABLE dimensions.
4671 INFO is a plist used as a communication channel.
4673 Return value is a CONS like (ROWS . COLUMNS) where
4674 ROWS (resp. COLUMNS) is the number of exportable
4675 rows (resp. columns)."
4676 (let (first-row (columns 0) (rows 0))
4677 ;; Set number of rows, and extract first one.
4678 (org-element-map table 'table-row
4679 (lambda (row)
4680 (when (eq (org-element-property :type row) 'standard)
4681 (incf rows)
4682 (unless first-row (setq first-row row)))) info)
4683 ;; Set number of columns.
4684 (org-element-map first-row 'table-cell (lambda (cell) (incf columns)) info)
4685 ;; Return value.
4686 (cons rows columns)))
4688 (defun org-export-table-cell-address (table-cell info)
4689 "Return address of a regular TABLE-CELL object.
4691 TABLE-CELL is the cell considered. INFO is a plist used as
4692 a communication channel.
4694 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4695 zero-based index. Only exportable cells are considered. The
4696 function returns nil for other cells."
4697 (let* ((table-row (org-export-get-parent table-cell))
4698 (table (org-export-get-parent-table table-cell)))
4699 ;; Ignore cells in special rows or in special column.
4700 (unless (or (org-export-table-row-is-special-p table-row info)
4701 (and (org-export-table-has-special-column-p table)
4702 (eq (car (org-element-contents table-row)) table-cell)))
4703 (cons
4704 ;; Row number.
4705 (org-export-table-row-number (org-export-get-parent table-cell) info)
4706 ;; Column number.
4707 (let ((col-count 0))
4708 (org-element-map table-row 'table-cell
4709 (lambda (cell)
4710 (if (eq cell table-cell) col-count (incf col-count) nil))
4711 info 'first-match))))))
4713 (defun org-export-get-table-cell-at (address table info)
4714 "Return regular table-cell object at ADDRESS in TABLE.
4716 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4717 zero-based index. TABLE is a table type element. INFO is
4718 a plist used as a communication channel.
4720 If no table-cell, among exportable cells, is found at ADDRESS,
4721 return nil."
4722 (let ((column-pos (cdr address)) (column-count 0))
4723 (org-element-map
4724 ;; Row at (car address) or nil.
4725 (let ((row-pos (car address)) (row-count 0))
4726 (org-element-map table 'table-row
4727 (lambda (row)
4728 (cond ((eq (org-element-property :type row) 'rule) nil)
4729 ((= row-count row-pos) row)
4730 (t (incf row-count) nil)))
4731 info 'first-match))
4732 'table-cell
4733 (lambda (cell)
4734 (if (= column-count column-pos) cell
4735 (incf column-count) nil))
4736 info 'first-match)))
4739 ;;;; For Tables Of Contents
4741 ;; `org-export-collect-headlines' builds a list of all exportable
4742 ;; headline elements, maybe limited to a certain depth. One can then
4743 ;; easily parse it and transcode it.
4745 ;; Building lists of tables, figures or listings is quite similar.
4746 ;; Once the generic function `org-export-collect-elements' is defined,
4747 ;; `org-export-collect-tables', `org-export-collect-figures' and
4748 ;; `org-export-collect-listings' can be derived from it.
4750 (defun org-export-collect-headlines (info &optional n)
4751 "Collect headlines in order to build a table of contents.
4753 INFO is a plist used as a communication channel.
4755 When optional argument N is an integer, it specifies the depth of
4756 the table of contents. Otherwise, it is set to the value of the
4757 last headline level. See `org-export-headline-levels' for more
4758 information.
4760 Return a list of all exportable headlines as parsed elements.
4761 Footnote sections, if any, will be ignored."
4762 (unless (wholenump n) (setq n (plist-get info :headline-levels)))
4763 (org-element-map (plist-get info :parse-tree) 'headline
4764 (lambda (headline)
4765 (unless (org-element-property :footnote-section-p headline)
4766 ;; Strip contents from HEADLINE.
4767 (let ((relative-level (org-export-get-relative-level headline info)))
4768 (unless (> relative-level n) headline))))
4769 info))
4771 (defun org-export-collect-elements (type info &optional predicate)
4772 "Collect referenceable elements of a determined type.
4774 TYPE can be a symbol or a list of symbols specifying element
4775 types to search. Only elements with a caption are collected.
4777 INFO is a plist used as a communication channel.
4779 When non-nil, optional argument PREDICATE is a function accepting
4780 one argument, an element of type TYPE. It returns a non-nil
4781 value when that element should be collected.
4783 Return a list of all elements found, in order of appearance."
4784 (org-element-map (plist-get info :parse-tree) type
4785 (lambda (element)
4786 (and (org-element-property :caption element)
4787 (or (not predicate) (funcall predicate element))
4788 element))
4789 info))
4791 (defun org-export-collect-tables (info)
4792 "Build a list of tables.
4793 INFO is a plist used as a communication channel.
4795 Return a list of table elements with a caption."
4796 (org-export-collect-elements 'table info))
4798 (defun org-export-collect-figures (info predicate)
4799 "Build a list of figures.
4801 INFO is a plist used as a communication channel. PREDICATE is
4802 a function which accepts one argument: a paragraph element and
4803 whose return value is non-nil when that element should be
4804 collected.
4806 A figure is a paragraph type element, with a caption, verifying
4807 PREDICATE. The latter has to be provided since a \"figure\" is
4808 a vague concept that may depend on back-end.
4810 Return a list of elements recognized as figures."
4811 (org-export-collect-elements 'paragraph info predicate))
4813 (defun org-export-collect-listings (info)
4814 "Build a list of src blocks.
4816 INFO is a plist used as a communication channel.
4818 Return a list of src-block elements with a caption."
4819 (org-export-collect-elements 'src-block info))
4822 ;;;; Smart Quotes
4824 ;; The main function for the smart quotes sub-system is
4825 ;; `org-export-activate-smart-quotes', which replaces every quote in
4826 ;; a given string from the parse tree with its "smart" counterpart.
4828 ;; Dictionary for smart quotes is stored in
4829 ;; `org-export-smart-quotes-alist'.
4831 ;; Internally, regexps matching potential smart quotes (checks at
4832 ;; string boundaries are also necessary) are defined in
4833 ;; `org-export-smart-quotes-regexps'.
4835 (defconst org-export-smart-quotes-alist
4836 '(("de"
4837 (opening-double-quote :utf-8 "„" :html "&bdquo;" :latex "\"`"
4838 :texinfo "@quotedblbase{}")
4839 (closing-double-quote :utf-8 "“" :html "&ldquo;" :latex "\"'"
4840 :texinfo "@quotedblleft{}")
4841 (opening-single-quote :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}"
4842 :texinfo "@quotesinglbase{}")
4843 (closing-single-quote :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}"
4844 :texinfo "@quoteleft{}")
4845 (apostrophe :utf-8 "’" :html "&rsquo;"))
4846 ("en"
4847 (opening-double-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4848 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4849 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
4850 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
4851 (apostrophe :utf-8 "’" :html "&rsquo;"))
4852 ("es"
4853 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
4854 :texinfo "@guillemetleft{}")
4855 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
4856 :texinfo "@guillemetright{}")
4857 (opening-single-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4858 (closing-single-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4859 (apostrophe :utf-8 "’" :html "&rsquo;"))
4860 ("fr"
4861 (opening-double-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4862 :texinfo "@guillemetleft{}@tie{}")
4863 (closing-double-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4864 :texinfo "@tie{}@guillemetright{}")
4865 (opening-single-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4866 :texinfo "@guillemetleft{}@tie{}")
4867 (closing-single-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4868 :texinfo "@tie{}@guillemetright{}")
4869 (apostrophe :utf-8 "’" :html "&rsquo;")))
4870 "Smart quotes translations.
4872 Alist whose CAR is a language string and CDR is an alist with
4873 quote type as key and a plist associating various encodings to
4874 their translation as value.
4876 A quote type can be any symbol among `opening-double-quote',
4877 `closing-double-quote', `opening-single-quote',
4878 `closing-single-quote' and `apostrophe'.
4880 Valid encodings include `:utf-8', `:html', `:latex' and
4881 `:texinfo'.
4883 If no translation is found, the quote character is left as-is.")
4885 (defconst org-export-smart-quotes-regexps
4886 (list
4887 ;; Possible opening quote at beginning of string.
4888 "\\`\\([\"']\\)\\(\\w\\|\\s.\\|\\s_\\)"
4889 ;; Possible closing quote at beginning of string.
4890 "\\`\\([\"']\\)\\(\\s-\\|\\s)\\|\\s.\\)"
4891 ;; Possible apostrophe at beginning of string.
4892 "\\`\\('\\)\\S-"
4893 ;; Opening single and double quotes.
4894 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\(?:\\w\\|\\s.\\|\\s_\\)"
4895 ;; Closing single and double quotes.
4896 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\(?:\\s-\\|\\s)\\|\\s.\\)"
4897 ;; Apostrophe.
4898 "\\S-\\('\\)\\S-"
4899 ;; Possible opening quote at end of string.
4900 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\'"
4901 ;; Possible closing quote at end of string.
4902 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\'"
4903 ;; Possible apostrophe at end of string.
4904 "\\S-\\('\\)\\'")
4905 "List of regexps matching a quote or an apostrophe.
4906 In every regexp, quote or apostrophe matched is put in group 1.")
4908 (defun org-export-activate-smart-quotes (s encoding info &optional original)
4909 "Replace regular quotes with \"smart\" quotes in string S.
4911 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
4912 `:utf-8'. INFO is a plist used as a communication channel.
4914 The function has to retrieve information about string
4915 surroundings in parse tree. It can only happen with an
4916 unmodified string. Thus, if S has already been through another
4917 process, a non-nil ORIGINAL optional argument will provide that
4918 original string.
4920 Return the new string."
4921 (if (equal s "") ""
4922 (let* ((prev (org-export-get-previous-element (or original s) info))
4923 ;; Try to be flexible when computing number of blanks
4924 ;; before object. The previous object may be a string
4925 ;; introduced by the back-end and not completely parsed.
4926 (pre-blank (and prev
4927 (or (org-element-property :post-blank prev)
4928 ;; A string with missing `:post-blank'
4929 ;; property.
4930 (and (stringp prev)
4931 (string-match " *\\'" prev)
4932 (length (match-string 0 prev)))
4933 ;; Fallback value.
4934 0)))
4935 (next (org-export-get-next-element (or original s) info))
4936 (get-smart-quote
4937 (lambda (q type)
4938 ;; Return smart quote associated to a give quote Q, as
4939 ;; a string. TYPE is a symbol among `open', `close' and
4940 ;; `apostrophe'.
4941 (let ((key (case type
4942 (apostrophe 'apostrophe)
4943 (open (if (equal "'" q) 'opening-single-quote
4944 'opening-double-quote))
4945 (otherwise (if (equal "'" q) 'closing-single-quote
4946 'closing-double-quote)))))
4947 (or (plist-get
4948 (cdr (assq key
4949 (cdr (assoc (plist-get info :language)
4950 org-export-smart-quotes-alist))))
4951 encoding)
4952 q)))))
4953 (if (or (equal "\"" s) (equal "'" s))
4954 ;; Only a quote: no regexp can match. We have to check both
4955 ;; sides and decide what to do.
4956 (cond ((and (not prev) (not next)) s)
4957 ((not prev) (funcall get-smart-quote s 'open))
4958 ((and (not next) (zerop pre-blank))
4959 (funcall get-smart-quote s 'close))
4960 ((not next) s)
4961 ((zerop pre-blank) (funcall get-smart-quote s 'apostrophe))
4962 (t (funcall get-smart-quote 'open)))
4963 ;; 1. Replace quote character at the beginning of S.
4964 (cond
4965 ;; Apostrophe?
4966 ((and prev (zerop pre-blank)
4967 (string-match (nth 2 org-export-smart-quotes-regexps) s))
4968 (setq s (replace-match
4969 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
4970 nil t s 1)))
4971 ;; Closing quote?
4972 ((and prev (zerop pre-blank)
4973 (string-match (nth 1 org-export-smart-quotes-regexps) s))
4974 (setq s (replace-match
4975 (funcall get-smart-quote (match-string 1 s) 'close)
4976 nil t s 1)))
4977 ;; Opening quote?
4978 ((and (or (not prev) (> pre-blank 0))
4979 (string-match (nth 0 org-export-smart-quotes-regexps) s))
4980 (setq s (replace-match
4981 (funcall get-smart-quote (match-string 1 s) 'open)
4982 nil t s 1))))
4983 ;; 2. Replace quotes in the middle of the string.
4984 (setq s (replace-regexp-in-string
4985 ;; Opening quotes.
4986 (nth 3 org-export-smart-quotes-regexps)
4987 (lambda (text)
4988 (funcall get-smart-quote (match-string 1 text) 'open))
4989 s nil t 1))
4990 (setq s (replace-regexp-in-string
4991 ;; Closing quotes.
4992 (nth 4 org-export-smart-quotes-regexps)
4993 (lambda (text)
4994 (funcall get-smart-quote (match-string 1 text) 'close))
4995 s nil t 1))
4996 (setq s (replace-regexp-in-string
4997 ;; Apostrophes.
4998 (nth 5 org-export-smart-quotes-regexps)
4999 (lambda (text)
5000 (funcall get-smart-quote (match-string 1 text) 'apostrophe))
5001 s nil t 1))
5002 ;; 3. Replace quote character at the end of S.
5003 (cond
5004 ;; Apostrophe?
5005 ((and next (string-match (nth 8 org-export-smart-quotes-regexps) s))
5006 (setq s (replace-match
5007 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
5008 nil t s 1)))
5009 ;; Closing quote?
5010 ((and (not next)
5011 (string-match (nth 7 org-export-smart-quotes-regexps) s))
5012 (setq s (replace-match
5013 (funcall get-smart-quote (match-string 1 s) 'close)
5014 nil t s 1)))
5015 ;; Opening quote?
5016 ((and next (string-match (nth 6 org-export-smart-quotes-regexps) s))
5017 (setq s (replace-match
5018 (funcall get-smart-quote (match-string 1 s) 'open)
5019 nil t s 1))))
5020 ;; Return string with smart quotes.
5021 s))))
5023 ;;;; Topology
5025 ;; Here are various functions to retrieve information about the
5026 ;; neighbourhood of a given element or object. Neighbours of interest
5027 ;; are direct parent (`org-export-get-parent'), parent headline
5028 ;; (`org-export-get-parent-headline'), first element containing an
5029 ;; object, (`org-export-get-parent-element'), parent table
5030 ;; (`org-export-get-parent-table'), previous element or object
5031 ;; (`org-export-get-previous-element') and next element or object
5032 ;; (`org-export-get-next-element').
5034 ;; `org-export-get-genealogy' returns the full genealogy of a given
5035 ;; element or object, from closest parent to full parse tree.
5037 (defun org-export-get-parent (blob)
5038 "Return BLOB parent or nil.
5039 BLOB is the element or object considered."
5040 (org-element-property :parent blob))
5042 (defun org-export-get-genealogy (blob)
5043 "Return full genealogy relative to a given element or object.
5045 BLOB is the element or object being considered.
5047 Ancestors are returned from closest to farthest, the last one
5048 being the full parse tree."
5049 (let (genealogy (parent blob))
5050 (while (setq parent (org-element-property :parent parent))
5051 (push parent genealogy))
5052 (nreverse genealogy)))
5054 (defun org-export-get-parent-headline (blob)
5055 "Return BLOB parent headline or nil.
5056 BLOB is the element or object being considered."
5057 (let ((parent blob))
5058 (while (and (setq parent (org-element-property :parent parent))
5059 (not (eq (org-element-type parent) 'headline))))
5060 parent))
5062 (defun org-export-get-parent-element (object)
5063 "Return first element containing OBJECT or nil.
5064 OBJECT is the object to consider."
5065 (let ((parent object))
5066 (while (and (setq parent (org-element-property :parent parent))
5067 (memq (org-element-type parent) org-element-all-objects)))
5068 parent))
5070 (defun org-export-get-parent-table (object)
5071 "Return OBJECT parent table or nil.
5072 OBJECT is either a `table-cell' or `table-element' type object."
5073 (let ((parent object))
5074 (while (and (setq parent (org-element-property :parent parent))
5075 (not (eq (org-element-type parent) 'table))))
5076 parent))
5078 (defun org-export-get-previous-element (blob info &optional n)
5079 "Return previous element or object.
5081 BLOB is an element or object. INFO is a plist used as
5082 a communication channel. Return previous exportable element or
5083 object, a string, or nil.
5085 When optional argument N is a positive integer, return a list
5086 containing up to N siblings before BLOB, from farthest to
5087 closest. With any other non-nil value, return a list containing
5088 all of them."
5089 (let ((siblings
5090 ;; An object can belong to the contents of its parent or
5091 ;; to a secondary string. We check the latter option
5092 ;; first.
5093 (let ((parent (org-export-get-parent blob)))
5094 (or (and (not (memq (org-element-type blob)
5095 org-element-all-elements))
5096 (let ((sec-value
5097 (org-element-property
5098 (cdr (assq (org-element-type parent)
5099 org-element-secondary-value-alist))
5100 parent)))
5101 (and (memq blob sec-value) sec-value)))
5102 (org-element-contents parent))))
5103 prev)
5104 (catch 'exit
5105 (mapc (lambda (obj)
5106 (cond ((memq obj (plist-get info :ignore-list)))
5107 ((null n) (throw 'exit obj))
5108 ((not (wholenump n)) (push obj prev))
5109 ((zerop n) (throw 'exit prev))
5110 (t (decf n) (push obj prev))))
5111 (cdr (memq blob (reverse siblings))))
5112 prev)))
5114 (defun org-export-get-next-element (blob info &optional n)
5115 "Return next element or object.
5117 BLOB is an element or object. INFO is a plist used as
5118 a communication channel. Return next exportable element or
5119 object, a string, or nil.
5121 When optional argument N is a positive integer, return a list
5122 containing up to N siblings after BLOB, from closest to farthest.
5123 With any other non-nil value, return a list containing all of
5124 them."
5125 (let ((siblings
5126 ;; An object can belong to the contents of its parent or to
5127 ;; a secondary string. We check the latter option first.
5128 (let ((parent (org-export-get-parent blob)))
5129 (or (and (not (memq (org-element-type blob)
5130 org-element-all-objects))
5131 (let ((sec-value
5132 (org-element-property
5133 (cdr (assq (org-element-type parent)
5134 org-element-secondary-value-alist))
5135 parent)))
5136 (cdr (memq blob sec-value))))
5137 (cdr (memq blob (org-element-contents parent))))))
5138 next)
5139 (catch 'exit
5140 (mapc (lambda (obj)
5141 (cond ((memq obj (plist-get info :ignore-list)))
5142 ((null n) (throw 'exit obj))
5143 ((not (wholenump n)) (push obj next))
5144 ((zerop n) (throw 'exit (nreverse next)))
5145 (t (decf n) (push obj next))))
5146 siblings)
5147 (nreverse next))))
5150 ;;;; Translation
5152 ;; `org-export-translate' translates a string according to language
5153 ;; specified by LANGUAGE keyword or `org-export-language-setup'
5154 ;; variable and a specified charset. `org-export-dictionary' contains
5155 ;; the dictionary used for the translation.
5157 (defconst org-export-dictionary
5158 '(("Author"
5159 ("ca" :default "Autor")
5160 ("cs" :default "Autor")
5161 ("da" :default "Ophavsmand")
5162 ("de" :default "Autor")
5163 ("eo" :html "A&#365;toro")
5164 ("es" :default "Autor")
5165 ("fi" :html "Tekij&auml;")
5166 ("fr" :default "Auteur")
5167 ("hu" :default "Szerz&otilde;")
5168 ("is" :html "H&ouml;fundur")
5169 ("it" :default "Autore")
5170 ("ja" :html "&#33879;&#32773;" :utf-8 "著者")
5171 ("nl" :default "Auteur")
5172 ("no" :default "Forfatter")
5173 ("nb" :default "Forfatter")
5174 ("nn" :default "Forfattar")
5175 ("pl" :default "Autor")
5176 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5177 ("sv" :html "F&ouml;rfattare")
5178 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5179 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
5180 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
5181 ("Date"
5182 ("ca" :default "Data")
5183 ("cs" :default "Datum")
5184 ("da" :default "Dato")
5185 ("de" :default "Datum")
5186 ("eo" :default "Dato")
5187 ("es" :default "Fecha")
5188 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
5189 ("hu" :html "D&aacute;tum")
5190 ("is" :default "Dagsetning")
5191 ("it" :default "Data")
5192 ("ja" :html "&#26085;&#20184;" :utf-8 "日付")
5193 ("nl" :default "Datum")
5194 ("no" :default "Dato")
5195 ("nb" :default "Dato")
5196 ("nn" :default "Dato")
5197 ("pl" :default "Data")
5198 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5199 ("sv" :default "Datum")
5200 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5201 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
5202 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
5203 ("Equation"
5204 ("fr" :ascii "Equation" :default "Équation"))
5205 ("Figure")
5206 ("Footnotes"
5207 ("ca" :html "Peus de p&agrave;gina")
5208 ("cs" :default "Pozn\xe1mky pod carou")
5209 ("da" :default "Fodnoter")
5210 ("de" :html "Fu&szlig;noten")
5211 ("eo" :default "Piednotoj")
5212 ("es" :html "Pies de p&aacute;gina")
5213 ("fi" :default "Alaviitteet")
5214 ("fr" :default "Notes de bas de page")
5215 ("hu" :html "L&aacute;bjegyzet")
5216 ("is" :html "Aftanm&aacute;lsgreinar")
5217 ("it" :html "Note a pi&egrave; di pagina")
5218 ("ja" :html "&#33050;&#27880;" :utf-8 "脚注")
5219 ("nl" :default "Voetnoten")
5220 ("no" :default "Fotnoter")
5221 ("nb" :default "Fotnoter")
5222 ("nn" :default "Fotnotar")
5223 ("pl" :default "Przypis")
5224 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5225 ("sv" :default "Fotnoter")
5226 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5227 :utf-8 "Примітки")
5228 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5229 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5230 ("List of Listings"
5231 ("fr" :default "Liste des programmes"))
5232 ("List of Tables"
5233 ("fr" :default "Liste des tableaux"))
5234 ("Listing %d:"
5235 ("fr"
5236 :ascii "Programme %d :" :default "Programme nº %d :"
5237 :latin1 "Programme %d :"))
5238 ("Listing %d: %s"
5239 ("fr"
5240 :ascii "Programme %d : %s" :default "Programme nº %d : %s"
5241 :latin1 "Programme %d : %s"))
5242 ("See section %s"
5243 ("fr" :default "cf. section %s"))
5244 ("Table %d:"
5245 ("fr"
5246 :ascii "Tableau %d :" :default "Tableau nº %d :" :latin1 "Tableau %d :"))
5247 ("Table %d: %s"
5248 ("fr"
5249 :ascii "Tableau %d : %s" :default "Tableau nº %d : %s"
5250 :latin1 "Tableau %d : %s"))
5251 ("Table of Contents"
5252 ("ca" :html "&Iacute;ndex")
5253 ("cs" :default "Obsah")
5254 ("da" :default "Indhold")
5255 ("de" :default "Inhaltsverzeichnis")
5256 ("eo" :default "Enhavo")
5257 ("es" :html "&Iacute;ndice")
5258 ("fi" :html "Sis&auml;llysluettelo")
5259 ("fr" :ascii "Sommaire" :default "Table des matières")
5260 ("hu" :html "Tartalomjegyz&eacute;k")
5261 ("is" :default "Efnisyfirlit")
5262 ("it" :default "Indice")
5263 ("ja" :html "&#30446;&#27425;" :utf-8 "目次")
5264 ("nl" :default "Inhoudsopgave")
5265 ("no" :default "Innhold")
5266 ("nb" :default "Innhold")
5267 ("nn" :default "Innhald")
5268 ("pl" :html "Spis tre&#x015b;ci")
5269 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5270 :utf-8 "Содержание")
5271 ("sv" :html "Inneh&aring;ll")
5272 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5273 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5274 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5275 ("Unknown reference"
5276 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")))
5277 "Dictionary for export engine.
5279 Alist whose CAR is the string to translate and CDR is an alist
5280 whose CAR is the language string and CDR is a plist whose
5281 properties are possible charsets and values translated terms.
5283 It is used as a database for `org-export-translate'. Since this
5284 function returns the string as-is if no translation was found,
5285 the variable only needs to record values different from the
5286 entry.")
5288 (defun org-export-translate (s encoding info)
5289 "Translate string S according to language specification.
5291 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
5292 and `:utf-8'. INFO is a plist used as a communication channel.
5294 Translation depends on `:language' property. Return the
5295 translated string. If no translation is found, try to fall back
5296 to `:default' encoding. If it fails, return S."
5297 (let* ((lang (plist-get info :language))
5298 (translations (cdr (assoc lang
5299 (cdr (assoc s org-export-dictionary))))))
5300 (or (plist-get translations encoding)
5301 (plist-get translations :default)
5302 s)))
5306 ;;; Asynchronous Export
5308 ;; `org-export-async-start' is the entry point for asynchronous
5309 ;; export. It recreates current buffer (including visibility,
5310 ;; narrowing and visited file) in an external Emacs process, and
5311 ;; evaluates a command there. It then applies a function on the
5312 ;; returned results in the current process.
5314 ;; Asynchronously generated results are never displayed directly.
5315 ;; Instead, they are stored in `org-export-stack-contents'. They can
5316 ;; then be retrieved by calling `org-export-stack'.
5318 ;; Export Stack is viewed through a dedicated major mode
5319 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
5320 ;;`org-export-stack-delete', `org-export-stack-view' and
5321 ;;`org-export-stack-clear'.
5323 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
5324 ;; It should used whenever `org-export-async-start' is called.
5326 (defmacro org-export-async-start (fun &rest body)
5327 "Call function FUN on the results returned by BODY evaluation.
5329 BODY evaluation happens in an asynchronous process, from a buffer
5330 which is an exact copy of the current one.
5332 Use `org-export-add-to-stack' in FUN in order to register results
5333 in the stack. Examples for, respectively a temporary buffer and
5334 a file are:
5336 \(org-export-async-start
5337 \(lambda (output)
5338 \(with-current-buffer (get-buffer-create \"*Org BACKEND Export*\")
5339 \(erase-buffer)
5340 \(insert output)
5341 \(goto-char (point-min))
5342 \(org-export-add-to-stack (current-buffer) 'backend)))
5343 `(org-export-as 'backend ,subtreep ,visible-only ,body-only ',ext-plist))
5347 \(org-export-async-start
5348 \(lambda (f) (org-export-add-to-stack f 'backend))
5349 `(expand-file-name
5350 \(org-export-to-file
5351 'backend ,outfile ,subtreep ,visible-only ,body-only ',ext-plist)))"
5352 (declare (indent 1) (debug t))
5353 (org-with-gensyms (process temp-file copy-fun proc-buffer handler coding)
5354 ;; Write the full sexp evaluating BODY in a copy of the current
5355 ;; buffer to a temporary file, as it may be too long for program
5356 ;; args in `start-process'.
5357 `(with-temp-message "Initializing asynchronous export process"
5358 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
5359 (,temp-file (make-temp-file "org-export-process"))
5360 (,coding buffer-file-coding-system))
5361 (with-temp-file ,temp-file
5362 (insert
5363 ;; Null characters (from variable values) are inserted
5364 ;; within the file. As a consequence, coding system for
5365 ;; buffer contents will not be recognized properly. So,
5366 ;; we make sure it is the same as the one used to display
5367 ;; the original buffer.
5368 (format ";; -*- coding: %s; -*-\n%S"
5369 ,coding
5370 `(with-temp-buffer
5371 ,(when org-export-async-debug '(setq debug-on-error t))
5372 ;; Ignore `kill-emacs-hook' and code evaluation
5373 ;; queries from Babel as we need a truly
5374 ;; non-interactive process.
5375 (setq kill-emacs-hook nil
5376 org-babel-confirm-evaluate-answer-no t)
5377 ;; Initialize export framework.
5378 (require 'ox)
5379 ;; Re-create current buffer there.
5380 (funcall ,,copy-fun)
5381 (restore-buffer-modified-p nil)
5382 ;; Sexp to evaluate in the buffer.
5383 (print (progn ,,@body))))))
5384 ;; Start external process.
5385 (let* ((process-connection-type nil)
5386 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
5387 (,process
5388 (start-process
5389 "org-export-process" ,proc-buffer
5390 (expand-file-name invocation-name invocation-directory)
5391 "-Q" "--batch"
5392 "-l" org-export-async-init-file
5393 "-l" ,temp-file)))
5394 ;; Register running process in stack.
5395 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
5396 ;; Set-up sentinel in order to catch results.
5397 (set-process-sentinel
5398 ,process
5399 (let ((handler ',fun))
5400 `(lambda (p status)
5401 (let ((proc-buffer (process-buffer p)))
5402 (when (eq (process-status p) 'exit)
5403 (unwind-protect
5404 (if (zerop (process-exit-status p))
5405 (unwind-protect
5406 (let ((results
5407 (with-current-buffer proc-buffer
5408 (goto-char (point-max))
5409 (backward-sexp)
5410 (read (current-buffer)))))
5411 (funcall ,handler results))
5412 (unless org-export-async-debug
5413 (and (get-buffer proc-buffer)
5414 (kill-buffer proc-buffer))))
5415 (org-export-add-to-stack proc-buffer nil p)
5416 (ding)
5417 (message "Process '%s' exited abnormally" p))
5418 (unless org-export-async-debug
5419 (delete-file ,,temp-file)))))))))))))
5421 (defun org-export-add-to-stack (source backend &optional process)
5422 "Add a new result to export stack if not present already.
5424 SOURCE is a buffer or a file name containing export results.
5425 BACKEND is a symbol representing export back-end used to generate
5428 Entries already pointing to SOURCE and unavailable entries are
5429 removed beforehand. Return the new stack."
5430 (setq org-export-stack-contents
5431 (cons (list source backend (or process (current-time)))
5432 (org-export-stack-remove source))))
5434 (defun org-export-stack ()
5435 "Menu for asynchronous export results and running processes."
5436 (interactive)
5437 (let ((buffer (get-buffer-create "*Org Export Stack*")))
5438 (set-buffer buffer)
5439 (when (zerop (buffer-size)) (org-export-stack-mode))
5440 (org-export-stack-refresh)
5441 (pop-to-buffer buffer))
5442 (message "Type \"q\" to quit, \"?\" for help"))
5444 (defun org-export--stack-source-at-point ()
5445 "Return source from export results at point in stack."
5446 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
5447 (if (not source) (error "Source unavailable, please refresh buffer")
5448 (let ((source-name (if (stringp source) source (buffer-name source))))
5449 (if (save-excursion
5450 (beginning-of-line)
5451 (looking-at (concat ".* +" (regexp-quote source-name) "$")))
5452 source
5453 ;; SOURCE is not consistent with current line. The stack
5454 ;; view is outdated.
5455 (error "Source unavailable; type `g' to update buffer"))))))
5457 (defun org-export-stack-clear ()
5458 "Remove all entries from export stack."
5459 (interactive)
5460 (setq org-export-stack-contents nil))
5462 (defun org-export-stack-refresh (&rest dummy)
5463 "Refresh the asynchronous export stack.
5464 DUMMY is ignored. Unavailable sources are removed from the list.
5465 Return the new stack."
5466 (let ((inhibit-read-only t))
5467 (org-preserve-lc
5468 (erase-buffer)
5469 (insert (concat
5470 (let ((counter 0))
5471 (mapconcat
5472 (lambda (entry)
5473 (let ((proc-p (processp (nth 2 entry))))
5474 (concat
5475 ;; Back-end.
5476 (format " %-12s " (or (nth 1 entry) ""))
5477 ;; Age.
5478 (let ((data (nth 2 entry)))
5479 (if proc-p (format " %6s " (process-status data))
5480 ;; Compute age of the results.
5481 (org-format-seconds
5482 "%4h:%.2m "
5483 (float-time (time-since data)))))
5484 ;; Source.
5485 (format " %s"
5486 (let ((source (car entry)))
5487 (if (stringp source) source
5488 (buffer-name source)))))))
5489 ;; Clear stack from exited processes, dead buffers or
5490 ;; non-existent files.
5491 (setq org-export-stack-contents
5492 (org-remove-if-not
5493 (lambda (el)
5494 (if (processp (nth 2 el))
5495 (buffer-live-p (process-buffer (nth 2 el)))
5496 (let ((source (car el)))
5497 (if (bufferp source) (buffer-live-p source)
5498 (file-exists-p source)))))
5499 org-export-stack-contents)) "\n")))))))
5501 (defun org-export-stack-remove (&optional source)
5502 "Remove export results at point from stack.
5503 If optional argument SOURCE is non-nil, remove it instead."
5504 (interactive)
5505 (let ((source (or source (org-export--stack-source-at-point))))
5506 (setq org-export-stack-contents
5507 (org-remove-if (lambda (el) (equal (car el) source))
5508 org-export-stack-contents))))
5510 (defun org-export-stack-view (&optional in-emacs)
5511 "View export results at point in stack.
5512 With an optional prefix argument IN-EMACS, force viewing files
5513 within Emacs."
5514 (interactive "P")
5515 (let ((source (org-export--stack-source-at-point)))
5516 (cond ((processp source)
5517 (org-switch-to-buffer-other-window (process-buffer source)))
5518 ((bufferp source) (org-switch-to-buffer-other-window source))
5519 (t (org-open-file source in-emacs)))))
5521 (defconst org-export-stack-mode-map
5522 (let ((km (make-sparse-keymap)))
5523 (define-key km " " 'next-line)
5524 (define-key km "n" 'next-line)
5525 (define-key km "\C-n" 'next-line)
5526 (define-key km [down] 'next-line)
5527 (define-key km "p" 'previous-line)
5528 (define-key km "\C-p" 'previous-line)
5529 (define-key km "\C-?" 'previous-line)
5530 (define-key km [up] 'previous-line)
5531 (define-key km "C" 'org-export-stack-clear)
5532 (define-key km "v" 'org-export-stack-view)
5533 (define-key km (kbd "RET") 'org-export-stack-view)
5534 (define-key km "d" 'org-export-stack-remove)
5536 "Keymap for Org Export Stack.")
5538 (define-derived-mode org-export-stack-mode special-mode "Org-Stack"
5539 "Mode for displaying asynchronous export stack.
5541 Type \\[org-export-stack] to visualize the asynchronous export
5542 stack.
5544 In an Org Export Stack buffer, use \\<org-export-stack-mode-map>\\[org-export-stack-view] to view export output
5545 on current line, \\[org-export-stack-remove] to remove it from the stack and \\[org-export-stack-clear] to clear
5546 stack completely.
5548 Removing entries in an Org Export Stack buffer doesn't affect
5549 files or buffers, only the display.
5551 \\{org-export-stack-mode-map}"
5552 (abbrev-mode 0)
5553 (auto-fill-mode 0)
5554 (setq buffer-read-only t
5555 buffer-undo-list t
5556 truncate-lines t
5557 header-line-format
5558 '(:eval
5559 (format " %-12s | %6s | %s" "Back-End" "Age" "Source")))
5560 (add-hook 'post-command-hook 'org-export-stack-refresh nil t)
5561 (set (make-local-variable 'revert-buffer-function)
5562 'org-export-stack-refresh))
5566 ;;; The Dispatcher
5568 ;; `org-export-dispatch' is the standard interactive way to start an
5569 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
5570 ;; for its interface, which, in turn, delegates response to key
5571 ;; pressed to `org-export--dispatch-action'.
5573 ;;;###autoload
5574 (defun org-export-dispatch (&optional arg)
5575 "Export dispatcher for Org mode.
5577 It provides an access to common export related tasks in a buffer.
5578 Its interface comes in two flavours: standard and expert.
5580 While both share the same set of bindings, only the former
5581 displays the valid keys associations in a dedicated buffer.
5582 Scrolling (resp. line-wise motion) in this buffer is done with
5583 SPC and DEL (resp. C-n and C-p) keys.
5585 Set variable `org-export-dispatch-use-expert-ui' to switch to one
5586 flavour or the other.
5588 When ARG is \\[universal-argument], repeat the last export action, with the same set
5589 of options used back then, on the current buffer.
5591 When ARG is \\[universal-argument] \\[universal-argument], display the asynchronous export stack."
5592 (interactive "P")
5593 (let* ((input
5594 (cond ((equal arg '(16)) '(stack))
5595 ((and arg org-export-dispatch-last-action))
5596 (t (save-window-excursion
5597 (unwind-protect
5598 (progn
5599 ;; Remember where we are
5600 (move-marker org-export-dispatch-last-position
5601 (point)
5602 (org-base-buffer (current-buffer)))
5603 ;; Get and store an export command
5604 (setq org-export-dispatch-last-action
5605 (org-export--dispatch-ui
5606 (list org-export-initial-scope
5607 (and org-export-in-background 'async))
5609 org-export-dispatch-use-expert-ui)))
5610 (and (get-buffer "*Org Export Dispatcher*")
5611 (kill-buffer "*Org Export Dispatcher*")))))))
5612 (action (car input))
5613 (optns (cdr input)))
5614 (unless (memq 'subtree optns)
5615 (move-marker org-export-dispatch-last-position nil))
5616 (case action
5617 ;; First handle special hard-coded actions.
5618 (template (org-export-insert-default-template nil optns))
5619 (stack (org-export-stack))
5620 (publish-current-file
5621 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
5622 (publish-current-project
5623 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
5624 (publish-choose-project
5625 (org-publish (assoc (org-icompleting-read
5626 "Publish project: "
5627 org-publish-project-alist nil t)
5628 org-publish-project-alist)
5629 (memq 'force optns)
5630 (memq 'async optns)))
5631 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
5632 (otherwise
5633 (save-excursion
5634 (when arg
5635 ;; Repeating command, maybe move cursor to restore subtree
5636 ;; context.
5637 (if (eq (marker-buffer org-export-dispatch-last-position)
5638 (org-base-buffer (current-buffer)))
5639 (goto-char org-export-dispatch-last-position)
5640 ;; We are in a different buffer, forget position.
5641 (move-marker org-export-dispatch-last-position nil)))
5642 (funcall action
5643 ;; Return a symbol instead of a list to ease
5644 ;; asynchronous export macro use.
5645 (and (memq 'async optns) t)
5646 (and (memq 'subtree optns) t)
5647 (and (memq 'visible optns) t)
5648 (and (memq 'body optns) t)))))))
5650 (defun org-export--dispatch-ui (options first-key expertp)
5651 "Handle interface for `org-export-dispatch'.
5653 OPTIONS is a list containing current interactive options set for
5654 export. It can contain any of the following symbols:
5655 `body' toggles a body-only export
5656 `subtree' restricts export to current subtree
5657 `visible' restricts export to visible part of buffer.
5658 `force' force publishing files.
5659 `async' use asynchronous export process
5661 FIRST-KEY is the key pressed to select the first level menu. It
5662 is nil when this menu hasn't been selected yet.
5664 EXPERTP, when non-nil, triggers expert UI. In that case, no help
5665 buffer is provided, but indications about currently active
5666 options are given in the prompt. Moreover, \[?] allows to switch
5667 back to standard interface."
5668 (let* ((fontify-key
5669 (lambda (key &optional access-key)
5670 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
5671 ;; non-nil is the required first-level key to activate
5672 ;; KEY. When its value is t, activate KEY independently
5673 ;; on the first key, if any. A nil value means KEY will
5674 ;; only be activated at first level.
5675 (if (or (eq access-key t) (eq access-key first-key))
5676 (org-propertize key 'face 'org-warning)
5677 key)))
5678 (fontify-value
5679 (lambda (value)
5680 ;; Fontify VALUE string.
5681 (org-propertize value 'face 'font-lock-variable-name-face)))
5682 ;; Prepare menu entries by extracting them from
5683 ;; `org-export-registered-backends', and sorting them by
5684 ;; access key and by ordinal, if any.
5685 (backends
5686 (sort
5687 (sort
5688 (delq nil
5689 (mapcar
5690 (lambda (b)
5691 (let ((name (car b)))
5692 (catch 'ignored
5693 ;; Ignore any back-end belonging to
5694 ;; `org-export-invisible-backends' or derived
5695 ;; from one of them.
5696 (dolist (ignored org-export-invisible-backends)
5697 (when (org-export-derived-backend-p name ignored)
5698 (throw 'ignored nil)))
5699 (org-export-backend-menu name))))
5700 org-export-registered-backends))
5701 (lambda (a b)
5702 (let ((key-a (nth 1 a))
5703 (key-b (nth 1 b)))
5704 (cond ((and (numberp key-a) (numberp key-b))
5705 (< key-a key-b))
5706 ((numberp key-b) t)))))
5707 (lambda (a b) (< (car a) (car b)))))
5708 ;; Compute a list of allowed keys based on the first key
5709 ;; pressed, if any. Some keys
5710 ;; (?^B, ?^V, ?^S, ?^F, ?^A, ?&, ?# and ?q) are always
5711 ;; available.
5712 (allowed-keys
5713 (nconc (list 2 22 19 6 1)
5714 (if (not first-key) (org-uniquify (mapcar 'car backends))
5715 (let (sub-menu)
5716 (dolist (backend backends (sort (mapcar 'car sub-menu) '<))
5717 (when (eq (car backend) first-key)
5718 (setq sub-menu (append (nth 2 backend) sub-menu))))))
5719 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
5720 ((not first-key) (list ?P)))
5721 (list ?& ?#)
5722 (when expertp (list ??))
5723 (list ?q)))
5724 ;; Build the help menu for standard UI.
5725 (help
5726 (unless expertp
5727 (concat
5728 ;; Options are hard-coded.
5729 (format "[%s] Body only: %s [%s] Visible only: %s
5730 \[%s] Export scope: %s [%s] Force publishing: %s
5731 \[%s] Async export: %s\n\n"
5732 (funcall fontify-key "C-b" t)
5733 (funcall fontify-value
5734 (if (memq 'body options) "On " "Off"))
5735 (funcall fontify-key "C-v" t)
5736 (funcall fontify-value
5737 (if (memq 'visible options) "On " "Off"))
5738 (funcall fontify-key "C-s" t)
5739 (funcall fontify-value
5740 (if (memq 'subtree options) "Subtree" "Buffer "))
5741 (funcall fontify-key "C-f" t)
5742 (funcall fontify-value
5743 (if (memq 'force options) "On " "Off"))
5744 (funcall fontify-key "C-a" t)
5745 (funcall fontify-value
5746 (if (memq 'async options) "On " "Off")))
5747 ;; Display registered back-end entries. When a key
5748 ;; appears for the second time, do not create another
5749 ;; entry, but append its sub-menu to existing menu.
5750 (let (last-key)
5751 (mapconcat
5752 (lambda (entry)
5753 (let ((top-key (car entry)))
5754 (concat
5755 (unless (eq top-key last-key)
5756 (setq last-key top-key)
5757 (format "\n[%s] %s\n"
5758 (funcall fontify-key (char-to-string top-key))
5759 (nth 1 entry)))
5760 (let ((sub-menu (nth 2 entry)))
5761 (unless (functionp sub-menu)
5762 ;; Split sub-menu into two columns.
5763 (let ((index -1))
5764 (concat
5765 (mapconcat
5766 (lambda (sub-entry)
5767 (incf index)
5768 (format
5769 (if (zerop (mod index 2)) " [%s] %-26s"
5770 "[%s] %s\n")
5771 (funcall fontify-key
5772 (char-to-string (car sub-entry))
5773 top-key)
5774 (nth 1 sub-entry)))
5775 sub-menu "")
5776 (when (zerop (mod index 2)) "\n"))))))))
5777 backends ""))
5778 ;; Publishing menu is hard-coded.
5779 (format "\n[%s] Publish
5780 [%s] Current file [%s] Current project
5781 [%s] Choose project [%s] All projects\n\n\n"
5782 (funcall fontify-key "P")
5783 (funcall fontify-key "f" ?P)
5784 (funcall fontify-key "p" ?P)
5785 (funcall fontify-key "x" ?P)
5786 (funcall fontify-key "a" ?P))
5787 (format "[%s] Export stack [%s] Insert template\n"
5788 (funcall fontify-key "&" t)
5789 (funcall fontify-key "#" t))
5790 (format "[%s] %s"
5791 (funcall fontify-key "q" t)
5792 (if first-key "Main menu" "Exit")))))
5793 ;; Build prompts for both standard and expert UI.
5794 (standard-prompt (unless expertp "Export command: "))
5795 (expert-prompt
5796 (when expertp
5797 (format
5798 "Export command (C-%s%s%s%s%s) [%s]: "
5799 (if (memq 'body options) (funcall fontify-key "b" t) "b")
5800 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
5801 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
5802 (if (memq 'force options) (funcall fontify-key "f" t) "f")
5803 (if (memq 'async options) (funcall fontify-key "a" t) "a")
5804 (mapconcat (lambda (k)
5805 ;; Strip control characters.
5806 (unless (< k 27) (char-to-string k)))
5807 allowed-keys "")))))
5808 ;; With expert UI, just read key with a fancy prompt. In standard
5809 ;; UI, display an intrusive help buffer.
5810 (if expertp
5811 (org-export--dispatch-action
5812 expert-prompt allowed-keys backends options first-key expertp)
5813 ;; At first call, create frame layout in order to display menu.
5814 (unless (get-buffer "*Org Export Dispatcher*")
5815 (delete-other-windows)
5816 (org-switch-to-buffer-other-window
5817 (get-buffer-create "*Org Export Dispatcher*"))
5818 (setq cursor-type nil
5819 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
5820 ;; Make sure that invisible cursor will not highlight square
5821 ;; brackets.
5822 (set-syntax-table (copy-syntax-table))
5823 (modify-syntax-entry ?\[ "w"))
5824 ;; At this point, the buffer containing the menu exists and is
5825 ;; visible in the current window. So, refresh it.
5826 (with-current-buffer "*Org Export Dispatcher*"
5827 ;; Refresh help. Maintain display continuity by re-visiting
5828 ;; previous window position.
5829 (let ((pos (window-start)))
5830 (erase-buffer)
5831 (insert help)
5832 (set-window-start nil pos)))
5833 (org-fit-window-to-buffer)
5834 (org-export--dispatch-action
5835 standard-prompt allowed-keys backends options first-key expertp))))
5837 (defun org-export--dispatch-action
5838 (prompt allowed-keys backends options first-key expertp)
5839 "Read a character from command input and act accordingly.
5841 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
5842 a list of characters available at a given step in the process.
5843 BACKENDS is a list of menu entries. OPTIONS, FIRST-KEY and
5844 EXPERTP are the same as defined in `org-export--dispatch-ui',
5845 which see.
5847 Toggle export options when required. Otherwise, return value is
5848 a list with action as CAR and a list of interactive export
5849 options as CDR."
5850 (let (key)
5851 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
5852 ;; C-p, SPC, DEL).
5853 (while (and (setq key (read-char-exclusive prompt))
5854 (not expertp)
5855 (memq key '(14 16 ?\s ?\d)))
5856 (case key
5857 (14 (if (not (pos-visible-in-window-p (point-max)))
5858 (ignore-errors (scroll-up-line))
5859 (message "End of buffer")
5860 (sit-for 1)))
5861 (16 (if (not (pos-visible-in-window-p (point-min)))
5862 (ignore-errors (scroll-down-line))
5863 (message "Beginning of buffer")
5864 (sit-for 1)))
5865 (?\s (if (not (pos-visible-in-window-p (point-max)))
5866 (scroll-up nil)
5867 (message "End of buffer")
5868 (sit-for 1)))
5869 (?\d (if (not (pos-visible-in-window-p (point-min)))
5870 (scroll-down nil)
5871 (message "Beginning of buffer")
5872 (sit-for 1)))))
5873 (cond
5874 ;; Ignore undefined associations.
5875 ((not (memq key allowed-keys))
5876 (ding)
5877 (unless expertp (message "Invalid key") (sit-for 1))
5878 (org-export--dispatch-ui options first-key expertp))
5879 ;; q key at first level aborts export. At second level, cancel
5880 ;; first key instead.
5881 ((eq key ?q) (if (not first-key) (error "Export aborted")
5882 (org-export--dispatch-ui options nil expertp)))
5883 ;; Help key: Switch back to standard interface if expert UI was
5884 ;; active.
5885 ((eq key ??) (org-export--dispatch-ui options first-key nil))
5886 ;; Send request for template insertion along with export scope.
5887 ((eq key ?#) (cons 'template (memq 'subtree options)))
5888 ;; Switch to asynchronous export stack.
5889 ((eq key ?&) '(stack))
5890 ;; Toggle options: C-b (2) C-v (22) C-s (19) C-f (6) C-a (1).
5891 ((memq key '(2 22 19 6 1))
5892 (org-export--dispatch-ui
5893 (let ((option (case key (2 'body) (22 'visible) (19 'subtree)
5894 (6 'force) (1 'async))))
5895 (if (memq option options) (remq option options)
5896 (cons option options)))
5897 first-key expertp))
5898 ;; Action selected: Send key and options back to
5899 ;; `org-export-dispatch'.
5900 ((or first-key (functionp (nth 2 (assq key backends))))
5901 (cons (cond
5902 ((not first-key) (nth 2 (assq key backends)))
5903 ;; Publishing actions are hard-coded. Send a special
5904 ;; signal to `org-export-dispatch'.
5905 ((eq first-key ?P)
5906 (case key
5907 (?f 'publish-current-file)
5908 (?p 'publish-current-project)
5909 (?x 'publish-choose-project)
5910 (?a 'publish-all)))
5911 ;; Return first action associated to FIRST-KEY + KEY
5912 ;; path. Indeed, derived backends can share the same
5913 ;; FIRST-KEY.
5914 (t (catch 'found
5915 (mapc (lambda (backend)
5916 (let ((match (assq key (nth 2 backend))))
5917 (when match (throw 'found (nth 2 match)))))
5918 (member (assq first-key backends) backends)))))
5919 options))
5920 ;; Otherwise, enter sub-menu.
5921 (t (org-export--dispatch-ui options key expertp)))))
5925 (provide 'ox)
5927 ;; Local variables:
5928 ;; generated-autoload-file: "org-loaddefs.el"
5929 ;; End:
5931 ;;; ox.el ends here