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