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