org.el: New command org-insert-last-stored-link bound to `C-c M-l'
[org-mode.git] / lisp / ox-odt.el
blobf920fc8e0a9699762dc43ffccabc036111a413f3
1 ;;; ox-odt.el --- OpenDocument Text Exporter for Org Mode
3 ;; Copyright (C) 2010-2014 Free Software Foundation, Inc.
5 ;; Author: Jambunathan K <kjambunathan at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;;; Code:
28 (eval-when-compile
29 (require 'cl)
30 (require 'table nil 'noerror))
31 (require 'format-spec)
32 (require 'ox)
33 (require 'org-compat)
35 ;;; Define Back-End
37 (org-export-define-backend 'odt
38 '((bold . org-odt-bold)
39 (center-block . org-odt-center-block)
40 (clock . org-odt-clock)
41 (code . org-odt-code)
42 (drawer . org-odt-drawer)
43 (dynamic-block . org-odt-dynamic-block)
44 (entity . org-odt-entity)
45 (example-block . org-odt-example-block)
46 (export-block . org-odt-export-block)
47 (export-snippet . org-odt-export-snippet)
48 (fixed-width . org-odt-fixed-width)
49 (footnote-definition . org-odt-footnote-definition)
50 (footnote-reference . org-odt-footnote-reference)
51 (headline . org-odt-headline)
52 (horizontal-rule . org-odt-horizontal-rule)
53 (inline-src-block . org-odt-inline-src-block)
54 (inlinetask . org-odt-inlinetask)
55 (italic . org-odt-italic)
56 (item . org-odt-item)
57 (keyword . org-odt-keyword)
58 (latex-environment . org-odt-latex-environment)
59 (latex-fragment . org-odt-latex-fragment)
60 (line-break . org-odt-line-break)
61 (link . org-odt-link)
62 (node-property . org-odt-node-property)
63 (paragraph . org-odt-paragraph)
64 (plain-list . org-odt-plain-list)
65 (plain-text . org-odt-plain-text)
66 (planning . org-odt-planning)
67 (property-drawer . org-odt-property-drawer)
68 (quote-block . org-odt-quote-block)
69 (quote-section . org-odt-quote-section)
70 (radio-target . org-odt-radio-target)
71 (section . org-odt-section)
72 (special-block . org-odt-special-block)
73 (src-block . org-odt-src-block)
74 (statistics-cookie . org-odt-statistics-cookie)
75 (strike-through . org-odt-strike-through)
76 (subscript . org-odt-subscript)
77 (superscript . org-odt-superscript)
78 (table . org-odt-table)
79 (table-cell . org-odt-table-cell)
80 (table-row . org-odt-table-row)
81 (target . org-odt-target)
82 (template . org-odt-template)
83 (timestamp . org-odt-timestamp)
84 (underline . org-odt-underline)
85 (verbatim . org-odt-verbatim)
86 (verse-block . org-odt-verse-block))
87 :export-block "ODT"
88 :filters-alist '((:filter-parse-tree
89 . (org-odt--translate-latex-fragments
90 org-odt--translate-description-lists
91 org-odt--translate-list-tables)))
92 :menu-entry
93 '(?o "Export to ODT"
94 ((?o "As ODT file" org-odt-export-to-odt)
95 (?O "As ODT file and open"
96 (lambda (a s v b)
97 (if a (org-odt-export-to-odt t s v)
98 (org-open-file (org-odt-export-to-odt nil s v) 'system))))))
99 :options-alist
100 '((:odt-styles-file "ODT_STYLES_FILE" nil nil t)
101 ;; Redefine regular option.
102 (:with-latex nil "tex" org-odt-with-latex)))
105 ;;; Dependencies
107 ;;; Hooks
109 ;;; Function Declarations
111 (declare-function org-id-find-id-file "org-id" (id))
112 (declare-function hfy-face-to-style "htmlfontify" (fn))
113 (declare-function hfy-face-or-def-to-name "htmlfontify" (fn))
114 (declare-function archive-zip-extract "arc-mode" (archive name))
115 (declare-function org-create-math-formula "org" (latex-frag &optional mathml-file))
116 (declare-function browse-url-file-url "browse-url" (file))
120 ;;; Internal Variables
122 (defconst org-odt-lib-dir
123 (file-name-directory load-file-name)
124 "Location of ODT exporter.
125 Use this to infer values of `org-odt-styles-dir' and
126 `org-odt-schema-dir'.")
128 (defvar org-odt-data-dir
129 (expand-file-name "../../etc/" org-odt-lib-dir)
130 "Data directory for ODT exporter.
131 Use this to infer values of `org-odt-styles-dir' and
132 `org-odt-schema-dir'.")
134 (defconst org-odt-special-string-regexps
135 '(("\\\\-" . "&#x00ad;\\1") ; shy
136 ("---\\([^-]\\)" . "&#x2014;\\1") ; mdash
137 ("--\\([^-]\\)" . "&#x2013;\\1") ; ndash
138 ("\\.\\.\\." . "&#x2026;")) ; hellip
139 "Regular expressions for special string conversion.")
141 (defconst org-odt-schema-dir-list
142 (list
143 (and org-odt-data-dir
144 (expand-file-name "./schema/" org-odt-data-dir)) ; bail out
145 (eval-when-compile
146 (and (boundp 'org-odt-data-dir) org-odt-data-dir ; see make install
147 (expand-file-name "./schema/" org-odt-data-dir))))
148 "List of directories to search for OpenDocument schema files.
149 Use this list to set the default value of
150 `org-odt-schema-dir'. The entries in this list are
151 populated heuristically based on the values of `org-odt-lib-dir'
152 and `org-odt-data-dir'.")
154 (defconst org-odt-styles-dir-list
155 (list
156 (and org-odt-data-dir
157 (expand-file-name "./styles/" org-odt-data-dir)) ; bail out
158 (eval-when-compile
159 (and (boundp 'org-odt-data-dir) org-odt-data-dir ; see make install
160 (expand-file-name "./styles/" org-odt-data-dir)))
161 (expand-file-name "../../etc/styles/" org-odt-lib-dir) ; git
162 (expand-file-name "./etc/styles/" org-odt-lib-dir) ; elpa
163 (expand-file-name "./org/" data-directory) ; system
165 "List of directories to search for OpenDocument styles files.
166 See `org-odt-styles-dir'. The entries in this list are populated
167 heuristically based on the values of `org-odt-lib-dir' and
168 `org-odt-data-dir'.")
170 (defconst org-odt-styles-dir
171 (let* ((styles-dir
172 (catch 'styles-dir
173 (message "Debug (ox-odt): Searching for OpenDocument styles files...")
174 (mapc (lambda (styles-dir)
175 (when styles-dir
176 (message "Debug (ox-odt): Trying %s..." styles-dir)
177 (when (and (file-readable-p
178 (expand-file-name
179 "OrgOdtContentTemplate.xml" styles-dir))
180 (file-readable-p
181 (expand-file-name
182 "OrgOdtStyles.xml" styles-dir)))
183 (message "Debug (ox-odt): Using styles under %s"
184 styles-dir)
185 (throw 'styles-dir styles-dir))))
186 org-odt-styles-dir-list)
187 nil)))
188 (unless styles-dir
189 (error "Error (ox-odt): Cannot find factory styles files, aborting"))
190 styles-dir)
191 "Directory that holds auxiliary XML files used by the ODT exporter.
193 This directory contains the following XML files -
194 \"OrgOdtStyles.xml\" and \"OrgOdtContentTemplate.xml\". These
195 XML files are used as the default values of
196 `org-odt-styles-file' and
197 `org-odt-content-template-file'.
199 The default value of this variable varies depending on the
200 version of org in use and is initialized from
201 `org-odt-styles-dir-list'. Note that the user could be using org
202 from one of: org's own private git repository, GNU ELPA tar or
203 standard Emacs.")
205 (defconst org-odt-bookmark-prefix "OrgXref.")
207 (defconst org-odt-manifest-file-entry-tag
208 "\n<manifest:file-entry manifest:media-type=\"%s\" manifest:full-path=\"%s\"%s/>")
210 (defconst org-odt-file-extensions
211 '(("odt" . "OpenDocument Text")
212 ("ott" . "OpenDocument Text Template")
213 ("odm" . "OpenDocument Master Document")
214 ("ods" . "OpenDocument Spreadsheet")
215 ("ots" . "OpenDocument Spreadsheet Template")
216 ("odg" . "OpenDocument Drawing (Graphics)")
217 ("otg" . "OpenDocument Drawing Template")
218 ("odp" . "OpenDocument Presentation")
219 ("otp" . "OpenDocument Presentation Template")
220 ("odi" . "OpenDocument Image")
221 ("odf" . "OpenDocument Formula")
222 ("odc" . "OpenDocument Chart")))
224 (defconst org-odt-table-style-format
226 <style:style style:name=\"%s\" style:family=\"table\">
227 <style:table-properties style:rel-width=\"%s%%\" fo:margin-top=\"0cm\" fo:margin-bottom=\"0.20cm\" table:align=\"center\"/>
228 </style:style>
230 "Template for auto-generated Table styles.")
232 (defvar org-odt-automatic-styles '()
233 "Registry of automatic styles for various OBJECT-TYPEs.
234 The variable has the following form:
235 \(\(OBJECT-TYPE-A
236 \(\(OBJECT-NAME-A.1 OBJECT-PROPS-A.1\)
237 \(OBJECT-NAME-A.2 OBJECT-PROPS-A.2\) ...\)\)
238 \(OBJECT-TYPE-B
239 \(\(OBJECT-NAME-B.1 OBJECT-PROPS-B.1\)
240 \(OBJECT-NAME-B.2 OBJECT-PROPS-B.2\) ...\)\)
241 ...\).
243 OBJECT-TYPEs could be \"Section\", \"Table\", \"Figure\" etc.
244 OBJECT-PROPS is (typically) a plist created by passing
245 \"#+ATTR_ODT: \" option to `org-odt-parse-block-attributes'.
247 Use `org-odt-add-automatic-style' to add update this variable.'")
249 (defvar org-odt-object-counters nil
250 "Running counters for various OBJECT-TYPEs.
251 Use this to generate automatic names and style-names. See
252 `org-odt-add-automatic-style'.")
254 (defvar org-odt-src-block-paragraph-format
255 "<style:style style:name=\"OrgSrcBlock\" style:family=\"paragraph\" style:parent-style-name=\"Preformatted_20_Text\">
256 <style:paragraph-properties fo:background-color=\"%s\" fo:padding=\"0.049cm\" fo:border=\"0.51pt solid #000000\" style:shadow=\"none\">
257 <style:background-image/>
258 </style:paragraph-properties>
259 <style:text-properties fo:color=\"%s\"/>
260 </style:style>"
261 "Custom paragraph style for colorized source and example blocks.
262 This style is much the same as that of \"OrgFixedWidthBlock\"
263 except that the foreground and background colors are set
264 according to the default face identified by the `htmlfontify'.")
266 (defvar hfy-optimisations)
267 (defvar org-odt-embedded-formulas-count 0)
268 (defvar org-odt-embedded-images-count 0)
269 (defvar org-odt-image-size-probe-method
270 (append (and (executable-find "identify") '(imagemagick)) ; See Bug#10675
271 '(emacs fixed))
272 "Ordered list of methods for determining image sizes.")
274 (defvar org-odt-default-image-sizes-alist
275 '(("as-char" . (5 . 0.4))
276 ("paragraph" . (5 . 5)))
277 "Hardcoded image dimensions one for each of the anchor
278 methods.")
280 ;; A4 page size is 21.0 by 29.7 cms
281 ;; The default page settings has 2cm margin on each of the sides. So
282 ;; the effective text area is 17.0 by 25.7 cm
283 (defvar org-odt-max-image-size '(17.0 . 20.0)
284 "Limiting dimensions for an embedded image.")
286 (defconst org-odt-label-styles
287 '(("math-formula" "%c" "text" "(%n)")
288 ("math-label" "(%n)" "text" "(%n)")
289 ("category-and-value" "%e %n: %c" "category-and-value" "%e %n")
290 ("value" "%e %n: %c" "value" "%n"))
291 "Specify how labels are applied and referenced.
293 This is an alist where each element is of the form:
295 \(STYLE-NAME ATTACH-FMT REF-MODE REF-FMT)
297 ATTACH-FMT controls how labels and captions are attached to an
298 entity. It may contain following specifiers - %e and %c. %e is
299 replaced with the CATEGORY-NAME. %n is replaced with
300 \"<text:sequence ...> SEQNO </text:sequence>\". %c is replaced
301 with CAPTION.
303 REF-MODE and REF-FMT controls how label references are generated.
304 The following XML is generated for a label reference -
305 \"<text:sequence-ref text:reference-format=\"REF-MODE\" ...>
306 REF-FMT </text:sequence-ref>\". REF-FMT may contain following
307 specifiers - %e and %n. %e is replaced with the CATEGORY-NAME.
308 %n is replaced with SEQNO.
310 See also `org-odt-format-label'.")
312 (defvar org-odt-category-map-alist
313 '(("__Table__" "Table" "value" "Table" org-odt--enumerable-p)
314 ("__Figure__" "Illustration" "value" "Figure" org-odt--enumerable-image-p)
315 ("__MathFormula__" "Text" "math-formula" "Equation" org-odt--enumerable-formula-p)
316 ("__DvipngImage__" "Equation" "value" "Equation" org-odt--enumerable-latex-image-p)
317 ("__Listing__" "Listing" "value" "Listing" org-odt--enumerable-p))
318 "Map a CATEGORY-HANDLE to OD-VARIABLE and LABEL-STYLE.
320 This is a list where each entry is of the form:
322 \(CATEGORY-HANDLE OD-VARIABLE LABEL-STYLE CATEGORY-NAME ENUMERATOR-PREDICATE)
324 CATEGORY_HANDLE identifies the captionable entity in question.
326 OD-VARIABLE is the OpenDocument sequence counter associated with
327 the entity. These counters are declared within
328 \"<text:sequence-decls>...</text:sequence-decls>\" block of
329 `org-odt-content-template-file'.
331 LABEL-STYLE is a key into `org-odt-label-styles' and specifies
332 how a given entity should be captioned and referenced.
334 CATEGORY-NAME is used for qualifying captions on export.
336 ENUMERATOR-PREDICATE is used for assigning a sequence number to
337 the entity. See `org-odt--enumerate'.")
339 (defvar org-odt-manifest-file-entries nil)
340 (defvar hfy-user-sheet-assoc)
342 (defvar org-odt-zip-dir nil
343 "Temporary work directory for OpenDocument exporter.")
347 ;;; User Configuration Variables
349 (defgroup org-export-odt nil
350 "Options for exporting Org mode files to ODT."
351 :tag "Org Export ODT"
352 :group 'org-export)
355 ;;;; Debugging
357 (defcustom org-odt-prettify-xml nil
358 "Specify whether or not the xml output should be prettified.
359 When this option is turned on, `indent-region' is run on all
360 component xml buffers before they are saved. Turn this off for
361 regular use. Turn this on if you need to examine the xml
362 visually."
363 :group 'org-export-odt
364 :version "24.1"
365 :type 'boolean)
368 ;;;; Document schema
370 (require 'rng-loc)
371 (defcustom org-odt-schema-dir
372 (let* ((schema-dir
373 (catch 'schema-dir
374 (message "Debug (ox-odt): Searching for OpenDocument schema files...")
375 (mapc
376 (lambda (schema-dir)
377 (when schema-dir
378 (message "Debug (ox-odt): Trying %s..." schema-dir)
379 (when (and (file-expand-wildcards
380 (expand-file-name "od-manifest-schema*.rnc"
381 schema-dir))
382 (file-expand-wildcards
383 (expand-file-name "od-schema*.rnc"
384 schema-dir))
385 (file-readable-p
386 (expand-file-name "schemas.xml" schema-dir)))
387 (message "Debug (ox-odt): Using schema files under %s"
388 schema-dir)
389 (throw 'schema-dir schema-dir))))
390 org-odt-schema-dir-list)
391 (message "Debug (ox-odt): No OpenDocument schema files installed")
392 nil)))
393 schema-dir)
394 "Directory that contains OpenDocument schema files.
396 This directory contains:
397 1. rnc files for OpenDocument schema
398 2. a \"schemas.xml\" file that specifies locating rules needed
399 for auto validation of OpenDocument XML files.
401 Use the customize interface to set this variable. This ensures
402 that `rng-schema-locating-files' is updated and auto-validation
403 of OpenDocument XML takes place based on the value
404 `rng-nxml-auto-validate-flag'.
406 The default value of this variable varies depending on the
407 version of org in use and is initialized from
408 `org-odt-schema-dir-list'. The OASIS schema files are available
409 only in the org's private git repository. It is *not* bundled
410 with GNU ELPA tar or standard Emacs distribution."
411 :type '(choice
412 (const :tag "Not set" nil)
413 (directory :tag "Schema directory"))
414 :group 'org-export-odt
415 :version "24.1"
416 :set
417 (lambda (var value)
418 "Set `org-odt-schema-dir'.
419 Also add it to `rng-schema-locating-files'."
420 (let ((schema-dir value))
421 (set var
422 (if (and
423 (file-expand-wildcards
424 (expand-file-name "od-manifest-schema*.rnc" schema-dir))
425 (file-expand-wildcards
426 (expand-file-name "od-schema*.rnc" schema-dir))
427 (file-readable-p
428 (expand-file-name "schemas.xml" schema-dir)))
429 schema-dir
430 (when value
431 (message "Error (ox-odt): %s has no OpenDocument schema files"
432 value))
433 nil)))
434 (when org-odt-schema-dir
435 (eval-after-load 'rng-loc
436 '(add-to-list 'rng-schema-locating-files
437 (expand-file-name "schemas.xml"
438 org-odt-schema-dir))))))
441 ;;;; Document styles
443 (defcustom org-odt-content-template-file nil
444 "Template file for \"content.xml\".
445 The exporter embeds the exported content just before
446 \"</office:text>\" element.
448 If unspecified, the file named \"OrgOdtContentTemplate.xml\"
449 under `org-odt-styles-dir' is used."
450 :type '(choice (const nil)
451 (file))
452 :group 'org-export-odt
453 :version "24.3")
455 (defcustom org-odt-styles-file nil
456 "Default styles file for use with ODT export.
457 Valid values are one of:
458 1. nil
459 2. path to a styles.xml file
460 3. path to a *.odt or a *.ott file
461 4. list of the form (ODT-OR-OTT-FILE (FILE-MEMBER-1 FILE-MEMBER-2
462 ...))
464 In case of option 1, an in-built styles.xml is used. See
465 `org-odt-styles-dir' for more information.
467 In case of option 3, the specified file is unzipped and the
468 styles.xml embedded therein is used.
470 In case of option 4, the specified ODT-OR-OTT-FILE is unzipped
471 and FILE-MEMBER-1, FILE-MEMBER-2 etc are copied in to the
472 generated odt file. Use relative path for specifying the
473 FILE-MEMBERS. styles.xml must be specified as one of the
474 FILE-MEMBERS.
476 Use options 1, 2 or 3 only if styles.xml alone suffices for
477 achieving the desired formatting. Use option 4, if the styles.xml
478 references additional files like header and footer images for
479 achieving the desired formatting.
481 Use \"#+ODT_STYLES_FILE: ...\" directive to set this variable on
482 a per-file basis. For example,
484 #+ODT_STYLES_FILE: \"/path/to/styles.xml\" or
485 #+ODT_STYLES_FILE: (\"/path/to/file.ott\" (\"styles.xml\" \"image/hdr.png\"))."
486 :group 'org-export-odt
487 :version "24.1"
488 :type
489 '(choice
490 (const :tag "Factory settings" nil)
491 (file :must-match t :tag "styles.xml")
492 (file :must-match t :tag "ODT or OTT file")
493 (list :tag "ODT or OTT file + Members"
494 (file :must-match t :tag "ODF Text or Text Template file")
495 (cons :tag "Members"
496 (file :tag " Member" "styles.xml")
497 (repeat (file :tag "Member"))))))
499 (defcustom org-odt-display-outline-level 2
500 "Outline levels considered for enumerating captioned entities."
501 :group 'org-export-odt
502 :version "24.4"
503 :package-version '(Org . "8.0")
504 :type 'integer)
506 ;;;; Document conversion
508 (defcustom org-odt-convert-processes
509 '(("LibreOffice"
510 "soffice --headless --convert-to %f%x --outdir %d %i")
511 ("unoconv"
512 "unoconv -f %f -o %d %i"))
513 "Specify a list of document converters and their usage.
514 The converters in this list are offered as choices while
515 customizing `org-odt-convert-process'.
517 This variable is a list where each element is of the
518 form (CONVERTER-NAME CONVERTER-CMD). CONVERTER-NAME is the name
519 of the converter. CONVERTER-CMD is the shell command for the
520 converter and can contain format specifiers. These format
521 specifiers are interpreted as below:
523 %i input file name in full
524 %I input file name as a URL
525 %f format of the output file
526 %o output file name in full
527 %O output file name as a URL
528 %d output dir in full
529 %D output dir as a URL.
530 %x extra options as set in `org-odt-convert-capabilities'."
531 :group 'org-export-odt
532 :version "24.1"
533 :type
534 '(choice
535 (const :tag "None" nil)
536 (alist :tag "Converters"
537 :key-type (string :tag "Converter Name")
538 :value-type (group (string :tag "Command line")))))
540 (defcustom org-odt-convert-process "LibreOffice"
541 "Use this converter to convert from \"odt\" format to other formats.
542 During customization, the list of converter names are populated
543 from `org-odt-convert-processes'."
544 :group 'org-export-odt
545 :version "24.1"
546 :type '(choice :convert-widget
547 (lambda (w)
548 (apply 'widget-convert (widget-type w)
549 (eval (car (widget-get w :args)))))
550 `((const :tag "None" nil)
551 ,@(mapcar (lambda (c)
552 `(const :tag ,(car c) ,(car c)))
553 org-odt-convert-processes))))
555 (defcustom org-odt-convert-capabilities
556 '(("Text"
557 ("odt" "ott" "doc" "rtf" "docx")
558 (("pdf" "pdf") ("odt" "odt") ("rtf" "rtf") ("ott" "ott")
559 ("doc" "doc" ":\"MS Word 97\"") ("docx" "docx") ("html" "html")))
560 ("Web"
561 ("html")
562 (("pdf" "pdf") ("odt" "odt") ("html" "html")))
563 ("Spreadsheet"
564 ("ods" "ots" "xls" "csv" "xlsx")
565 (("pdf" "pdf") ("ots" "ots") ("html" "html") ("csv" "csv") ("ods" "ods")
566 ("xls" "xls") ("xlsx" "xlsx")))
567 ("Presentation"
568 ("odp" "otp" "ppt" "pptx")
569 (("pdf" "pdf") ("swf" "swf") ("odp" "odp") ("otp" "otp") ("ppt" "ppt")
570 ("pptx" "pptx") ("odg" "odg"))))
571 "Specify input and output formats of `org-odt-convert-process'.
572 More correctly, specify the set of input and output formats that
573 the user is actually interested in.
575 This variable is an alist where each element is of the
576 form (DOCUMENT-CLASS INPUT-FMT-LIST OUTPUT-FMT-ALIST).
577 INPUT-FMT-LIST is a list of INPUT-FMTs. OUTPUT-FMT-ALIST is an
578 alist where each element is of the form (OUTPUT-FMT
579 OUTPUT-FILE-EXTENSION EXTRA-OPTIONS).
581 The variable is interpreted as follows:
582 `org-odt-convert-process' can take any document that is in
583 INPUT-FMT-LIST and produce any document that is in the
584 OUTPUT-FMT-LIST. A document converted to OUTPUT-FMT will have
585 OUTPUT-FILE-EXTENSION as the file name extension. OUTPUT-FMT
586 serves dual purposes:
587 - It is used for populating completion candidates during
588 `org-odt-convert' commands.
589 - It is used as the value of \"%f\" specifier in
590 `org-odt-convert-process'.
592 EXTRA-OPTIONS is used as the value of \"%x\" specifier in
593 `org-odt-convert-process'.
595 DOCUMENT-CLASS is used to group a set of file formats in
596 INPUT-FMT-LIST in to a single class.
598 Note that this variable inherently captures how LibreOffice based
599 converters work. LibreOffice maps documents of various formats
600 to classes like Text, Web, Spreadsheet, Presentation etc and
601 allow document of a given class (irrespective of its source
602 format) to be converted to any of the export formats associated
603 with that class.
605 See default setting of this variable for an typical
606 configuration."
607 :group 'org-export-odt
608 :version "24.1"
609 :type
610 '(choice
611 (const :tag "None" nil)
612 (alist :tag "Capabilities"
613 :key-type (string :tag "Document Class")
614 :value-type
615 (group (repeat :tag "Input formats" (string :tag "Input format"))
616 (alist :tag "Output formats"
617 :key-type (string :tag "Output format")
618 :value-type
619 (group (string :tag "Output file extension")
620 (choice
621 (const :tag "None" nil)
622 (string :tag "Extra options"))))))))
624 (defcustom org-odt-preferred-output-format nil
625 "Automatically post-process to this format after exporting to \"odt\".
626 Command `org-odt-export-to-odt' exports first to \"odt\" format
627 and then uses `org-odt-convert-process' to convert the
628 resulting document to this format. During customization of this
629 variable, the list of valid values are populated based on
630 `org-odt-convert-capabilities'.
632 You can set this option on per-file basis using file local
633 values. See Info node `(emacs) File Variables'."
634 :group 'org-export-odt
635 :version "24.1"
636 :type '(choice :convert-widget
637 (lambda (w)
638 (apply 'widget-convert (widget-type w)
639 (eval (car (widget-get w :args)))))
640 `((const :tag "None" nil)
641 ,@(mapcar (lambda (c)
642 `(const :tag ,c ,c))
643 (org-odt-reachable-formats "odt")))))
644 ;;;###autoload
645 (put 'org-odt-preferred-output-format 'safe-local-variable 'stringp)
648 ;;;; Drawers
650 (defcustom org-odt-format-drawer-function
651 (lambda (name contents) contents)
652 "Function called to format a drawer in ODT code.
654 The function must accept two parameters:
655 NAME the drawer name, like \"LOGBOOK\"
656 CONTENTS the contents of the drawer.
658 The function should return the string to be exported.
660 The default value simply returns the value of CONTENTS."
661 :group 'org-export-odt
662 :version "24.4"
663 :package-version '(Org . "8.3")
664 :type 'function)
667 ;;;; Headline
669 (defcustom org-odt-format-headline-function 'ignore
670 "Function to format headline text.
672 This function will be called with 5 arguments:
673 TODO the todo keyword \(string or nil\).
674 TODO-TYPE the type of todo \(symbol: `todo', `done', nil\)
675 PRIORITY the priority of the headline \(integer or nil\)
676 TEXT the main headline text \(string\).
677 TAGS the tags string, separated with colons \(string or nil\).
679 The function result will be used as headline text."
680 :group 'org-export-odt
681 :version "24.4"
682 :package-version '(Org . "8.0")
683 :type 'function)
686 ;;;; Inlinetasks
688 (defcustom org-odt-format-inlinetask-function 'ignore
689 "Function called to format an inlinetask in ODT code.
691 The function must accept six parameters:
692 TODO the todo keyword, as a string
693 TODO-TYPE the todo type, a symbol among `todo', `done' and nil.
694 PRIORITY the inlinetask priority, as a string
695 NAME the inlinetask name, as a string.
696 TAGS the inlinetask tags, as a string.
697 CONTENTS the contents of the inlinetask, as a string.
699 The function should return the string to be exported."
700 :group 'org-export-odt
701 :version "24.4"
702 :package-version '(Org . "8.0")
703 :type 'function)
706 ;;;; LaTeX
708 (defcustom org-odt-with-latex org-export-with-latex
709 "Non-nil means process LaTeX math snippets.
711 When set, the exporter will process LaTeX environments and
712 fragments.
714 This option can also be set with the +OPTIONS line,
715 e.g. \"tex:mathjax\". Allowed values are:
717 nil Ignore math snippets.
718 `verbatim' Keep everything in verbatim
719 `dvipng' Process the LaTeX fragments to images. This will also
720 include processing of non-math environments.
721 `imagemagick' Convert the LaTeX fragments to pdf files and use
722 imagemagick to convert pdf files to png files.
723 `mathjax' Do MathJax preprocessing and arrange for MathJax.js to
724 be loaded.
725 t Synonym for `mathjax'."
726 :group 'org-export-odt
727 :version "24.4"
728 :package-version '(Org . "8.0")
729 :type '(choice
730 (const :tag "Do not process math in any way" nil)
731 (const :tag "Use dvipng to make images" dvipng)
732 (const :tag "Use imagemagick to make images" imagemagick)
733 (const :tag "Use MathJax to display math" mathjax)
734 (const :tag "Leave math verbatim" verbatim)))
737 ;;;; Links
739 (defcustom org-odt-inline-formula-rules
740 '(("file" . "\\.\\(mathml\\|mml\\|odf\\)\\'"))
741 "Rules characterizing formula files that can be inlined into ODT.
743 A rule consists in an association whose key is the type of link
744 to consider, and value is a regexp that will be matched against
745 link's path."
746 :group 'org-export-odt
747 :version "24.4"
748 :package-version '(Org . "8.0")
749 :type '(alist :key-type (string :tag "Type")
750 :value-type (regexp :tag "Path")))
752 (defcustom org-odt-inline-image-rules
753 '(("file" . "\\.\\(jpeg\\|jpg\\|png\\|gif\\)\\'"))
754 "Rules characterizing image files that can be inlined into ODT.
756 A rule consists in an association whose key is the type of link
757 to consider, and value is a regexp that will be matched against
758 link's path."
759 :group 'org-export-odt
760 :version "24.4"
761 :package-version '(Org . "8.0")
762 :type '(alist :key-type (string :tag "Type")
763 :value-type (regexp :tag "Path")))
765 (defcustom org-odt-pixels-per-inch 96.0
766 "Scaling factor for converting images pixels to inches.
767 Use this for sizing of embedded images. See Info node `(org)
768 Images in ODT export' for more information."
769 :type 'float
770 :group 'org-export-odt
771 :version "24.4"
772 :package-version '(Org . "8.1"))
775 ;;;; Src Block
777 (defcustom org-odt-create-custom-styles-for-srcblocks t
778 "Whether custom styles for colorized source blocks be automatically created.
779 When this option is turned on, the exporter creates custom styles
780 for source blocks based on the advice of `htmlfontify'. Creation
781 of custom styles happen as part of `org-odt-hfy-face-to-css'.
783 When this option is turned off exporter does not create such
784 styles.
786 Use the latter option if you do not want the custom styles to be
787 based on your current display settings. It is necessary that the
788 styles.xml already contains needed styles for colorizing to work.
790 This variable is effective only if
791 `org-odt-fontify-srcblocks' is turned on."
792 :group 'org-export-odt
793 :version "24.1"
794 :type 'boolean)
796 (defcustom org-odt-fontify-srcblocks t
797 "Specify whether or not source blocks need to be fontified.
798 Turn this option on if you want to colorize the source code
799 blocks in the exported file. For colorization to work, you need
800 to make available an enhanced version of `htmlfontify' library."
801 :type 'boolean
802 :group 'org-export-odt
803 :version "24.1")
806 ;;;; Table
808 (defcustom org-odt-table-styles
809 '(("OrgEquation" "OrgEquation"
810 ((use-first-column-styles . t)
811 (use-last-column-styles . t)))
812 ("TableWithHeaderRowAndColumn" "Custom"
813 ((use-first-row-styles . t)
814 (use-first-column-styles . t)))
815 ("TableWithFirstRowandLastRow" "Custom"
816 ((use-first-row-styles . t)
817 (use-last-row-styles . t)))
818 ("GriddedTable" "Custom" nil))
819 "Specify how Table Styles should be derived from a Table Template.
820 This is a list where each element is of the
821 form (TABLE-STYLE-NAME TABLE-TEMPLATE-NAME TABLE-CELL-OPTIONS).
823 TABLE-STYLE-NAME is the style associated with the table through
824 \"#+ATTR_ODT: :style TABLE-STYLE-NAME\" line.
826 TABLE-TEMPLATE-NAME is a set of - upto 9 - automatic
827 TABLE-CELL-STYLE-NAMEs and PARAGRAPH-STYLE-NAMEs (as defined
828 below) that is included in
829 `org-odt-content-template-file'.
831 TABLE-CELL-STYLE-NAME := TABLE-TEMPLATE-NAME + TABLE-CELL-TYPE +
832 \"TableCell\"
833 PARAGRAPH-STYLE-NAME := TABLE-TEMPLATE-NAME + TABLE-CELL-TYPE +
834 \"TableParagraph\"
835 TABLE-CELL-TYPE := \"FirstRow\" | \"LastColumn\" |
836 \"FirstRow\" | \"LastRow\" |
837 \"EvenRow\" | \"OddRow\" |
838 \"EvenColumn\" | \"OddColumn\" | \"\"
839 where \"+\" above denotes string concatenation.
841 TABLE-CELL-OPTIONS is an alist where each element is of the
842 form (TABLE-CELL-STYLE-SELECTOR . ON-OR-OFF).
843 TABLE-CELL-STYLE-SELECTOR := `use-first-row-styles' |
844 `use-last-row-styles' |
845 `use-first-column-styles' |
846 `use-last-column-styles' |
847 `use-banding-rows-styles' |
848 `use-banding-columns-styles' |
849 `use-first-row-styles'
850 ON-OR-OFF := `t' | `nil'
852 For example, with the following configuration
854 \(setq org-odt-table-styles
855 '\(\(\"TableWithHeaderRowsAndColumns\" \"Custom\"
856 \(\(use-first-row-styles . t\)
857 \(use-first-column-styles . t\)\)\)
858 \(\"TableWithHeaderColumns\" \"Custom\"
859 \(\(use-first-column-styles . t\)\)\)\)\)
861 1. A table associated with \"TableWithHeaderRowsAndColumns\"
862 style will use the following table-cell styles -
863 \"CustomFirstRowTableCell\", \"CustomFirstColumnTableCell\",
864 \"CustomTableCell\" and the following paragraph styles
865 \"CustomFirstRowTableParagraph\",
866 \"CustomFirstColumnTableParagraph\", \"CustomTableParagraph\"
867 as appropriate.
869 2. A table associated with \"TableWithHeaderColumns\" style will
870 use the following table-cell styles -
871 \"CustomFirstColumnTableCell\", \"CustomTableCell\" and the
872 following paragraph styles
873 \"CustomFirstColumnTableParagraph\", \"CustomTableParagraph\"
874 as appropriate..
876 Note that TABLE-TEMPLATE-NAME corresponds to the
877 \"<table:table-template>\" elements contained within
878 \"<office:styles>\". The entries (TABLE-STYLE-NAME
879 TABLE-TEMPLATE-NAME TABLE-CELL-OPTIONS) correspond to
880 \"table:template-name\" and \"table:use-first-row-styles\" etc
881 attributes of \"<table:table>\" element. Refer ODF-1.2
882 specification for more information. Also consult the
883 implementation filed under `org-odt-get-table-cell-styles'.
885 The TABLE-STYLE-NAME \"OrgEquation\" is used internally for
886 formatting of numbered display equations. Do not delete this
887 style from the list."
888 :group 'org-export-odt
889 :version "24.1"
890 :type '(choice
891 (const :tag "None" nil)
892 (repeat :tag "Table Styles"
893 (list :tag "Table Style Specification"
894 (string :tag "Table Style Name")
895 (string :tag "Table Template Name")
896 (alist :options (use-first-row-styles
897 use-last-row-styles
898 use-first-column-styles
899 use-last-column-styles
900 use-banding-rows-styles
901 use-banding-columns-styles)
902 :key-type symbol
903 :value-type (const :tag "True" t))))))
905 ;;;; Timestamps
907 (defcustom org-odt-use-date-fields nil
908 "Non-nil, if timestamps should be exported as date fields.
910 When nil, export timestamps as plain text.
912 When non-nil, map `org-time-stamp-custom-formats' to a pair of
913 OpenDocument date-styles with names \"OrgDate1\" and \"OrgDate2\"
914 respectively. A timestamp with no time component is formatted
915 with style \"OrgDate1\" while one with explicit hour and minutes
916 is formatted with style \"OrgDate2\".
918 This feature is experimental. Most (but not all) of the common
919 %-specifiers in `format-time-string' are supported.
920 Specifically, locale-dependent specifiers like \"%c\", \"%x\" are
921 formatted as canonical Org timestamps. For finer control, avoid
922 these %-specifiers.
924 Textual specifiers like \"%b\", \"%h\", \"%B\", \"%a\", \"%A\"
925 etc., are displayed by the application in the default language
926 and country specified in `org-odt-styles-file'. Note that the
927 default styles file uses language \"en\" and country \"GB\". You
928 can localize the week day and month strings in the exported
929 document by setting the default language and country either using
930 the application UI or through a custom styles file.
932 See `org-odt--build-date-styles' for implementation details."
933 :group 'org-export-odt
934 :version "24.4"
935 :package-version '(Org . "8.0")
936 :type 'boolean)
940 ;;; Internal functions
942 ;;;; Date
944 (defun org-odt--format-timestamp (timestamp &optional end iso-date-p)
945 (let* ((format-timestamp
946 (lambda (timestamp format &optional end utc)
947 (if timestamp
948 (org-timestamp-format timestamp format end utc)
949 (format-time-string format nil utc))))
950 (has-time-p (or (not timestamp)
951 (org-timestamp-has-time-p timestamp)))
952 (iso-date (let ((format (if has-time-p "%Y-%m-%dT%H:%M:%S"
953 "%Y-%m-%dT%H:%M:%S")))
954 (funcall format-timestamp timestamp format end))))
955 (if iso-date-p iso-date
956 (let* ((style (if has-time-p "OrgDate2" "OrgDate1"))
957 ;; LibreOffice does not care about end goes as content
958 ;; within the "<text:date>...</text:date>" field. The
959 ;; displayed date is automagically corrected to match the
960 ;; format requested by "style:data-style-name" attribute. So
961 ;; don't bother about formatting the date contents to be
962 ;; compatible with "OrgDate1" and "OrgDateTime" styles. A
963 ;; simple Org-style date should suffice.
964 (date (let* ((formats
965 (if org-display-custom-times
966 (cons (substring
967 (car org-time-stamp-custom-formats) 1 -1)
968 (substring
969 (cdr org-time-stamp-custom-formats) 1 -1))
970 '("%Y-%m-%d %a" . "%Y-%m-%d %a %H:%M")))
971 (format (if has-time-p (cdr formats) (car formats))))
972 (funcall format-timestamp timestamp format end)))
973 (repeater (let ((repeater-type (org-element-property
974 :repeater-type timestamp))
975 (repeater-value (org-element-property
976 :repeater-value timestamp))
977 (repeater-unit (org-element-property
978 :repeater-unit timestamp)))
979 (concat
980 (case repeater-type
981 (catchup "++") (restart ".+") (cumulate "+"))
982 (when repeater-value
983 (number-to-string repeater-value))
984 (case repeater-unit
985 (hour "h") (day "d") (week "w") (month "m")
986 (year "y"))))))
987 (concat
988 (format "<text:date text:date-value=\"%s\" style:data-style-name=\"%s\" text:fixed=\"true\">%s</text:date>"
989 iso-date style date)
990 (and (not (string= repeater "")) " ")
991 repeater)))))
993 ;;;; Frame
995 (defun org-odt--frame (text width height style &optional extra
996 anchor-type &rest title-and-desc)
997 (let ((frame-attrs
998 (concat
999 (if width (format " svg:width=\"%0.2fcm\"" width) "")
1000 (if height (format " svg:height=\"%0.2fcm\"" height) "")
1001 extra
1002 (format " text:anchor-type=\"%s\"" (or anchor-type "paragraph"))
1003 (format " draw:name=\"%s\""
1004 (car (org-odt-add-automatic-style "Frame"))))))
1005 (format
1006 "\n<draw:frame draw:style-name=\"%s\"%s>\n%s\n</draw:frame>"
1007 style frame-attrs
1008 (concat text
1009 (let ((title (car title-and-desc))
1010 (desc (cadr title-and-desc)))
1011 (concat (when title
1012 (format "<svg:title>%s</svg:title>"
1013 (org-odt--encode-plain-text title t)))
1014 (when desc
1015 (format "<svg:desc>%s</svg:desc>"
1016 (org-odt--encode-plain-text desc t)))))))))
1019 ;;;; Library wrappers
1021 (defun org-odt--zip-extract (archive members target)
1022 (when (atom members) (setq members (list members)))
1023 (mapc (lambda (member)
1024 (require 'arc-mode)
1025 (let* ((--quote-file-name
1026 ;; This is shamelessly stolen from `archive-zip-extract'.
1027 (lambda (name)
1028 (if (or (not (memq system-type '(windows-nt ms-dos)))
1029 (and (boundp 'w32-quote-process-args)
1030 (null w32-quote-process-args)))
1031 (shell-quote-argument name)
1032 name)))
1033 (target (funcall --quote-file-name target))
1034 (archive (expand-file-name archive))
1035 (archive-zip-extract
1036 (list "unzip" "-qq" "-o" "-d" target))
1037 exit-code command-output)
1038 (setq command-output
1039 (with-temp-buffer
1040 (setq exit-code (archive-zip-extract archive member))
1041 (buffer-string)))
1042 (unless (zerop exit-code)
1043 (message command-output)
1044 (error "Extraction failed"))))
1045 members))
1047 ;;;; Target
1049 (defun org-odt--target (text id)
1050 (if (not id) text
1051 (concat
1052 (format "\n<text:bookmark-start text:name=\"OrgXref.%s\"/>" id)
1053 (format "\n<text:bookmark text:name=\"%s\"/>" id) text
1054 (format "\n<text:bookmark-end text:name=\"OrgXref.%s\"/>" id))))
1056 ;;;; Textbox
1058 (defun org-odt--textbox (text width height style &optional
1059 extra anchor-type)
1060 (org-odt--frame
1061 (format "\n<draw:text-box %s>%s\n</draw:text-box>"
1062 (concat (format " fo:min-height=\"%0.2fcm\"" (or height .2))
1063 (and (not width)
1064 (format " fo:min-width=\"%0.2fcm\"" (or width .2))))
1065 text)
1066 width nil style extra anchor-type))
1070 ;;;; Table of Contents
1072 (defun org-odt-begin-toc (index-title depth)
1073 (concat
1074 (format "
1075 <text:table-of-content text:style-name=\"OrgIndexSection\" text:protected=\"true\" text:name=\"Table of Contents\">
1076 <text:table-of-content-source text:outline-level=\"%d\">
1077 <text:index-title-template text:style-name=\"Contents_20_Heading\">%s</text:index-title-template>
1078 " depth index-title)
1080 (let ((levels (number-sequence 1 10)))
1081 (mapconcat
1082 (lambda (level)
1083 (format
1085 <text:table-of-content-entry-template text:outline-level=\"%d\" text:style-name=\"Contents_20_%d\">
1086 <text:index-entry-link-start text:style-name=\"Internet_20_link\"/>
1087 <text:index-entry-chapter/>
1088 <text:index-entry-text/>
1089 <text:index-entry-link-end/>
1090 </text:table-of-content-entry-template>
1091 " level level)) levels ""))
1093 (format "
1094 </text:table-of-content-source>
1096 <text:index-body>
1097 <text:index-title text:style-name=\"Sect1\" text:name=\"Table of Contents1_Head\">
1098 <text:p text:style-name=\"Contents_20_Heading\">%s</text:p>
1099 </text:index-title>
1100 " index-title)))
1102 (defun org-odt-end-toc ()
1103 (format "
1104 </text:index-body>
1105 </text:table-of-content>
1108 (defun* org-odt-format-toc-headline
1109 (todo todo-type priority text tags
1110 &key level section-number headline-label &allow-other-keys)
1111 (setq text
1112 (concat
1113 ;; Section number.
1114 (when section-number (concat section-number ". "))
1115 ;; Todo.
1116 (when todo
1117 (let ((style (if (member todo org-done-keywords)
1118 "OrgDone" "OrgTodo")))
1119 (format "<text:span text:style-name=\"%s\">%s</text:span> "
1120 style todo)))
1121 (when priority
1122 (let* ((style (format "OrgPriority-%s" priority))
1123 (priority (format "[#%c]" priority)))
1124 (format "<text:span text:style-name=\"%s\">%s</text:span> "
1125 style priority)))
1126 ;; Title.
1127 text
1128 ;; Tags.
1129 (when tags
1130 (concat
1131 (format " <text:span text:style-name=\"%s\">[%s]</text:span>"
1132 "OrgTags"
1133 (mapconcat
1134 (lambda (tag)
1135 (format
1136 "<text:span text:style-name=\"%s\">%s</text:span>"
1137 "OrgTag" tag)) tags " : "))))))
1138 (format "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
1139 headline-label text))
1141 (defun org-odt-toc (depth info)
1142 (assert (wholenump depth))
1143 ;; When a headline is marked as a radio target, as in the example below:
1145 ;; ** <<<Some Heading>>>
1146 ;; Some text.
1148 ;; suppress generation of radio targets. i.e., Radio targets are to
1149 ;; be marked as targets within /document body/ and *not* within
1150 ;; /TOC/, as otherwise there will be duplicated anchors one in TOC
1151 ;; and one in the document body.
1153 ;; FIXME-1: Currently exported headings are memoized. `org-export.el'
1154 ;; doesn't provide a way to disable memoization. So this doesn't
1155 ;; work.
1157 ;; FIXME-2: Are there any other objects that need to be suppressed
1158 ;; within TOC?
1159 (let* ((title (org-export-translate "Table of Contents" :utf-8 info))
1160 (headlines (org-export-collect-headlines
1161 info (and (wholenump depth) depth)))
1162 (backend (org-export-create-backend
1163 :parent (org-export-backend-name
1164 (plist-get info :back-end))
1165 :transcoders (mapcar
1166 (lambda (type) (cons type (lambda (d c i) c)))
1167 (list 'radio-target)))))
1168 (when headlines
1169 (concat
1170 (org-odt-begin-toc title depth)
1171 (mapconcat
1172 (lambda (headline)
1173 (let* ((entry (org-odt-format-headline--wrap
1174 headline backend info 'org-odt-format-toc-headline))
1175 (level (org-export-get-relative-level headline info))
1176 (style (format "Contents_20_%d" level)))
1177 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1178 style entry)))
1179 headlines "\n")
1180 (org-odt-end-toc)))))
1183 ;;;; Document styles
1185 (defun org-odt-add-automatic-style (object-type &optional object-props)
1186 "Create an automatic style of type OBJECT-TYPE with param OBJECT-PROPS.
1187 OBJECT-PROPS is (typically) a plist created by passing
1188 \"#+ATTR_ODT: \" option of the object in question to
1189 `org-odt-parse-block-attributes'.
1191 Use `org-odt-object-counters' to generate an automatic
1192 OBJECT-NAME and STYLE-NAME. If OBJECT-PROPS is non-nil, add a
1193 new entry in `org-odt-automatic-styles'. Return (OBJECT-NAME
1194 . STYLE-NAME)."
1195 (assert (stringp object-type))
1196 (let* ((object (intern object-type))
1197 (seqvar object)
1198 (seqno (1+ (or (plist-get org-odt-object-counters seqvar) 0)))
1199 (object-name (format "%s%d" object-type seqno)) style-name)
1200 (setq org-odt-object-counters
1201 (plist-put org-odt-object-counters seqvar seqno))
1202 (when object-props
1203 (setq style-name (format "Org%s" object-name))
1204 (setq org-odt-automatic-styles
1205 (plist-put org-odt-automatic-styles object
1206 (append (list (list style-name object-props))
1207 (plist-get org-odt-automatic-styles object)))))
1208 (cons object-name style-name)))
1210 ;;;; Checkbox
1212 (defun org-odt--checkbox (item)
1213 "Return check-box string associated to ITEM."
1214 (let ((checkbox (org-element-property :checkbox item)))
1215 (if (not checkbox) ""
1216 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1217 "OrgCode" (case checkbox
1218 (on "[&#x2713;] ") ; CHECK MARK
1219 (off "[ ] ")
1220 (trans "[-] "))))))
1222 ;;; Template
1224 (defun org-odt--build-date-styles (fmt style)
1225 ;; In LibreOffice 3.4.6, there doesn't seem to be a convenient way
1226 ;; to modify the date fields. A date could be modified by
1227 ;; offsetting in days. That's about it. Also, date and time may
1228 ;; have to be emitted as two fields - a date field and a time field
1229 ;; - separately.
1231 ;; One can add Form Controls to date and time fields so that they
1232 ;; can be easily modified. But then, the exported document will
1233 ;; become tightly coupled with LibreOffice and may not function
1234 ;; properly with other OpenDocument applications.
1236 ;; I have a strange feeling that Date styles are a bit flaky at the
1237 ;; moment.
1239 ;; The feature is experimental.
1240 (when (and fmt style)
1241 (let* ((fmt-alist
1242 '(("%A" . "<number:day-of-week number:style=\"long\"/>")
1243 ("%B" . "<number:month number:textual=\"true\" number:style=\"long\"/>")
1244 ("%H" . "<number:hours number:style=\"long\"/>")
1245 ("%M" . "<number:minutes number:style=\"long\"/>")
1246 ("%S" . "<number:seconds number:style=\"long\"/>")
1247 ("%V" . "<number:week-of-year/>")
1248 ("%Y" . "<number:year number:style=\"long\"/>")
1249 ("%a" . "<number:day-of-week number:style=\"short\"/>")
1250 ("%b" . "<number:month number:textual=\"true\" number:style=\"short\"/>")
1251 ("%d" . "<number:day number:style=\"long\"/>")
1252 ("%e" . "<number:day number:style=\"short\"/>")
1253 ("%h" . "<number:month number:textual=\"true\" number:style=\"short\"/>")
1254 ("%k" . "<number:hours number:style=\"short\"/>")
1255 ("%m" . "<number:month number:style=\"long\"/>")
1256 ("%p" . "<number:am-pm/>")
1257 ("%y" . "<number:year number:style=\"short\"/>")))
1258 (case-fold-search nil)
1259 (re (mapconcat 'identity (mapcar 'car fmt-alist) "\\|"))
1260 match rpl (start 0) (filler-beg 0) filler-end filler output)
1261 (mapc
1262 (lambda (pair)
1263 (setq fmt (replace-regexp-in-string (car pair) (cdr pair) fmt t t)))
1264 '(("\\(?:%[[:digit:]]*N\\)" . "") ; strip ns, us and ns
1265 ("%C" . "Y") ; replace century with year
1266 ("%D" . "%m/%d/%y")
1267 ("%G" . "Y") ; year corresponding to iso week
1268 ("%I" . "%H") ; hour on a 12-hour clock
1269 ("%R" . "%H:%M")
1270 ("%T" . "%H:%M:%S")
1271 ("%U\\|%W" . "%V") ; week no. starting on Sun./Mon.
1272 ("%Z" . "") ; time zone name
1273 ("%c" . "%Y-%M-%d %a %H:%M" ) ; locale's date and time format
1274 ("%g" . "%y")
1275 ("%X" . "%x" ) ; locale's pref. time format
1276 ("%j" . "") ; day of the year
1277 ("%l" . "%k") ; like %I blank-padded
1278 ("%s" . "") ; no. of secs since 1970-01-01 00:00:00 +0000
1279 ("%n" . "<text:line-break/>")
1280 ("%r" . "%I:%M:%S %p")
1281 ("%t" . "<text:tab/>")
1282 ("%u\\|%w" . "") ; numeric day of week - Mon (1-7), Sun(0-6)
1283 ("%x" . "%Y-%M-%d %a") ; locale's pref. time format
1284 ("%z" . "") ; time zone in numeric form
1286 (while (string-match re fmt start)
1287 (setq match (match-string 0 fmt))
1288 (setq rpl (assoc-default match fmt-alist))
1289 (setq start (match-end 0))
1290 (setq filler-end (match-beginning 0))
1291 (setq filler (substring fmt (prog1 filler-beg
1292 (setq filler-beg (match-end 0)))
1293 filler-end))
1294 (setq filler (and (not (string= filler ""))
1295 (format "<number:text>%s</number:text>"
1296 (org-odt--encode-plain-text filler))))
1297 (setq output (concat output "\n" filler "\n" rpl)))
1298 (setq filler (substring fmt filler-beg))
1299 (unless (string= filler "")
1300 (setq output (concat output
1301 (format "\n<number:text>%s</number:text>"
1302 (org-odt--encode-plain-text filler)))))
1303 (format "\n<number:date-style style:name=\"%s\" %s>%s\n</number:date-style>"
1304 style
1305 (concat " number:automatic-order=\"true\""
1306 " number:format-source=\"fixed\"")
1307 output ))))
1309 (defun org-odt-template (contents info)
1310 "Return complete document string after ODT conversion.
1311 CONTENTS is the transcoded contents string. RAW-DATA is the
1312 original parsed data. INFO is a plist holding export options."
1313 ;; Write meta file.
1314 (let ((title (org-export-data (plist-get info :title) info))
1315 (author (let ((author (plist-get info :author)))
1316 (if (not author) "" (org-export-data author info))))
1317 (email (plist-get info :email))
1318 (keywords (plist-get info :keywords))
1319 (description (plist-get info :description)))
1320 (write-region
1321 (concat
1322 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
1323 <office:document-meta
1324 xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"
1325 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
1326 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
1327 xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"
1328 xmlns:ooo=\"http://openoffice.org/2004/office\"
1329 office:version=\"1.2\">
1330 <office:meta>\n"
1331 (format "<dc:creator>%s</dc:creator>\n" author)
1332 (format "<meta:initial-creator>%s</meta:initial-creator>\n" author)
1333 ;; Date, if required.
1334 (when (plist-get info :with-date)
1335 ;; Check if DATE is specified as an Org-timestamp. If yes,
1336 ;; include it as meta information. Otherwise, just use
1337 ;; today's date.
1338 (let* ((date (let ((date (plist-get info :date)))
1339 (and (not (cdr date))
1340 (eq (org-element-type (car date)) 'timestamp)
1341 (car date)))))
1342 (let ((iso-date (org-odt--format-timestamp date nil 'iso-date)))
1343 (concat
1344 (format "<dc:date>%s</dc:date>\n" iso-date)
1345 (format "<meta:creation-date>%s</meta:creation-date>\n"
1346 iso-date)))))
1347 (format "<meta:generator>%s</meta:generator>\n"
1348 (let ((creator-info (plist-get info :with-creator)))
1349 (if (or (not creator-info) (eq creator-info 'comment)) ""
1350 (plist-get info :creator))))
1351 (format "<meta:keyword>%s</meta:keyword>\n" keywords)
1352 (format "<dc:subject>%s</dc:subject>\n" description)
1353 (format "<dc:title>%s</dc:title>\n" title)
1354 "\n"
1355 " </office:meta>\n" "</office:document-meta>")
1356 nil (concat org-odt-zip-dir "meta.xml"))
1357 ;; Add meta.xml in to manifest.
1358 (org-odt-create-manifest-file-entry "text/xml" "meta.xml"))
1360 ;; Update styles file.
1361 ;; Copy styles.xml. Also dump htmlfontify styles, if there is any.
1362 ;; Write styles file.
1363 (let* ((styles-file (plist-get info :odt-styles-file))
1364 (styles-file (and styles-file (read (org-trim styles-file))))
1365 ;; Non-availability of styles.xml is not a critical
1366 ;; error. For now, throw an error.
1367 (styles-file (or styles-file
1368 org-odt-styles-file
1369 (expand-file-name "OrgOdtStyles.xml"
1370 org-odt-styles-dir)
1371 (error "org-odt: Missing styles file?"))))
1372 (cond
1373 ((listp styles-file)
1374 (let ((archive (nth 0 styles-file))
1375 (members (nth 1 styles-file)))
1376 (org-odt--zip-extract archive members org-odt-zip-dir)
1377 (mapc
1378 (lambda (member)
1379 (when (org-file-image-p member)
1380 (let* ((image-type (file-name-extension member))
1381 (media-type (format "image/%s" image-type)))
1382 (org-odt-create-manifest-file-entry media-type member))))
1383 members)))
1384 ((and (stringp styles-file) (file-exists-p styles-file))
1385 (let ((styles-file-type (file-name-extension styles-file)))
1386 (cond
1387 ((string= styles-file-type "xml")
1388 (copy-file styles-file (concat org-odt-zip-dir "styles.xml") t))
1389 ((member styles-file-type '("odt" "ott"))
1390 (org-odt--zip-extract styles-file "styles.xml" org-odt-zip-dir)))))
1392 (error (format "Invalid specification of styles.xml file: %S"
1393 org-odt-styles-file))))
1395 ;; create a manifest entry for styles.xml
1396 (org-odt-create-manifest-file-entry "text/xml" "styles.xml")
1398 ;; FIXME: Who is opening an empty styles.xml before this point?
1399 (with-current-buffer
1400 (find-file-noselect (concat org-odt-zip-dir "styles.xml") t)
1401 (revert-buffer t t)
1403 ;; Write custom styles for source blocks
1404 ;; Save STYLES used for colorizing of source blocks.
1405 ;; Update styles.xml with styles that were collected as part of
1406 ;; `org-odt-hfy-face-to-css' callbacks.
1407 (let ((styles (mapconcat (lambda (style) (format " %s\n" (cddr style)))
1408 hfy-user-sheet-assoc "")))
1409 (when styles
1410 (goto-char (point-min))
1411 (when (re-search-forward "</office:styles>" nil t)
1412 (goto-char (match-beginning 0))
1413 (insert "\n<!-- Org Htmlfontify Styles -->\n" styles "\n"))))
1415 ;; Update styles.xml - take care of outline numbering
1417 ;; Don't make automatic backup of styles.xml file. This setting
1418 ;; prevents the backed-up styles.xml file from being zipped in to
1419 ;; odt file. This is more of a hackish fix. Better alternative
1420 ;; would be to fix the zip command so that the output odt file
1421 ;; includes only the needed files and excludes any auto-generated
1422 ;; extra files like backups and auto-saves etc etc. Note that
1423 ;; currently the zip command zips up the entire temp directory so
1424 ;; that any auto-generated files created under the hood ends up in
1425 ;; the resulting odt file.
1426 (set (make-local-variable 'backup-inhibited) t)
1428 ;; Outline numbering is retained only upto LEVEL.
1429 ;; To disable outline numbering pass a LEVEL of 0.
1431 (goto-char (point-min))
1432 (let ((regex
1433 "<text:outline-level-style\\([^>]*\\)text:level=\"\\([^\"]*\\)\"\\([^>]*\\)>")
1434 (replacement
1435 "<text:outline-level-style\\1text:level=\"\\2\" style:num-format=\"\">"))
1436 (while (re-search-forward regex nil t)
1437 (unless (let ((sec-num (plist-get info :section-numbers))
1438 (level (string-to-number (match-string 2))))
1439 (if (wholenump sec-num) (<= level sec-num) sec-num))
1440 (replace-match replacement t nil))))
1441 (save-buffer 0)))
1442 ;; Update content.xml.
1444 (let* ( ;; `org-display-custom-times' should be accessed right
1445 ;; within the context of the Org buffer. So obtain its
1446 ;; value before moving on to temp-buffer context down below.
1447 (custom-time-fmts
1448 (if org-display-custom-times
1449 (cons (substring (car org-time-stamp-custom-formats) 1 -1)
1450 (substring (cdr org-time-stamp-custom-formats) 1 -1))
1451 '("%Y-%M-%d %a" . "%Y-%M-%d %a %H:%M"))))
1452 (with-temp-buffer
1453 (insert-file-contents
1454 (or org-odt-content-template-file
1455 (expand-file-name "OrgOdtContentTemplate.xml"
1456 org-odt-styles-dir)))
1457 ;; Write automatic styles.
1458 ;; - Position the cursor.
1459 (goto-char (point-min))
1460 (re-search-forward " </office:automatic-styles>" nil t)
1461 (goto-char (match-beginning 0))
1462 ;; - Dump automatic table styles.
1463 (loop for (style-name props) in
1464 (plist-get org-odt-automatic-styles 'Table) do
1465 (when (setq props (or (plist-get props :rel-width) "96"))
1466 (insert (format org-odt-table-style-format style-name props))))
1467 ;; - Dump date-styles.
1468 (when org-odt-use-date-fields
1469 (insert (org-odt--build-date-styles (car custom-time-fmts)
1470 "OrgDate1")
1471 (org-odt--build-date-styles (cdr custom-time-fmts)
1472 "OrgDate2")))
1473 ;; Update display level.
1474 ;; - Remove existing sequence decls. Also position the cursor.
1475 (goto-char (point-min))
1476 (when (re-search-forward "<text:sequence-decls" nil t)
1477 (delete-region (match-beginning 0)
1478 (re-search-forward "</text:sequence-decls>" nil nil)))
1479 ;; Update sequence decls according to user preference.
1480 (insert
1481 (format
1482 "\n<text:sequence-decls>\n%s\n</text:sequence-decls>"
1483 (mapconcat
1484 (lambda (x)
1485 (format
1486 "<text:sequence-decl text:display-outline-level=\"%d\" text:name=\"%s\"/>"
1487 org-odt-display-outline-level (nth 1 x)))
1488 org-odt-category-map-alist "\n")))
1489 ;; Position the cursor to document body.
1490 (goto-char (point-min))
1491 (re-search-forward "</office:text>" nil nil)
1492 (goto-char (match-beginning 0))
1494 ;; Preamble - Title, Author, Date etc.
1495 (insert
1496 (let* ((title (org-export-data (plist-get info :title) info))
1497 (author (and (plist-get info :with-author)
1498 (let ((auth (plist-get info :author)))
1499 (and auth (org-export-data auth info)))))
1500 (email (plist-get info :email))
1501 ;; Switch on or off above vars based on user settings
1502 (author (and (plist-get info :with-author) (or author email)))
1503 (email (and (plist-get info :with-email) email)))
1504 (concat
1505 ;; Title.
1506 (when title
1507 (concat
1508 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1509 "OrgTitle" (format "\n<text:title>%s</text:title>" title))
1510 ;; Separator.
1511 "\n<text:p text:style-name=\"OrgTitle\"/>"))
1512 (cond
1513 ((and author (not email))
1514 ;; Author only.
1515 (concat
1516 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1517 "OrgSubtitle"
1518 (format "<text:initial-creator>%s</text:initial-creator>" author))
1519 ;; Separator.
1520 "\n<text:p text:style-name=\"OrgSubtitle\"/>"))
1521 ((and author email)
1522 ;; Author and E-mail.
1523 (concat
1524 (format
1525 "\n<text:p text:style-name=\"%s\">%s</text:p>"
1526 "OrgSubtitle"
1527 (format
1528 "<text:a xlink:type=\"simple\" xlink:href=\"%s\">%s</text:a>"
1529 (concat "mailto:" email)
1530 (format "<text:initial-creator>%s</text:initial-creator>" author)))
1531 ;; Separator.
1532 "\n<text:p text:style-name=\"OrgSubtitle\"/>")))
1533 ;; Date, if required.
1534 (when (plist-get info :with-date)
1535 (let* ((date (plist-get info :date))
1536 ;; Check if DATE is specified as a timestamp.
1537 (timestamp (and (not (cdr date))
1538 (eq (org-element-type (car date)) 'timestamp)
1539 (car date))))
1540 (concat
1541 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1542 "OrgSubtitle"
1543 (if (and org-odt-use-date-fields timestamp)
1544 (org-odt--format-timestamp (car date))
1545 (org-export-data (plist-get info :date) info)))
1546 ;; Separator
1547 "<text:p text:style-name=\"OrgSubtitle\"/>"))))))
1548 ;; Table of Contents
1549 (let* ((with-toc (plist-get info :with-toc))
1550 (depth (and with-toc (if (wholenump with-toc)
1551 with-toc
1552 (plist-get info :headline-levels)))))
1553 (when depth (insert (or (org-odt-toc depth info) ""))))
1554 ;; Contents.
1555 (insert contents)
1556 ;; Return contents.
1557 (buffer-substring-no-properties (point-min) (point-max)))))
1561 ;;; Transcode Functions
1563 ;;;; Bold
1565 (defun org-odt-bold (bold contents info)
1566 "Transcode BOLD from Org to ODT.
1567 CONTENTS is the text with bold markup. INFO is a plist holding
1568 contextual information."
1569 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1570 "Bold" contents))
1573 ;;;; Center Block
1575 (defun org-odt-center-block (center-block contents info)
1576 "Transcode a CENTER-BLOCK element from Org to ODT.
1577 CONTENTS holds the contents of the center block. INFO is a plist
1578 holding contextual information."
1579 contents)
1582 ;;;; Clock
1584 (defun org-odt-clock (clock contents info)
1585 "Transcode a CLOCK element from Org to ODT.
1586 CONTENTS is nil. INFO is a plist used as a communication
1587 channel."
1588 (let ((timestamp (org-element-property :value clock))
1589 (duration (org-element-property :duration clock)))
1590 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1591 (if (eq (org-element-type (org-export-get-next-element clock info))
1592 'clock) "OrgClock" "OrgClockLastLine")
1593 (concat
1594 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1595 "OrgClockKeyword" org-clock-string)
1596 (org-odt-timestamp timestamp contents info)
1597 (and duration (format " (%s)" duration))))))
1600 ;;;; Code
1602 (defun org-odt-code (code contents info)
1603 "Transcode a CODE object from Org to ODT.
1604 CONTENTS is nil. INFO is a plist used as a communication
1605 channel."
1606 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1607 "OrgCode" (org-odt--encode-plain-text
1608 (org-element-property :value code))))
1611 ;;;; Comment
1613 ;; Comments are ignored.
1616 ;;;; Comment Block
1618 ;; Comment Blocks are ignored.
1621 ;;;; Drawer
1623 (defun org-odt-drawer (drawer contents info)
1624 "Transcode a DRAWER element from Org to ODT.
1625 CONTENTS holds the contents of the block. INFO is a plist
1626 holding contextual information."
1627 (let* ((name (org-element-property :drawer-name drawer))
1628 (output (funcall org-odt-format-drawer-function
1629 name contents)))
1630 output))
1633 ;;;; Dynamic Block
1635 (defun org-odt-dynamic-block (dynamic-block contents info)
1636 "Transcode a DYNAMIC-BLOCK element from Org to ODT.
1637 CONTENTS holds the contents of the block. INFO is a plist
1638 holding contextual information. See `org-export-data'."
1639 contents)
1642 ;;;; Entity
1644 (defun org-odt-entity (entity contents info)
1645 "Transcode an ENTITY object from Org to ODT.
1646 CONTENTS are the definition itself. INFO is a plist holding
1647 contextual information."
1648 (org-element-property :utf-8 entity))
1651 ;;;; Example Block
1653 (defun org-odt-example-block (example-block contents info)
1654 "Transcode a EXAMPLE-BLOCK element from Org to ODT.
1655 CONTENTS is nil. INFO is a plist holding contextual information."
1656 (org-odt-format-code example-block info))
1659 ;;;; Export Snippet
1661 (defun org-odt-export-snippet (export-snippet contents info)
1662 "Transcode a EXPORT-SNIPPET object from Org to ODT.
1663 CONTENTS is nil. INFO is a plist holding contextual information."
1664 (when (eq (org-export-snippet-backend export-snippet) 'odt)
1665 (org-element-property :value export-snippet)))
1668 ;;;; Export Block
1670 (defun org-odt-export-block (export-block contents info)
1671 "Transcode a EXPORT-BLOCK element from Org to ODT.
1672 CONTENTS is nil. INFO is a plist holding contextual information."
1673 (when (string= (org-element-property :type export-block) "ODT")
1674 (org-remove-indentation (org-element-property :value export-block))))
1677 ;;;; Fixed Width
1679 (defun org-odt-fixed-width (fixed-width contents info)
1680 "Transcode a FIXED-WIDTH element from Org to ODT.
1681 CONTENTS is nil. INFO is a plist holding contextual information."
1682 (org-odt-do-format-code (org-element-property :value fixed-width)))
1685 ;;;; Footnote Definition
1687 ;; Footnote Definitions are ignored.
1690 ;;;; Footnote Reference
1692 (defun org-odt-footnote-reference (footnote-reference contents info)
1693 "Transcode a FOOTNOTE-REFERENCE element from Org to ODT.
1694 CONTENTS is nil. INFO is a plist holding contextual information."
1695 (let ((--format-footnote-definition
1696 (function
1697 (lambda (n def)
1698 (setq n (format "%d" n))
1699 (let ((id (concat "fn" n))
1700 (note-class "footnote")
1701 (par-style "Footnote"))
1702 (format
1703 "<text:note text:id=\"%s\" text:note-class=\"%s\">%s</text:note>"
1704 id note-class
1705 (concat
1706 (format "<text:note-citation>%s</text:note-citation>" n)
1707 (format "<text:note-body>%s</text:note-body>" def)))))))
1708 (--format-footnote-reference
1709 (function
1710 (lambda (n)
1711 (setq n (format "%d" n))
1712 (let ((note-class "footnote")
1713 (ref-format "text")
1714 (ref-name (concat "fn" n)))
1715 (format
1716 "<text:span text:style-name=\"%s\">%s</text:span>"
1717 "OrgSuperscript"
1718 (format "<text:note-ref text:note-class=\"%s\" text:reference-format=\"%s\" text:ref-name=\"%s\">%s</text:note-ref>"
1719 note-class ref-format ref-name n)))))))
1720 (concat
1721 ;; Insert separator between two footnotes in a row.
1722 (let ((prev (org-export-get-previous-element footnote-reference info)))
1723 (and (eq (org-element-type prev) 'footnote-reference)
1724 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1725 "OrgSuperscript" ",")))
1726 ;; Transcode footnote reference.
1727 (let ((n (org-export-get-footnote-number footnote-reference info)))
1728 (cond
1729 ((not (org-export-footnote-first-reference-p footnote-reference info))
1730 (funcall --format-footnote-reference n))
1731 ;; Inline definitions are secondary strings.
1732 ;; Non-inline footnotes definitions are full Org data.
1734 (let* ((raw (org-export-get-footnote-definition
1735 footnote-reference info))
1736 (def
1737 (let ((def (org-trim
1738 (org-export-data-with-backend
1740 (org-export-create-backend
1741 :parent 'odt
1742 :transcoders
1743 '((paragraph . (lambda (p c i)
1744 (org-odt--format-paragraph
1745 p c "Footnote"
1746 "OrgFootnoteCenter"
1747 "OrgFootnoteQuotations")))))
1748 info))))
1749 (if (eq (org-element-type raw) 'org-data) def
1750 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1751 "Footnote" def)))))
1752 (funcall --format-footnote-definition n def))))))))
1755 ;;;; Headline
1757 (defun* org-odt-format-headline
1758 (todo todo-type priority text tags
1759 &key level section-number headline-label &allow-other-keys)
1760 (concat
1761 ;; Todo.
1762 (when todo
1763 (let ((style (if (member todo org-done-keywords) "OrgDone" "OrgTodo")))
1764 (format "<text:span text:style-name=\"%s\">%s</text:span> "
1765 style todo)))
1766 (when priority
1767 (let* ((style (format "OrgPriority-%s" priority))
1768 (priority (format "[#%c]" priority)))
1769 (format "<text:span text:style-name=\"%s\">%s</text:span> "
1770 style priority)))
1771 ;; Title.
1772 text
1773 ;; Tags.
1774 (when tags
1775 (concat
1776 "<text:tab/>"
1777 (format "<text:span text:style-name=\"%s\">[%s]</text:span>"
1778 "OrgTags" (mapconcat
1779 (lambda (tag)
1780 (format
1781 "<text:span text:style-name=\"%s\">%s</text:span>"
1782 "OrgTag" tag)) tags " : "))))))
1784 (defun org-odt-format-headline--wrap (headline backend info
1785 &optional format-function
1786 &rest extra-keys)
1787 "Transcode a HEADLINE element using BACKEND.
1788 INFO is a plist holding contextual information."
1789 (setq backend (or backend (plist-get info :back-end)))
1790 (let* ((level (+ (org-export-get-relative-level headline info)))
1791 (headline-number (org-export-get-headline-number headline info))
1792 (section-number (and (org-export-numbered-headline-p headline info)
1793 (mapconcat 'number-to-string
1794 headline-number ".")))
1795 (todo (and (plist-get info :with-todo-keywords)
1796 (let ((todo (org-element-property :todo-keyword headline)))
1797 (and todo
1798 (org-export-data-with-backend todo backend info)))))
1799 (todo-type (and todo (org-element-property :todo-type headline)))
1800 (priority (and (plist-get info :with-priority)
1801 (org-element-property :priority headline)))
1802 (text (org-export-data-with-backend
1803 (org-element-property :title headline) backend info))
1804 (tags (and (plist-get info :with-tags)
1805 (org-export-get-tags headline info)))
1806 (headline-label (concat "sec-" (mapconcat 'number-to-string
1807 headline-number "-")))
1808 (format-function (cond
1809 ((functionp format-function) format-function)
1810 ((not (eq org-odt-format-headline-function 'ignore))
1811 (function*
1812 (lambda (todo todo-type priority text tags
1813 &allow-other-keys)
1814 (funcall org-odt-format-headline-function
1815 todo todo-type priority text tags))))
1816 (t 'org-odt-format-headline))))
1817 (apply format-function
1818 todo todo-type priority text tags
1819 :headline-label headline-label :level level
1820 :section-number section-number extra-keys)))
1822 (defun org-odt-headline (headline contents info)
1823 "Transcode a HEADLINE element from Org to ODT.
1824 CONTENTS holds the contents of the headline. INFO is a plist
1825 holding contextual information."
1826 ;; Case 1: This is a footnote section: ignore it.
1827 (unless (org-element-property :footnote-section-p headline)
1828 (let* ((text (org-export-data (org-element-property :title headline) info))
1829 ;; Create the headline text.
1830 (full-text (org-odt-format-headline--wrap headline nil info))
1831 ;; Get level relative to current parsed data.
1832 (level (org-export-get-relative-level headline info))
1833 ;; Get canonical label for the headline.
1834 (id (concat "sec-" (mapconcat 'number-to-string
1835 (org-export-get-headline-number
1836 headline info) "-")))
1837 ;; Get user-specified labels for the headline.
1838 (extra-ids (list (org-element-property :CUSTOM_ID headline)
1839 (org-element-property :ID headline)))
1840 ;; Extra targets.
1841 (extra-targets
1842 (mapconcat (lambda (x)
1843 (when x
1844 (let ((x (if (org-uuidgen-p x) (concat "ID-" x) x)))
1845 (org-odt--target
1846 "" (org-export-solidify-link-text x)))))
1847 extra-ids ""))
1848 ;; Title.
1849 (anchored-title (org-odt--target full-text id)))
1850 (cond
1851 ;; Case 2. This is a deep sub-tree: export it as a list item.
1852 ;; Also export as items headlines for which no section
1853 ;; format has been found.
1854 ((org-export-low-level-p headline info)
1855 ;; Build the real contents of the sub-tree.
1856 (concat
1857 (and (org-export-first-sibling-p headline info)
1858 (format "\n<text:list text:style-name=\"%s\" %s>"
1859 ;; Choose style based on list type.
1860 (if (org-export-numbered-headline-p headline info)
1861 "OrgNumberedList" "OrgBulletedList")
1862 ;; If top-level list, re-start numbering. Otherwise,
1863 ;; continue numbering.
1864 (format "text:continue-numbering=\"%s\""
1865 (let* ((parent (org-export-get-parent-headline
1866 headline)))
1867 (if (and parent
1868 (org-export-low-level-p parent info))
1869 "true" "false")))))
1870 (let ((headline-has-table-p
1871 (let ((section (assq 'section (org-element-contents headline))))
1872 (assq 'table (and section (org-element-contents section))))))
1873 (format "\n<text:list-item>\n%s\n%s"
1874 (concat
1875 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1876 "Text_20_body"
1877 (concat extra-targets anchored-title))
1878 contents)
1879 (if headline-has-table-p
1880 "</text:list-header>"
1881 "</text:list-item>")))
1882 (and (org-export-last-sibling-p headline info)
1883 "</text:list>")))
1884 ;; Case 3. Standard headline. Export it as a section.
1886 (concat
1887 (format
1888 "\n<text:h text:style-name=\"%s\" text:outline-level=\"%s\">%s</text:h>"
1889 (format "Heading_20_%s" level)
1890 level
1891 (concat extra-targets anchored-title))
1892 contents))))))
1895 ;;;; Horizontal Rule
1897 (defun org-odt-horizontal-rule (horizontal-rule contents info)
1898 "Transcode an HORIZONTAL-RULE object from Org to ODT.
1899 CONTENTS is nil. INFO is a plist holding contextual information."
1900 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1901 "Horizontal_20_Line" ""))
1904 ;;;; Inline Babel Call
1906 ;; Inline Babel Calls are ignored.
1909 ;;;; Inline Src Block
1911 (defun org-odt--find-verb-separator (s)
1912 "Return a character not used in string S.
1913 This is used to choose a separator for constructs like \\verb."
1914 (let ((ll "~,./?;':\"|!@#%^&-_=+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>()[]{}"))
1915 (loop for c across ll
1916 when (not (string-match (regexp-quote (char-to-string c)) s))
1917 return (char-to-string c))))
1919 (defun org-odt-inline-src-block (inline-src-block contents info)
1920 "Transcode an INLINE-SRC-BLOCK element from Org to ODT.
1921 CONTENTS holds the contents of the item. INFO is a plist holding
1922 contextual information."
1923 (let* ((org-lang (org-element-property :language inline-src-block))
1924 (code (org-element-property :value inline-src-block))
1925 (separator (org-odt--find-verb-separator code)))
1926 (error "FIXME")))
1929 ;;;; Inlinetask
1931 (defun org-odt-inlinetask (inlinetask contents info)
1932 "Transcode an INLINETASK element from Org to ODT.
1933 CONTENTS holds the contents of the block. INFO is a plist
1934 holding contextual information."
1935 (cond
1936 ;; If `org-odt-format-inlinetask-function' is not 'ignore, call it
1937 ;; with appropriate arguments.
1938 ((not (eq org-odt-format-inlinetask-function 'ignore))
1939 (let ((format-function
1940 (function*
1941 (lambda (todo todo-type priority text tags
1942 &key contents &allow-other-keys)
1943 (funcall org-odt-format-inlinetask-function
1944 todo todo-type priority text tags contents)))))
1945 (org-odt-format-headline--wrap
1946 inlinetask nil info format-function :contents contents)))
1947 ;; Otherwise, use a default template.
1949 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1950 "Text_20_body"
1951 (org-odt--textbox
1952 (concat
1953 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1954 "OrgInlineTaskHeading"
1955 (org-odt-format-headline--wrap inlinetask nil info))
1956 contents)
1957 nil nil "OrgInlineTaskFrame" " style:rel-width=\"100%\"")))))
1959 ;;;; Italic
1961 (defun org-odt-italic (italic contents info)
1962 "Transcode ITALIC from Org to ODT.
1963 CONTENTS is the text with italic markup. INFO is a plist holding
1964 contextual information."
1965 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1966 "Emphasis" contents))
1969 ;;;; Item
1971 (defun org-odt-item (item contents info)
1972 "Transcode an ITEM element from Org to ODT.
1973 CONTENTS holds the contents of the item. INFO is a plist holding
1974 contextual information."
1975 (let* ((plain-list (org-export-get-parent item))
1976 (type (org-element-property :type plain-list))
1977 (counter (org-element-property :counter item))
1978 (tag (let ((tag (org-element-property :tag item)))
1979 (and tag
1980 (concat (org-odt--checkbox item)
1981 (org-export-data tag info))))))
1982 (case type
1983 ((ordered unordered descriptive-1 descriptive-2)
1984 (format "\n<text:list-item>\n%s\n%s"
1985 contents
1986 (let* ((--element-has-a-table-p
1987 (function
1988 (lambda (element info)
1989 (loop for el in (org-element-contents element)
1990 thereis (eq (org-element-type el) 'table))))))
1991 (cond
1992 ((funcall --element-has-a-table-p item info)
1993 "</text:list-header>")
1994 (t "</text:list-item>")))))
1995 (t (error "Unknown list type: %S" type)))))
1997 ;;;; Keyword
1999 (defun org-odt-keyword (keyword contents info)
2000 "Transcode a KEYWORD element from Org to ODT.
2001 CONTENTS is nil. INFO is a plist holding contextual information."
2002 (let ((key (org-element-property :key keyword))
2003 (value (org-element-property :value keyword)))
2004 (cond
2005 ((string= key "ODT") value)
2006 ((string= key "INDEX")
2007 ;; FIXME
2008 (ignore))
2009 ((string= key "TOC")
2010 (let ((value (downcase value)))
2011 (cond
2012 ((string-match "\\<headlines\\>" value)
2013 (let ((depth (or (and (string-match "[0-9]+" value)
2014 (string-to-number (match-string 0 value)))
2015 (plist-get info :with-toc))))
2016 (when (wholenump depth) (org-odt-toc depth info))))
2017 ((member value '("tables" "figures" "listings"))
2018 ;; FIXME
2019 (ignore))))))))
2022 ;;;; Latex Environment
2025 ;; (eval-after-load 'ox-odt '(ad-deactivate 'org-format-latex-as-mathml))
2026 ;; (defadvice org-format-latex-as-mathml ; FIXME
2027 ;; (after org-odt-protect-latex-fragment activate)
2028 ;; "Encode LaTeX fragment as XML.
2029 ;; Do this when translation to MathML fails."
2030 ;; (unless (> (length ad-return-value) 0)
2031 ;; (setq ad-return-value (org-odt--encode-plain-text (ad-get-arg 0)))))
2033 (defun org-odt-latex-environment (latex-environment contents info)
2034 "Transcode a LATEX-ENVIRONMENT element from Org to ODT.
2035 CONTENTS is nil. INFO is a plist holding contextual information."
2036 (let* ((latex-frag (org-remove-indentation
2037 (org-element-property :value latex-environment))))
2038 (org-odt-do-format-code latex-frag)))
2041 ;;;; Latex Fragment
2043 ;; (when latex-frag ; FIXME
2044 ;; (setq href (org-propertize href :title "LaTeX Fragment"
2045 ;; :description latex-frag)))
2046 ;; handle verbatim
2047 ;; provide descriptions
2049 (defun org-odt-latex-fragment (latex-fragment contents info)
2050 "Transcode a LATEX-FRAGMENT object from Org to ODT.
2051 CONTENTS is nil. INFO is a plist holding contextual information."
2052 (let* ((latex-frag (org-element-property :value latex-fragment))
2053 (processing-type (plist-get info :with-latex)))
2054 (format "<text:span text:style-name=\"%s\">%s</text:span>"
2055 "OrgCode" (org-odt--encode-plain-text latex-frag t))))
2058 ;;;; Line Break
2060 (defun org-odt-line-break (line-break contents info)
2061 "Transcode a LINE-BREAK object from Org to ODT.
2062 CONTENTS is nil. INFO is a plist holding contextual information."
2063 "<text:line-break/>")
2066 ;;;; Link
2068 ;;;; Links :: Label references
2070 (defun org-odt--enumerate (element info &optional predicate n)
2071 (when predicate (assert (funcall predicate element info)))
2072 (let* ((--numbered-parent-headline-at-<=-n
2073 (function
2074 (lambda (element n info)
2075 (loop for x in (org-export-get-genealogy element)
2076 thereis (and (eq (org-element-type x) 'headline)
2077 (<= (org-export-get-relative-level x info) n)
2078 (org-export-numbered-headline-p x info)
2079 x)))))
2080 (--enumerate
2081 (function
2082 (lambda (element scope info &optional predicate)
2083 (let ((counter 0))
2084 (org-element-map (or scope (plist-get info :parse-tree))
2085 (org-element-type element)
2086 (lambda (el)
2087 (and (or (not predicate) (funcall predicate el info))
2088 (incf counter)
2089 (eq element el)
2090 counter))
2091 info 'first-match)))))
2092 (scope (funcall --numbered-parent-headline-at-<=-n
2093 element (or n org-odt-display-outline-level) info))
2094 (ordinal (funcall --enumerate element scope info predicate))
2095 (tag
2096 (concat
2097 ;; Section number.
2098 (and scope
2099 (mapconcat 'number-to-string
2100 (org-export-get-headline-number scope info) "."))
2101 ;; Separator.
2102 (and scope ".")
2103 ;; Ordinal.
2104 (number-to-string ordinal))))
2105 tag))
2107 (defun org-odt-format-label (element info op)
2108 "Return a label for ELEMENT.
2110 ELEMENT is a `link', `table', `src-block' or `paragraph' type
2111 element. INFO is a plist used as a communication channel. OP is
2112 either `definition' or `reference', depending on the purpose of
2113 the generated string.
2115 Return value is a string if OP is set to `reference' or a cons
2116 cell like CAPTION . SHORT-CAPTION) where CAPTION and
2117 SHORT-CAPTION are strings."
2118 (assert (memq (org-element-type element) '(link table src-block paragraph)))
2119 (let* ((caption-from
2120 (case (org-element-type element)
2121 (link (org-export-get-parent-element element))
2122 (t element)))
2123 ;; Get label and caption.
2124 (label (org-element-property :name caption-from))
2125 (caption (org-export-get-caption caption-from))
2126 (caption (and caption (org-export-data caption info)))
2127 ;; FIXME: We don't use short-caption for now
2128 (short-caption nil))
2129 (when (or label caption)
2130 (let* ((default-category
2131 (case (org-element-type element)
2132 (table "__Table__")
2133 (src-block "__Listing__")
2134 ((link paragraph)
2135 (cond
2136 ((org-odt--enumerable-latex-image-p element info)
2137 "__DvipngImage__")
2138 ((org-odt--enumerable-image-p element info)
2139 "__Figure__")
2140 ((org-odt--enumerable-formula-p element info)
2141 "__MathFormula__")
2142 (t (error "Don't know how to format label for link: %S"
2143 element))))
2144 (t (error "Don't know how to format label for element type: %s"
2145 (org-element-type element)))))
2146 seqno)
2147 (assert default-category)
2148 (destructuring-bind (counter label-style category predicate)
2149 (assoc-default default-category org-odt-category-map-alist)
2150 ;; Compute sequence number of the element.
2151 (setq seqno (org-odt--enumerate element info predicate))
2152 ;; Localize category string.
2153 (setq category (org-export-translate category :utf-8 info))
2154 (case op
2155 ;; Case 1: Handle Label definition.
2156 (definition
2157 ;; Assign an internal label, if user has not provided one
2158 (setq label (org-export-solidify-link-text
2159 (or label (format "%s-%s" default-category seqno))))
2160 (cons
2161 (concat
2162 ;; Sneak in a bookmark. The bookmark is used when the
2163 ;; labeled element is referenced with a link that
2164 ;; provides its own description.
2165 (format "\n<text:bookmark text:name=\"%s\"/>" label)
2166 ;; Label definition: Typically formatted as below:
2167 ;; CATEGORY SEQ-NO: LONG CAPTION
2168 ;; with translation for correct punctuation.
2169 (format-spec
2170 (org-export-translate
2171 (cadr (assoc-string label-style org-odt-label-styles t))
2172 :utf-8 info)
2173 `((?e . ,category)
2174 (?n . ,(format
2175 "<text:sequence text:ref-name=\"%s\" text:name=\"%s\" text:formula=\"ooow:%s+1\" style:num-format=\"1\">%s</text:sequence>"
2176 label counter counter seqno))
2177 (?c . ,(or caption "")))))
2178 short-caption))
2179 ;; Case 2: Handle Label reference.
2180 (reference
2181 (assert label)
2182 (setq label (org-export-solidify-link-text label))
2183 (let* ((fmt (cddr (assoc-string label-style org-odt-label-styles t)))
2184 (fmt1 (car fmt))
2185 (fmt2 (cadr fmt)))
2186 (format "<text:sequence-ref text:reference-format=\"%s\" text:ref-name=\"%s\">%s</text:sequence-ref>"
2187 fmt1 label (format-spec fmt2 `((?e . ,category)
2188 (?n . ,seqno))))))
2189 (t (error "Unknown %S on label" op))))))))
2192 ;;;; Links :: Inline Images
2194 (defun org-odt--copy-image-file (path)
2195 "Returns the internal name of the file"
2196 (let* ((image-type (file-name-extension path))
2197 (media-type (format "image/%s" image-type))
2198 (target-dir "Images/")
2199 (target-file
2200 (format "%s%04d.%s" target-dir
2201 (incf org-odt-embedded-images-count) image-type)))
2202 (message "Embedding %s as %s..."
2203 (substring-no-properties path) target-file)
2205 (when (= 1 org-odt-embedded-images-count)
2206 (make-directory (concat org-odt-zip-dir target-dir))
2207 (org-odt-create-manifest-file-entry "" target-dir))
2209 (copy-file path (concat org-odt-zip-dir target-file) 'overwrite)
2210 (org-odt-create-manifest-file-entry media-type target-file)
2211 target-file))
2213 (defun org-odt--image-size (file &optional user-width
2214 user-height scale dpi embed-as)
2215 (let* ((--pixels-to-cms
2216 (function (lambda (pixels dpi)
2217 (let ((cms-per-inch 2.54)
2218 (inches (/ pixels dpi)))
2219 (* cms-per-inch inches)))))
2220 (--size-in-cms
2221 (function
2222 (lambda (size-in-pixels dpi)
2223 (and size-in-pixels
2224 (cons (funcall --pixels-to-cms (car size-in-pixels) dpi)
2225 (funcall --pixels-to-cms (cdr size-in-pixels) dpi))))))
2226 (dpi (or dpi org-odt-pixels-per-inch))
2227 (anchor-type (or embed-as "paragraph"))
2228 (user-width (and (not scale) user-width))
2229 (user-height (and (not scale) user-height))
2230 (size
2231 (and
2232 (not (and user-height user-width))
2234 ;; Use Imagemagick.
2235 (and (executable-find "identify")
2236 (let ((size-in-pixels
2237 (let ((dim (shell-command-to-string
2238 (format "identify -format \"%%w:%%h\" \"%s\""
2239 file))))
2240 (when (string-match "\\([0-9]+\\):\\([0-9]+\\)" dim)
2241 (cons (string-to-number (match-string 1 dim))
2242 (string-to-number (match-string 2 dim)))))))
2243 (funcall --size-in-cms size-in-pixels dpi)))
2244 ;; Use Emacs.
2245 (let ((size-in-pixels
2246 (ignore-errors ; Emacs could be in batch mode
2247 (clear-image-cache)
2248 (image-size (create-image file) 'pixels))))
2249 (funcall --size-in-cms size-in-pixels dpi))
2250 ;; Use hard-coded values.
2251 (cdr (assoc-string anchor-type
2252 org-odt-default-image-sizes-alist))
2253 ;; Error out.
2254 (error "Cannot determine image size, aborting"))))
2255 (width (car size)) (height (cdr size)))
2256 (cond
2257 (scale
2258 (setq width (* width scale) height (* height scale)))
2259 ((and user-height user-width)
2260 (setq width user-width height user-height))
2261 (user-height
2262 (setq width (* user-height (/ width height)) height user-height))
2263 (user-width
2264 (setq height (* user-width (/ height width)) width user-width))
2265 (t (ignore)))
2266 ;; ensure that an embedded image fits comfortably within a page
2267 (let ((max-width (car org-odt-max-image-size))
2268 (max-height (cdr org-odt-max-image-size)))
2269 (when (or (> width max-width) (> height max-height))
2270 (let* ((scale1 (/ max-width width))
2271 (scale2 (/ max-height height))
2272 (scale (min scale1 scale2)))
2273 (setq width (* scale width) height (* scale height)))))
2274 (cons width height)))
2276 (defun org-odt-link--inline-image (element info)
2277 "Return ODT code for an inline image.
2278 LINK is the link pointing to the inline image. INFO is a plist
2279 used as a communication channel."
2280 (assert (eq (org-element-type element) 'link))
2281 (let* ((src (let* ((type (org-element-property :type element))
2282 (raw-path (org-element-property :path element)))
2283 (cond ((member type '("http" "https"))
2284 (concat type ":" raw-path))
2285 ((file-name-absolute-p raw-path)
2286 (expand-file-name raw-path))
2287 (t raw-path))))
2288 (src-expanded (if (file-name-absolute-p src) src
2289 (expand-file-name src (file-name-directory
2290 (plist-get info :input-file)))))
2291 (href (format
2292 "\n<draw:image xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>"
2293 (org-odt--copy-image-file src-expanded)))
2294 ;; Extract attributes from #+ATTR_ODT line.
2295 (attr-from (case (org-element-type element)
2296 (link (org-export-get-parent-element element))
2297 (t element)))
2298 ;; Convert attributes to a plist.
2299 (attr-plist (org-export-read-attribute :attr_odt attr-from))
2300 ;; Handle `:anchor', `:style' and `:attributes' properties.
2301 (user-frame-anchor
2302 (car (assoc-string (plist-get attr-plist :anchor)
2303 '(("as-char") ("paragraph") ("page")) t)))
2304 (user-frame-style
2305 (and user-frame-anchor (plist-get attr-plist :style)))
2306 (user-frame-attrs
2307 (and user-frame-anchor (plist-get attr-plist :attributes)))
2308 (user-frame-params
2309 (list user-frame-style user-frame-attrs user-frame-anchor))
2310 ;; (embed-as (or embed-as user-frame-anchor "paragraph"))
2312 ;; Handle `:width', `:height' and `:scale' properties. Read
2313 ;; them as numbers since we need them for computations.
2314 (size (org-odt--image-size
2315 src-expanded
2316 (let ((width (plist-get attr-plist :width)))
2317 (and width (read width)))
2318 (let ((length (plist-get attr-plist :length)))
2319 (and length (read length)))
2320 (let ((scale (plist-get attr-plist :scale)))
2321 (and scale (read scale)))
2322 nil ; embed-as
2323 "paragraph" ; FIXME
2325 (width (car size)) (height (cdr size))
2326 (standalone-link-p (org-odt--standalone-link-p element info))
2327 (embed-as (if standalone-link-p "paragraph" "as-char"))
2328 (captions (org-odt-format-label element info 'definition))
2329 (caption (car captions)) (short-caption (cdr captions))
2330 (entity (concat (and caption "Captioned") embed-as "Image"))
2331 ;; Check if this link was created by LaTeX-to-PNG converter.
2332 (replaces (org-element-property
2333 :replaces (if (not standalone-link-p) element
2334 (org-export-get-parent-element element))))
2335 ;; If yes, note down the type of the element - LaTeX Fragment
2336 ;; or LaTeX environment. It will go in to frame title.
2337 (title (and replaces (capitalize
2338 (symbol-name (org-element-type replaces)))))
2340 ;; If yes, note down its contents. It will go in to frame
2341 ;; description. This quite useful for debugging.
2342 (desc (and replaces (org-element-property :value replaces))))
2343 (org-odt--render-image/formula entity href width height
2344 captions user-frame-params title desc)))
2347 ;;;; Links :: Math formula
2349 (defun org-odt-link--inline-formula (element info)
2350 (let* ((src (let* ((type (org-element-property :type element))
2351 (raw-path (org-element-property :path element)))
2352 (cond
2353 ((file-name-absolute-p raw-path)
2354 (expand-file-name raw-path))
2355 (t raw-path))))
2356 (src-expanded (if (file-name-absolute-p src) src
2357 (expand-file-name src (file-name-directory
2358 (plist-get info :input-file)))))
2359 (href
2360 (format
2361 "\n<draw:object %s xlink:href=\"%s\" xlink:type=\"simple\"/>"
2362 " xlink:show=\"embed\" xlink:actuate=\"onLoad\""
2363 (file-name-directory (org-odt--copy-formula-file src-expanded))))
2364 (standalone-link-p (org-odt--standalone-link-p element info))
2365 (embed-as (if standalone-link-p 'paragraph 'character))
2366 (captions (org-odt-format-label element info 'definition))
2367 (caption (car captions)) (short-caption (cdr captions))
2368 ;; Check if this link was created by LaTeX-to-MathML
2369 ;; converter.
2370 (replaces (org-element-property
2371 :replaces (if (not standalone-link-p) element
2372 (org-export-get-parent-element element))))
2373 ;; If yes, note down the type of the element - LaTeX Fragment
2374 ;; or LaTeX environment. It will go in to frame title.
2375 (title (and replaces (capitalize
2376 (symbol-name (org-element-type replaces)))))
2378 ;; If yes, note down its contents. It will go in to frame
2379 ;; description. This quite useful for debugging.
2380 (desc (and replaces (org-element-property :value replaces)))
2381 width height)
2382 (cond
2383 ((eq embed-as 'character)
2384 (org-odt--render-image/formula "InlineFormula" href width height
2385 nil nil title desc))
2387 (let* ((equation (org-odt--render-image/formula
2388 "CaptionedDisplayFormula" href width height
2389 captions nil title desc))
2390 (label
2391 (let* ((org-odt-category-map-alist
2392 '(("__MathFormula__" "Text" "math-label" "Equation"
2393 org-odt--enumerable-formula-p))))
2394 (car (org-odt-format-label element info 'definition)))))
2395 (concat equation "<text:tab/>" label))))))
2397 (defun org-odt--copy-formula-file (src-file)
2398 "Returns the internal name of the file"
2399 (let* ((target-dir (format "Formula-%04d/"
2400 (incf org-odt-embedded-formulas-count)))
2401 (target-file (concat target-dir "content.xml")))
2402 ;; Create a directory for holding formula file. Also enter it in
2403 ;; to manifest.
2404 (make-directory (concat org-odt-zip-dir target-dir))
2405 (org-odt-create-manifest-file-entry
2406 "application/vnd.oasis.opendocument.formula" target-dir "1.2")
2407 ;; Copy over the formula file from user directory to zip
2408 ;; directory.
2409 (message "Embedding %s as %s..." src-file target-file)
2410 (let ((case-fold-search nil))
2411 (cond
2412 ;; Case 1: Mathml.
2413 ((string-match "\\.\\(mathml\\|mml\\)\\'" src-file)
2414 (copy-file src-file (concat org-odt-zip-dir target-file) 'overwrite))
2415 ;; Case 2: OpenDocument formula.
2416 ((string-match "\\.odf\\'" src-file)
2417 (org-odt--zip-extract src-file "content.xml"
2418 (concat org-odt-zip-dir target-dir)))
2419 (t (error "%s is not a formula file" src-file))))
2420 ;; Enter the formula file in to manifest.
2421 (org-odt-create-manifest-file-entry "text/xml" target-file)
2422 target-file))
2424 ;;;; Targets
2426 (defun org-odt--render-image/formula (cfg-key href width height &optional
2427 captions user-frame-params
2428 &rest title-and-desc)
2429 (let* ((frame-cfg-alist
2430 ;; Each element of this alist is of the form (CFG-HANDLE
2431 ;; INNER-FRAME-PARAMS OUTER-FRAME-PARAMS).
2433 ;; CFG-HANDLE is the key to the alist.
2435 ;; INNER-FRAME-PARAMS and OUTER-FRAME-PARAMS specify the
2436 ;; frame params for INNER-FRAME and OUTER-FRAME
2437 ;; respectively. See below.
2439 ;; Configurations that are meant to be applied to
2440 ;; non-captioned image/formula specifies no
2441 ;; OUTER-FRAME-PARAMS.
2443 ;; TERMINOLOGY
2444 ;; ===========
2445 ;; INNER-FRAME :: Frame that directly surrounds an
2446 ;; image/formula.
2448 ;; OUTER-FRAME :: Frame that encloses the INNER-FRAME. This
2449 ;; frame also contains the caption, if any.
2451 ;; FRAME-PARAMS :: List of the form (FRAME-STYLE-NAME
2452 ;; FRAME-ATTRIBUTES FRAME-ANCHOR). Note
2453 ;; that these are the last three arguments
2454 ;; to `org-odt--frame'.
2456 ;; Note that an un-captioned image/formula requires just an
2457 ;; INNER-FRAME, while a captioned image/formula requires
2458 ;; both an INNER and an OUTER-FRAME.
2459 '(("As-CharImage" ("OrgInlineImage" nil "as-char"))
2460 ("ParagraphImage" ("OrgDisplayImage" nil "paragraph"))
2461 ("PageImage" ("OrgPageImage" nil "page"))
2462 ("CaptionedAs-CharImage"
2463 ("OrgCaptionedImage"
2464 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
2465 ("OrgInlineImage" nil "as-char"))
2466 ("CaptionedParagraphImage"
2467 ("OrgCaptionedImage"
2468 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
2469 ("OrgImageCaptionFrame" nil "paragraph"))
2470 ("CaptionedPageImage"
2471 ("OrgCaptionedImage"
2472 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
2473 ("OrgPageImageCaptionFrame" nil "page"))
2474 ("InlineFormula" ("OrgInlineFormula" nil "as-char"))
2475 ("DisplayFormula" ("OrgDisplayFormula" nil "as-char"))
2476 ("CaptionedDisplayFormula"
2477 ("OrgCaptionedFormula" nil "paragraph")
2478 ("OrgFormulaCaptionFrame" nil "paragraph"))))
2479 (caption (car captions)) (short-caption (cdr captions))
2480 ;; Retrieve inner and outer frame params, from configuration.
2481 (frame-cfg (assoc-string cfg-key frame-cfg-alist t))
2482 (inner (nth 1 frame-cfg))
2483 (outer (nth 2 frame-cfg))
2484 ;; User-specified frame params (from #+ATTR_ODT spec)
2485 (user user-frame-params)
2486 (--merge-frame-params (function
2487 (lambda (default user)
2488 "Merge default and user frame params."
2489 (if (not user) default
2490 (assert (= (length default) 3))
2491 (assert (= (length user) 3))
2492 (loop for u in user
2493 for d in default
2494 collect (or u d)))))))
2495 (cond
2496 ;; Case 1: Image/Formula has no caption.
2497 ;; There is only one frame, one that surrounds the image
2498 ;; or formula.
2499 ((not caption)
2500 ;; Merge user frame params with that from configuration.
2501 (setq inner (funcall --merge-frame-params inner user))
2502 (apply 'org-odt--frame href width height
2503 (append inner title-and-desc)))
2504 ;; Case 2: Image/Formula is captioned or labeled.
2505 ;; There are two frames: The inner one surrounds the
2506 ;; image or formula. The outer one contains the
2507 ;; caption/sequence number.
2509 ;; Merge user frame params with outer frame params.
2510 (setq outer (funcall --merge-frame-params outer user))
2511 ;; Short caption, if specified, goes as part of inner frame.
2512 (setq inner (let ((frame-params (copy-sequence inner)))
2513 (setcar (cdr frame-params)
2514 (concat
2515 (cadr frame-params)
2516 (when short-caption
2517 (format " draw:name=\"%s\" " short-caption))))
2518 frame-params))
2519 (apply 'org-odt--textbox
2520 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
2521 "Illustration"
2522 (concat
2523 (apply 'org-odt--frame href width height
2524 (append inner title-and-desc))
2525 caption))
2526 width height outer)))))
2528 (defun org-odt--enumerable-p (element info)
2529 ;; Element should have a caption or label.
2530 (or (org-element-property :caption element)
2531 (org-element-property :name element)))
2533 (defun org-odt--enumerable-image-p (element info)
2534 (org-odt--standalone-link-p
2535 element info
2536 ;; Paragraph should have a caption or label. It SHOULD NOT be a
2537 ;; replacement element. (i.e., It SHOULD NOT be a result of LaTeX
2538 ;; processing.)
2539 (lambda (p)
2540 (and (not (org-element-property :replaces p))
2541 (or (org-element-property :caption p)
2542 (org-element-property :name p))))
2543 ;; Link should point to an image file.
2544 (lambda (l)
2545 (assert (eq (org-element-type l) 'link))
2546 (org-export-inline-image-p l org-odt-inline-image-rules))))
2548 (defun org-odt--enumerable-latex-image-p (element info)
2549 (org-odt--standalone-link-p
2550 element info
2551 ;; Paragraph should have a caption or label. It SHOULD also be a
2552 ;; replacement element. (i.e., It SHOULD be a result of LaTeX
2553 ;; processing.)
2554 (lambda (p)
2555 (and (org-element-property :replaces p)
2556 (or (org-element-property :caption p)
2557 (org-element-property :name p))))
2558 ;; Link should point to an image file.
2559 (lambda (l)
2560 (assert (eq (org-element-type l) 'link))
2561 (org-export-inline-image-p l org-odt-inline-image-rules))))
2563 (defun org-odt--enumerable-formula-p (element info)
2564 (org-odt--standalone-link-p
2565 element info
2566 ;; Paragraph should have a caption or label.
2567 (lambda (p)
2568 (or (org-element-property :caption p)
2569 (org-element-property :name p)))
2570 ;; Link should point to a MathML or ODF file.
2571 (lambda (l)
2572 (assert (eq (org-element-type l) 'link))
2573 (org-export-inline-image-p l org-odt-inline-formula-rules))))
2575 (defun org-odt--standalone-link-p (element info &optional
2576 paragraph-predicate
2577 link-predicate)
2578 "Test if ELEMENT is a standalone link for the purpose ODT export.
2579 INFO is a plist holding contextual information.
2581 Return non-nil, if ELEMENT is of type paragraph satisfying
2582 PARAGRAPH-PREDICATE and its sole content, save for whitespaces,
2583 is a link that satisfies LINK-PREDICATE.
2585 Return non-nil, if ELEMENT is of type link satisfying
2586 LINK-PREDICATE and its containing paragraph satisfies
2587 PARAGRAPH-PREDICATE in addition to having no other content save for
2588 leading and trailing whitespaces.
2590 Return nil, otherwise."
2591 (let ((p (case (org-element-type element)
2592 (paragraph element)
2593 (link (and (or (not link-predicate)
2594 (funcall link-predicate element))
2595 (org-export-get-parent element)))
2596 (t nil))))
2597 (when (and p (eq (org-element-type p) 'paragraph))
2598 (when (or (not paragraph-predicate)
2599 (funcall paragraph-predicate p))
2600 (let ((contents (org-element-contents p)))
2601 (loop for x in contents
2602 with inline-image-count = 0
2603 always (case (org-element-type x)
2604 (plain-text
2605 (not (org-string-nw-p x)))
2606 (link
2607 (and (or (not link-predicate)
2608 (funcall link-predicate x))
2609 (= (incf inline-image-count) 1)))
2610 (t nil))))))))
2612 (defun org-odt-link--infer-description (destination info)
2613 ;; DESTINATION is a HEADLINE, a "<<target>>" or an element (like
2614 ;; paragraph, verse-block etc) to which a "#+NAME: label" can be
2615 ;; attached. Note that labels that are attached to captioned
2616 ;; entities - inline images, math formulae and tables - get resolved
2617 ;; as part of `org-odt-format-label' and `org-odt--enumerate'.
2619 ;; Create a cross-reference to DESTINATION but make best-efforts to
2620 ;; create a *meaningful* description. Check item numbers, section
2621 ;; number and section title in that order.
2623 ;; NOTE: Counterpart of `org-export-get-ordinal'.
2624 ;; FIXME: Handle footnote-definition footnote-reference?
2625 (let* ((genealogy (org-export-get-genealogy destination))
2626 (data (reverse genealogy))
2627 (label (case (org-element-type destination)
2628 (headline
2629 (format "sec-%s" (mapconcat 'number-to-string
2630 (org-export-get-headline-number
2631 destination info) "-")))
2632 (target
2633 (org-element-property :value destination))
2634 (t (error "FIXME: Resolve %S" destination)))))
2636 (let* ( ;; Locate top-level list.
2637 (top-level-list
2638 (loop for x on data
2639 when (eq (org-element-type (car x)) 'plain-list)
2640 return x))
2641 ;; Get list item nos.
2642 (item-numbers
2643 (loop for (plain-list item . rest) on top-level-list by #'cddr
2644 until (not (eq (org-element-type plain-list) 'plain-list))
2645 collect (when (eq (org-element-property :type
2646 plain-list)
2647 'ordered)
2648 (1+ (length (org-export-get-previous-element
2649 item info t))))))
2650 ;; Locate top-most listified headline.
2651 (listified-headlines
2652 (loop for x on data
2653 when (and (eq (org-element-type (car x)) 'headline)
2654 (org-export-low-level-p (car x) info))
2655 return x))
2656 ;; Get listified headline numbers.
2657 (listified-headline-nos
2658 (loop for el in listified-headlines
2659 when (eq (org-element-type el) 'headline)
2660 collect (when (org-export-numbered-headline-p el info)
2661 (1+ (length (org-export-get-previous-element
2662 el info t)))))))
2663 ;; Combine item numbers from both the listified headlines and
2664 ;; regular list items.
2666 ;; Case 1: Check if all the parents of list item are numbered.
2667 ;; If yes, link to the item proper.
2668 (let ((item-numbers (append listified-headline-nos item-numbers)))
2669 (when (and item-numbers (not (memq nil item-numbers)))
2670 (format "<text:bookmark-ref text:reference-format=\"number-all-superior\" text:ref-name=\"%s\">%s</text:bookmark-ref>"
2671 (org-export-solidify-link-text label)
2672 (mapconcat (lambda (n) (if (not n) " "
2673 (concat (number-to-string n) ".")))
2674 item-numbers "")))))
2675 ;; Case 2: Locate a regular and numbered headline in the
2676 ;; hierarchy. Display its section number.
2677 (let ((headline (loop for el in (cons destination genealogy)
2678 when (and (eq (org-element-type el) 'headline)
2679 (not (org-export-low-level-p el info))
2680 (org-export-numbered-headline-p el info))
2681 return el)))
2682 ;; We found one.
2683 (when headline
2684 (format "<text:bookmark-ref text:reference-format=\"chapter\" text:ref-name=\"OrgXref.%s\">%s</text:bookmark-ref>"
2685 (org-export-solidify-link-text label)
2686 (mapconcat 'number-to-string (org-export-get-headline-number
2687 headline info) "."))))
2688 ;; Case 4: Locate a regular headline in the hierarchy. Display
2689 ;; its title.
2690 (let ((headline (loop for el in (cons destination genealogy)
2691 when (and (eq (org-element-type el) 'headline)
2692 (not (org-export-low-level-p el info)))
2693 return el)))
2694 ;; We found one.
2695 (when headline
2696 (format "<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"OrgXref.%s\">%s</text:bookmark-ref>"
2697 (org-export-solidify-link-text label)
2698 (let ((title (org-element-property :title headline)))
2699 (org-export-data title info)))))
2700 (error "FIXME?"))))
2702 (defun org-odt-link (link desc info)
2703 "Transcode a LINK object from Org to ODT.
2705 DESC is the description part of the link, or the empty string.
2706 INFO is a plist holding contextual information. See
2707 `org-export-data'."
2708 (let* ((type (org-element-property :type link))
2709 (raw-path (org-element-property :path link))
2710 ;; Ensure DESC really exists, or set it to nil.
2711 (desc (and (not (string= desc "")) desc))
2712 (imagep (org-export-inline-image-p
2713 link org-odt-inline-image-rules))
2714 (path (cond
2715 ((member type '("http" "https" "ftp" "mailto"))
2716 (concat type ":" raw-path))
2717 ((string= type "file")
2718 (if (file-name-absolute-p raw-path)
2719 (concat "file://" (expand-file-name raw-path))
2720 (concat "file://" raw-path)))
2721 (t raw-path)))
2722 ;; Convert & to &amp; for correct XML representation
2723 (path (replace-regexp-in-string "&" "&amp;" path))
2724 protocol)
2725 (cond
2726 ;; Image file.
2727 ((and (not desc) (org-export-inline-image-p
2728 link org-odt-inline-image-rules))
2729 (org-odt-link--inline-image link info))
2730 ;; Formula file.
2731 ((and (not desc) (org-export-inline-image-p
2732 link org-odt-inline-formula-rules))
2733 (org-odt-link--inline-formula link info))
2734 ;; Radio target: Transcode target's contents and use them as
2735 ;; link's description.
2736 ((string= type "radio")
2737 (let ((destination (org-export-resolve-radio-link link info)))
2738 (when destination
2739 (let ((desc (org-export-data (org-element-contents destination) info))
2740 (href (org-export-solidify-link-text path)))
2741 (format
2742 "<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"OrgXref.%s\">%s</text:bookmark-ref>"
2743 href desc)))))
2744 ;; Links pointing to a headline: Find destination and build
2745 ;; appropriate referencing command.
2746 ((member type '("custom-id" "fuzzy" "id"))
2747 (let ((destination (if (string= type "fuzzy")
2748 (org-export-resolve-fuzzy-link link info)
2749 (org-export-resolve-id-link link info))))
2750 (case (org-element-type destination)
2751 ;; Case 1: Fuzzy link points nowhere.
2752 ('nil
2753 (format "<text:span text:style-name=\"%s\">%s</text:span>"
2754 "Emphasis"
2755 (or desc
2756 (org-export-data (org-element-property :raw-link link)
2757 info))))
2758 ;; Case 2: Fuzzy link points to a headline.
2759 (headline
2760 ;; If there's a description, create a hyperlink.
2761 ;; Otherwise, try to provide a meaningful description.
2762 (if (not desc) (org-odt-link--infer-description destination info)
2763 (let* ((headline-no
2764 (org-export-get-headline-number destination info))
2765 (label
2766 (format "sec-%s"
2767 (mapconcat 'number-to-string headline-no "-"))))
2768 (format
2769 "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
2770 label desc))))
2771 ;; Case 3: Fuzzy link points to a target.
2772 (target
2773 ;; If there's a description, create a hyperlink.
2774 ;; Otherwise, try to provide a meaningful description.
2775 (if (not desc) (org-odt-link--infer-description destination info)
2776 (let ((label (org-element-property :value destination)))
2777 (format "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
2778 (org-export-solidify-link-text label)
2779 desc))))
2780 ;; Case 4: Fuzzy link points to some element (e.g., an
2781 ;; inline image, a math formula or a table).
2782 (otherwise
2783 (let ((label-reference
2784 (ignore-errors (org-odt-format-label
2785 destination info 'reference))))
2786 (cond ((not label-reference)
2787 (org-odt-link--infer-description destination info))
2788 ;; LINK has no description. Create
2789 ;; a cross-reference showing entity's sequence
2790 ;; number.
2791 ((not desc) label-reference)
2792 ;; LINK has description. Insert a hyperlink with
2793 ;; user-provided description.
2795 (let ((label (org-element-property :name destination)))
2796 (format "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
2797 (org-export-solidify-link-text label)
2798 desc)))))))))
2799 ;; Coderef: replace link with the reference name or the
2800 ;; equivalent line number.
2801 ((string= type "coderef")
2802 (let* ((line-no (format "%d" (org-export-resolve-coderef path info)))
2803 (href (concat "coderef-" path)))
2804 (format
2805 (org-export-get-coderef-format path desc)
2806 (format
2807 "<text:bookmark-ref text:reference-format=\"number\" text:ref-name=\"OrgXref.%s\">%s</text:bookmark-ref>"
2808 href line-no))))
2809 ;; Link type is handled by a special function.
2810 ((functionp (setq protocol (nth 2 (assoc type org-link-protocols))))
2811 (funcall protocol (org-link-unescape path) desc 'odt))
2812 ;; External link with a description part.
2813 ((and path desc)
2814 (let ((link-contents (org-element-contents link)))
2815 ;; Check if description is a link to an inline image.
2816 (if (and (not (cdr link-contents))
2817 (let ((desc-element (car link-contents)))
2818 (and (eq (org-element-type desc-element) 'link)
2819 (org-export-inline-image-p
2820 desc-element org-odt-inline-image-rules))))
2821 ;; Format link as a clickable image.
2822 (format "\n<draw:a xlink:type=\"simple\" xlink:href=\"%s\">\n%s\n</draw:a>"
2823 path desc)
2824 ;; Otherwise, format it as a regular link.
2825 (format "<text:a xlink:type=\"simple\" xlink:href=\"%s\">%s</text:a>"
2826 path desc))))
2827 ;; External link without a description part.
2828 (path
2829 (format "<text:a xlink:type=\"simple\" xlink:href=\"%s\">%s</text:a>"
2830 path path))
2831 ;; No path, only description. Try to do something useful.
2832 (t (format "<text:span text:style-name=\"%s\">%s</text:span>"
2833 "Emphasis" desc)))))
2836 ;;;; Node Property
2838 (defun org-odt-node-property (node-property contents info)
2839 "Transcode a NODE-PROPERTY element from Org to ODT.
2840 CONTENTS is nil. INFO is a plist holding contextual
2841 information."
2842 (org-odt--encode-plain-text
2843 (format "%s:%s"
2844 (org-element-property :key node-property)
2845 (let ((value (org-element-property :value node-property)))
2846 (if value (concat " " value) "")))))
2848 ;;;; Paragraph
2850 (defun org-odt--format-paragraph (paragraph contents default center quote)
2851 "Format paragraph according to given styles.
2852 PARAGRAPH is a paragraph type element. CONTENTS is the
2853 transcoded contents of that paragraph, as a string. DEFAULT,
2854 CENTER and QUOTE are, respectively, style to use when paragraph
2855 belongs to no special environment, a center block, or a quote
2856 block."
2857 (let* ((parent (org-export-get-parent paragraph))
2858 (parent-type (org-element-type parent))
2859 (style (case parent-type
2860 (quote-block quote)
2861 (center-block center)
2862 (t default))))
2863 ;; If this paragraph is a leading paragraph in an item and the
2864 ;; item has a checkbox, splice the checkbox and paragraph contents
2865 ;; together.
2866 (when (and (eq (org-element-type parent) 'item)
2867 (eq paragraph (car (org-element-contents parent))))
2868 (setq contents (concat (org-odt--checkbox parent) contents)))
2869 (format "\n<text:p text:style-name=\"%s\">%s</text:p>" style contents)))
2871 (defun org-odt-paragraph (paragraph contents info)
2872 "Transcode a PARAGRAPH element from Org to ODT.
2873 CONTENTS is the contents of the paragraph, as a string. INFO is
2874 the plist used as a communication channel."
2875 (org-odt--format-paragraph
2876 paragraph contents
2877 (or (org-element-property :style paragraph) "Text_20_body")
2878 "OrgCenter"
2879 "Quotations"))
2882 ;;;; Plain List
2884 (defun org-odt-plain-list (plain-list contents info)
2885 "Transcode a PLAIN-LIST element from Org to ODT.
2886 CONTENTS is the contents of the list. INFO is a plist holding
2887 contextual information."
2888 (format "\n<text:list text:style-name=\"%s\" %s>\n%s</text:list>"
2889 ;; Choose style based on list type.
2890 (case (org-element-property :type plain-list)
2891 (ordered "OrgNumberedList")
2892 (unordered "OrgBulletedList")
2893 (descriptive-1 "OrgDescriptionList")
2894 (descriptive-2 "OrgDescriptionList"))
2895 ;; If top-level list, re-start numbering. Otherwise,
2896 ;; continue numbering.
2897 (format "text:continue-numbering=\"%s\""
2898 (let* ((parent (org-export-get-parent plain-list)))
2899 (if (and parent (eq (org-element-type parent) 'item))
2900 "true" "false")))
2901 contents))
2903 ;;;; Plain Text
2905 (defun org-odt--encode-tabs-and-spaces (line)
2906 (replace-regexp-in-string
2907 "\\([\t]\\|\\([ ]+\\)\\)"
2908 (lambda (s)
2909 (cond
2910 ((string= s "\t") "<text:tab/>")
2911 (t (let ((n (length s)))
2912 (cond
2913 ((= n 1) " ")
2914 ((> n 1) (concat " " (format "<text:s text:c=\"%d\"/>" (1- n))))
2915 (t ""))))))
2916 line))
2918 (defun org-odt--encode-plain-text (text &optional no-whitespace-filling)
2919 (mapc
2920 (lambda (pair)
2921 (setq text (replace-regexp-in-string (car pair) (cdr pair) text t t)))
2922 '(("&" . "&amp;") ("<" . "&lt;") (">" . "&gt;")))
2923 (if no-whitespace-filling text
2924 (org-odt--encode-tabs-and-spaces text)))
2926 (defun org-odt-plain-text (text info)
2927 "Transcode a TEXT string from Org to ODT.
2928 TEXT is the string to transcode. INFO is a plist holding
2929 contextual information."
2930 (let ((output text))
2931 ;; Protect &, < and >.
2932 (setq output (org-odt--encode-plain-text output t))
2933 ;; Handle smart quotes. Be sure to provide original string since
2934 ;; OUTPUT may have been modified.
2935 (when (plist-get info :with-smart-quotes)
2936 (setq output (org-export-activate-smart-quotes output :utf-8 info text)))
2937 ;; Convert special strings.
2938 (when (plist-get info :with-special-strings)
2939 (mapc
2940 (lambda (pair)
2941 (setq output
2942 (replace-regexp-in-string (car pair) (cdr pair) output t nil)))
2943 org-odt-special-string-regexps))
2944 ;; Handle break preservation if required.
2945 (when (plist-get info :preserve-breaks)
2946 (setq output (replace-regexp-in-string
2947 "\\(\\\\\\\\\\)?[ \t]*\n" "<text:line-break/>" output t)))
2948 ;; Return value.
2949 output))
2952 ;;;; Planning
2954 (defun org-odt-planning (planning contents info)
2955 "Transcode a PLANNING element from Org to ODT.
2956 CONTENTS is nil. INFO is a plist used as a communication
2957 channel."
2958 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
2959 "OrgPlanning"
2960 (concat
2961 (let ((closed (org-element-property :closed planning)))
2962 (when closed
2963 (concat
2964 (format "<text:span text:style-name=\"%s\">%s</text:span>"
2965 "OrgClosedKeyword" org-closed-string)
2966 (org-odt-timestamp closed contents info))))
2967 (let ((deadline (org-element-property :deadline planning)))
2968 (when deadline
2969 (concat
2970 (format "<text:span text:style-name=\"%s\">%s</text:span>"
2971 "OrgDeadlineKeyword" org-deadline-string)
2972 (org-odt-timestamp deadline contents info))))
2973 (let ((scheduled (org-element-property :scheduled planning)))
2974 (when scheduled
2975 (concat
2976 (format "<text:span text:style-name=\"%s\">%s</text:span>"
2977 "OrgScheduledKeyword" org-deadline-string)
2978 (org-odt-timestamp scheduled contents info)))))))
2981 ;;;; Property Drawer
2983 (defun org-odt-property-drawer (property-drawer contents info)
2984 "Transcode a PROPERTY-DRAWER element from Org to ODT.
2985 CONTENTS holds the contents of the drawer. INFO is a plist
2986 holding contextual information."
2987 (and (org-string-nw-p contents)
2988 (format "<text:p text:style-name=\"OrgFixedWidthBlock\">%s</text:p>"
2989 contents)))
2992 ;;;; Quote Block
2994 (defun org-odt-quote-block (quote-block contents info)
2995 "Transcode a QUOTE-BLOCK element from Org to ODT.
2996 CONTENTS holds the contents of the block. INFO is a plist
2997 holding contextual information."
2998 contents)
3001 ;;;; Quote Section
3003 (defun org-odt-quote-section (quote-section contents info)
3004 "Transcode a QUOTE-SECTION element from Org to ODT.
3005 CONTENTS is nil. INFO is a plist holding contextual information."
3006 (let ((value (org-remove-indentation
3007 (org-element-property :value quote-section))))
3008 (when value (org-odt-do-format-code value))))
3011 ;;;; Section
3013 (defun org-odt-format-section (text style &optional name)
3014 (let ((default-name (car (org-odt-add-automatic-style "Section"))))
3015 (format "\n<text:section text:style-name=\"%s\" %s>\n%s\n</text:section>"
3016 style
3017 (format "text:name=\"%s\"" (or name default-name))
3018 text)))
3021 (defun org-odt-section (section contents info) ; FIXME
3022 "Transcode a SECTION element from Org to ODT.
3023 CONTENTS holds the contents of the section. INFO is a plist
3024 holding contextual information."
3025 contents)
3027 ;;;; Radio Target
3029 (defun org-odt-radio-target (radio-target text info)
3030 "Transcode a RADIO-TARGET object from Org to ODT.
3031 TEXT is the text of the target. INFO is a plist holding
3032 contextual information."
3033 (org-odt--target
3034 text (org-export-solidify-link-text
3035 (org-element-property :value radio-target))))
3038 ;;;; Special Block
3040 (defun org-odt-special-block (special-block contents info)
3041 "Transcode a SPECIAL-BLOCK element from Org to ODT.
3042 CONTENTS holds the contents of the block. INFO is a plist
3043 holding contextual information."
3044 (let ((type (downcase (org-element-property :type special-block)))
3045 (attributes (org-export-read-attribute :attr_odt special-block)))
3046 (cond
3047 ;; Annotation.
3048 ((string= type "annotation")
3049 (let* ((author (or (plist-get attributes :author)
3050 (let ((author (plist-get info :author)))
3051 (and author (org-export-data author info)))))
3052 (date (or (plist-get attributes :date)
3053 ;; FIXME: Is `car' right thing to do below?
3054 (car (plist-get info :date)))))
3055 (format "\n<text:p>%s</text:p>"
3056 (format "<office:annotation>\n%s\n</office:annotation>"
3057 (concat
3058 (and author
3059 (format "<dc:creator>%s</dc:creator>" author))
3060 (and date
3061 (format "<dc:date>%s</dc:date>"
3062 (org-odt--format-timestamp date nil 'iso-date)))
3063 contents)))))
3064 ;; Textbox.
3065 ((string= type "textbox")
3066 (let ((width (plist-get attributes :width))
3067 (height (plist-get attributes :height))
3068 (style (plist-get attributes :style))
3069 (extra (plist-get attributes :extra))
3070 (anchor (plist-get attributes :anchor)))
3071 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3072 "Text_20_body" (org-odt--textbox contents width height
3073 style extra anchor))))
3074 (t contents))))
3077 ;;;; Src Block
3079 (defun org-odt-hfy-face-to-css (fn)
3080 "Create custom style for face FN.
3081 When FN is the default face, use its foreground and background
3082 properties to create \"OrgSrcBlock\" paragraph style. Otherwise
3083 use its color attribute to create a character style whose name
3084 is obtained from FN. Currently all attributes of FN other than
3085 color are ignored.
3087 The style name for a face FN is derived using the following
3088 operations on the face name in that order - de-dash, CamelCase
3089 and prefix with \"OrgSrc\". For example,
3090 `font-lock-function-name-face' is associated with
3091 \"OrgSrcFontLockFunctionNameFace\"."
3092 (let* ((css-list (hfy-face-to-style fn))
3093 (style-name (concat "OrgSrc"
3094 (mapconcat
3095 'capitalize (split-string
3096 (hfy-face-or-def-to-name fn) "-")
3097 "")))
3098 (color-val (cdr (assoc "color" css-list)))
3099 (background-color-val (cdr (assoc "background" css-list)))
3100 (style (and org-odt-create-custom-styles-for-srcblocks
3101 (cond
3102 ((eq fn 'default)
3103 (format org-odt-src-block-paragraph-format
3104 background-color-val color-val))
3106 (format
3108 <style:style style:name=\"%s\" style:family=\"text\">
3109 <style:text-properties fo:color=\"%s\"/>
3110 </style:style>" style-name color-val))))))
3111 (cons style-name style)))
3113 (defun org-odt-htmlfontify-string (line)
3114 (let* ((hfy-html-quote-regex "\\([<\"&> ]\\)")
3115 (hfy-html-quote-map '(("\"" "&quot;")
3116 ("<" "&lt;")
3117 ("&" "&amp;")
3118 (">" "&gt;")
3119 (" " "<text:s/>")
3120 (" " "<text:tab/>")))
3121 (hfy-face-to-css 'org-odt-hfy-face-to-css)
3122 (hfy-optimisations-1 (copy-sequence hfy-optimisations))
3123 (hfy-optimisations (add-to-list 'hfy-optimisations-1
3124 'body-text-only))
3125 (hfy-begin-span-handler
3126 (lambda (style text-block text-id text-begins-block-p)
3127 (insert (format "<text:span text:style-name=\"%s\">" style))))
3128 (hfy-end-span-handler (lambda nil (insert "</text:span>"))))
3129 (org-no-warnings (htmlfontify-string line))))
3131 (defun org-odt-do-format-code
3132 (code &optional lang refs retain-labels num-start)
3133 (let* ((lang (or (assoc-default lang org-src-lang-modes) lang))
3134 (lang-mode (and lang (intern (format "%s-mode" lang))))
3135 (code-lines (org-split-string code "\n"))
3136 (code-length (length code-lines))
3137 (use-htmlfontify-p (and (functionp lang-mode)
3138 org-odt-fontify-srcblocks
3139 (require 'htmlfontify nil t)
3140 (fboundp 'htmlfontify-string)))
3141 (code (if (not use-htmlfontify-p) code
3142 (with-temp-buffer
3143 (insert code)
3144 (funcall lang-mode)
3145 (font-lock-fontify-buffer)
3146 (buffer-string))))
3147 (fontifier (if use-htmlfontify-p 'org-odt-htmlfontify-string
3148 'org-odt--encode-plain-text))
3149 (par-style (if use-htmlfontify-p "OrgSrcBlock"
3150 "OrgFixedWidthBlock"))
3151 (i 0))
3152 (assert (= code-length (length (org-split-string code "\n"))))
3153 (setq code
3154 (org-export-format-code
3155 code
3156 (lambda (loc line-num ref)
3157 (setq par-style
3158 (concat par-style (and (= (incf i) code-length) "LastLine")))
3160 (setq loc (concat loc (and ref retain-labels (format " (%s)" ref))))
3161 (setq loc (funcall fontifier loc))
3162 (when ref
3163 (setq loc (org-odt--target loc (concat "coderef-" ref))))
3164 (assert par-style)
3165 (setq loc (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3166 par-style loc))
3167 (if (not line-num) loc
3168 (format "\n<text:list-item>%s\n</text:list-item>" loc)))
3169 num-start refs))
3170 (cond
3171 ((not num-start) code)
3172 ((= num-start 0)
3173 (format
3174 "\n<text:list text:style-name=\"OrgSrcBlockNumberedLine\"%s>%s</text:list>"
3175 " text:continue-numbering=\"false\"" code))
3177 (format
3178 "\n<text:list text:style-name=\"OrgSrcBlockNumberedLine\"%s>%s</text:list>"
3179 " text:continue-numbering=\"true\"" code)))))
3181 (defun org-odt-format-code (element info)
3182 (let* ((lang (org-element-property :language element))
3183 ;; Extract code and references.
3184 (code-info (org-export-unravel-code element))
3185 (code (car code-info))
3186 (refs (cdr code-info))
3187 ;; Does the src block contain labels?
3188 (retain-labels (org-element-property :retain-labels element))
3189 ;; Does it have line numbers?
3190 (num-start (case (org-element-property :number-lines element)
3191 (continued (org-export-get-loc element info))
3192 (new 0))))
3193 (org-odt-do-format-code code lang refs retain-labels num-start)))
3195 (defun org-odt-src-block (src-block contents info)
3196 "Transcode a SRC-BLOCK element from Org to ODT.
3197 CONTENTS holds the contents of the item. INFO is a plist holding
3198 contextual information."
3199 (let* ((lang (org-element-property :language src-block))
3200 (attributes (org-export-read-attribute :attr_odt src-block))
3201 (captions (org-odt-format-label src-block info 'definition))
3202 (caption (car captions)) (short-caption (cdr captions)))
3203 (concat
3204 (and caption
3205 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3206 "Listing" caption))
3207 (let ((--src-block (org-odt-format-code src-block info)))
3208 (if (not (plist-get attributes :textbox)) --src-block
3209 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3210 "Text_20_body"
3211 (org-odt--textbox --src-block nil nil nil)))))))
3214 ;;;; Statistics Cookie
3216 (defun org-odt-statistics-cookie (statistics-cookie contents info)
3217 "Transcode a STATISTICS-COOKIE object from Org to ODT.
3218 CONTENTS is nil. INFO is a plist holding contextual information."
3219 (let ((cookie-value (org-element-property :value statistics-cookie)))
3220 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3221 "OrgCode" cookie-value)))
3224 ;;;; Strike-Through
3226 (defun org-odt-strike-through (strike-through contents info)
3227 "Transcode STRIKE-THROUGH from Org to ODT.
3228 CONTENTS is the text with strike-through markup. INFO is a plist
3229 holding contextual information."
3230 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3231 "Strikethrough" contents))
3234 ;;;; Subscript
3236 (defun org-odt-subscript (subscript contents info)
3237 "Transcode a SUBSCRIPT object from Org to ODT.
3238 CONTENTS is the contents of the object. INFO is a plist holding
3239 contextual information."
3240 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3241 "OrgSubscript" contents))
3244 ;;;; Superscript
3246 (defun org-odt-superscript (superscript contents info)
3247 "Transcode a SUPERSCRIPT object from Org to ODT.
3248 CONTENTS is the contents of the object. INFO is a plist holding
3249 contextual information."
3250 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3251 "OrgSuperscript" contents))
3254 ;;;; Table Cell
3256 (defun org-odt-table-style-spec (element info)
3257 (let* ((table (org-export-get-parent-table element))
3258 (table-attributes (org-export-read-attribute :attr_odt table))
3259 (table-style (plist-get table-attributes :style)))
3260 (assoc table-style org-odt-table-styles)))
3262 (defun org-odt-get-table-cell-styles (table-cell info)
3263 "Retrieve styles applicable to a table cell.
3264 R and C are (zero-based) row and column numbers of the table
3265 cell. STYLE-SPEC is an entry in `org-odt-table-styles'
3266 applicable to the current table. It is `nil' if the table is not
3267 associated with any style attributes.
3269 Return a cons of (TABLE-CELL-STYLE-NAME . PARAGRAPH-STYLE-NAME).
3271 When STYLE-SPEC is nil, style the table cell the conventional way
3272 - choose cell borders based on row and column groupings and
3273 choose paragraph alignment based on `org-col-cookies' text
3274 property. See also
3275 `org-odt-get-paragraph-style-cookie-for-table-cell'.
3277 When STYLE-SPEC is non-nil, ignore the above cookie and return
3278 styles congruent with the ODF-1.2 specification."
3279 (let* ((table-cell-address (org-export-table-cell-address table-cell info))
3280 (r (car table-cell-address)) (c (cdr table-cell-address))
3281 (style-spec (org-odt-table-style-spec table-cell info))
3282 (table-dimensions (org-export-table-dimensions
3283 (org-export-get-parent-table table-cell)
3284 info)))
3285 (when style-spec
3286 ;; LibreOffice - particularly the Writer - honors neither table
3287 ;; templates nor custom table-cell styles. Inorder to retain
3288 ;; inter-operability with LibreOffice, only automatic styles are
3289 ;; used for styling of table-cells. The current implementation is
3290 ;; congruent with ODF-1.2 specification and hence is
3291 ;; future-compatible.
3293 ;; Additional Note: LibreOffice's AutoFormat facility for tables -
3294 ;; which recognizes as many as 16 different cell types - is much
3295 ;; richer. Unfortunately it is NOT amenable to easy configuration
3296 ;; by hand.
3297 (let* ((template-name (nth 1 style-spec))
3298 (cell-style-selectors (nth 2 style-spec))
3299 (cell-type
3300 (cond
3301 ((and (cdr (assoc 'use-first-column-styles cell-style-selectors))
3302 (= c 0)) "FirstColumn")
3303 ((and (cdr (assoc 'use-last-column-styles cell-style-selectors))
3304 (= (1+ c) (cdr table-dimensions)))
3305 "LastColumn")
3306 ((and (cdr (assoc 'use-first-row-styles cell-style-selectors))
3307 (= r 0)) "FirstRow")
3308 ((and (cdr (assoc 'use-last-row-styles cell-style-selectors))
3309 (= (1+ r) (car table-dimensions)))
3310 "LastRow")
3311 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
3312 (= (% r 2) 1)) "EvenRow")
3313 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
3314 (= (% r 2) 0)) "OddRow")
3315 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
3316 (= (% c 2) 1)) "EvenColumn")
3317 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
3318 (= (% c 2) 0)) "OddColumn")
3319 (t ""))))
3320 (concat template-name cell-type)))))
3322 (defun org-odt-table-cell (table-cell contents info)
3323 "Transcode a TABLE-CELL element from Org to ODT.
3324 CONTENTS is nil. INFO is a plist used as a communication
3325 channel."
3326 (let* ((table-cell-address (org-export-table-cell-address table-cell info))
3327 (r (car table-cell-address))
3328 (c (cdr table-cell-address))
3329 (horiz-span (or (org-export-table-cell-width table-cell info) 0))
3330 (table-row (org-export-get-parent table-cell))
3331 (custom-style-prefix (org-odt-get-table-cell-styles
3332 table-cell info))
3333 (paragraph-style
3335 (and custom-style-prefix
3336 (format "%sTableParagraph" custom-style-prefix))
3337 (concat
3338 (cond
3339 ((and (= 1 (org-export-table-row-group table-row info))
3340 (org-export-table-has-header-p
3341 (org-export-get-parent-table table-row) info))
3342 "OrgTableHeading")
3343 ((let* ((table (org-export-get-parent-table table-cell))
3344 (table-attrs (org-export-read-attribute :attr_odt table))
3345 (table-header-columns
3346 (let ((cols (plist-get table-attrs :header-columns)))
3347 (and cols (read cols)))))
3348 (<= c (cond ((wholenump table-header-columns)
3349 (- table-header-columns 1))
3350 (table-header-columns 0)
3351 (t -1))))
3352 "OrgTableHeading")
3353 (t "OrgTableContents"))
3354 (capitalize (symbol-name (org-export-table-cell-alignment
3355 table-cell info))))))
3356 (cell-style-name
3358 (and custom-style-prefix (format "%sTableCell"
3359 custom-style-prefix))
3360 (concat
3361 "OrgTblCell"
3362 (when (or (org-export-table-row-starts-rowgroup-p table-row info)
3363 (zerop r)) "T")
3364 (when (org-export-table-row-ends-rowgroup-p table-row info) "B")
3365 (when (and (org-export-table-cell-starts-colgroup-p table-cell info)
3366 (not (zerop c)) ) "L"))))
3367 (cell-attributes
3368 (concat
3369 (format " table:style-name=\"%s\"" cell-style-name)
3370 (and (> horiz-span 0)
3371 (format " table:number-columns-spanned=\"%d\""
3372 (1+ horiz-span))))))
3373 (unless contents (setq contents ""))
3374 (concat
3375 (assert paragraph-style)
3376 (format "\n<table:table-cell%s>\n%s\n</table:table-cell>"
3377 cell-attributes
3378 (let ((table-cell-contents (org-element-contents table-cell)))
3379 (if (memq (org-element-type (car table-cell-contents))
3380 org-element-all-elements)
3381 contents
3382 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3383 paragraph-style contents))))
3384 (let (s)
3385 (dotimes (i horiz-span s)
3386 (setq s (concat s "\n<table:covered-table-cell/>"))))
3387 "\n")))
3390 ;;;; Table Row
3392 (defun org-odt-table-row (table-row contents info)
3393 "Transcode a TABLE-ROW element from Org to ODT.
3394 CONTENTS is the contents of the row. INFO is a plist used as a
3395 communication channel."
3396 ;; Rules are ignored since table separators are deduced from
3397 ;; borders of the current row.
3398 (when (eq (org-element-property :type table-row) 'standard)
3399 (let* ((rowgroup-tags
3400 (if (and (= 1 (org-export-table-row-group table-row info))
3401 (org-export-table-has-header-p
3402 (org-export-get-parent-table table-row) info))
3403 ;; If the row belongs to the first rowgroup and the
3404 ;; table has more than one row groups, then this row
3405 ;; belongs to the header row group.
3406 '("\n<table:table-header-rows>" . "\n</table:table-header-rows>")
3407 ;; Otherwise, it belongs to non-header row group.
3408 '("\n<table:table-rows>" . "\n</table:table-rows>"))))
3409 (concat
3410 ;; Does this row begin a rowgroup?
3411 (when (org-export-table-row-starts-rowgroup-p table-row info)
3412 (car rowgroup-tags))
3413 ;; Actual table row
3414 (format "\n<table:table-row>\n%s\n</table:table-row>" contents)
3415 ;; Does this row end a rowgroup?
3416 (when (org-export-table-row-ends-rowgroup-p table-row info)
3417 (cdr rowgroup-tags))))))
3420 ;;;; Table
3422 (defun org-odt-table-first-row-data-cells (table info)
3423 (let ((table-row
3424 (org-element-map table 'table-row
3425 (lambda (row)
3426 (unless (eq (org-element-property :type row) 'rule) row))
3427 info 'first-match))
3428 (special-column-p (org-export-table-has-special-column-p table)))
3429 (if (not special-column-p) (org-element-contents table-row)
3430 (cdr (org-element-contents table-row)))))
3432 (defun org-odt--table (table contents info)
3433 "Transcode a TABLE element from Org to ODT.
3434 CONTENTS is the contents of the table. INFO is a plist holding
3435 contextual information."
3436 (case (org-element-property :type table)
3437 ;; Case 1: table.el doesn't support export to OD format. Strip
3438 ;; such tables from export.
3439 (table.el
3440 (prog1 nil
3441 (message
3442 (concat
3443 "(ox-odt): Found table.el-type table in the source Org file."
3444 " table.el doesn't support export to ODT format."
3445 " Stripping the table from export."))))
3446 ;; Case 2: Native Org tables.
3447 (otherwise
3448 (let* ((captions (org-odt-format-label table info 'definition))
3449 (caption (car captions)) (short-caption (cdr captions))
3450 (attributes (org-export-read-attribute :attr_odt table))
3451 (custom-table-style (nth 1 (org-odt-table-style-spec table info)))
3452 (table-column-specs
3453 (function
3454 (lambda (table info)
3455 (let* ((table-style (or custom-table-style "OrgTable"))
3456 (column-style (format "%sColumn" table-style)))
3457 (mapconcat
3458 (lambda (table-cell)
3459 (let ((width (1+ (or (org-export-table-cell-width
3460 table-cell info) 0)))
3461 (s (format
3462 "\n<table:table-column table:style-name=\"%s\"/>"
3463 column-style))
3464 out)
3465 (dotimes (i width out) (setq out (concat s out)))))
3466 (org-odt-table-first-row-data-cells table info) "\n"))))))
3467 (concat
3468 ;; caption.
3469 (when caption
3470 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3471 "Table" caption))
3472 ;; begin table.
3473 (let* ((automatic-name
3474 (org-odt-add-automatic-style "Table" attributes)))
3475 (format
3476 "\n<table:table table:style-name=\"%s\"%s>"
3477 (or custom-table-style (cdr automatic-name) "OrgTable")
3478 (concat (when short-caption
3479 (format " table:name=\"%s\"" short-caption)))))
3480 ;; column specification.
3481 (funcall table-column-specs table info)
3482 ;; actual contents.
3483 "\n" contents
3484 ;; end table.
3485 "</table:table>")))))
3487 (defun org-odt-table (table contents info)
3488 "Transcode a TABLE element from Org to ODT.
3489 CONTENTS is the contents of the table. INFO is a plist holding
3490 contextual information.
3492 Use `org-odt--table' to typeset the table. Handle details
3493 pertaining to indentation here."
3494 (let* ((--element-preceded-by-table-p
3495 (function
3496 (lambda (element info)
3497 (loop for el in (org-export-get-previous-element element info t)
3498 thereis (eq (org-element-type el) 'table)))))
3499 (--walk-list-genealogy-and-collect-tags
3500 (function
3501 (lambda (table info)
3502 (let* ((genealogy (org-export-get-genealogy table))
3503 (list-genealogy
3504 (when (eq (org-element-type (car genealogy)) 'item)
3505 (loop for el in genealogy
3506 when (memq (org-element-type el)
3507 '(item plain-list))
3508 collect el)))
3509 (llh-genealogy
3510 (apply 'nconc
3511 (loop for el in genealogy
3512 when (and (eq (org-element-type el) 'headline)
3513 (org-export-low-level-p el info))
3514 collect
3515 (list el
3516 (assq 'headline
3517 (org-element-contents
3518 (org-export-get-parent el)))))))
3519 parent-list)
3520 (nconc
3521 ;; Handle list genealogy.
3522 (loop for el in list-genealogy collect
3523 (case (org-element-type el)
3524 (plain-list
3525 (setq parent-list el)
3526 (cons "</text:list>"
3527 (format "\n<text:list text:style-name=\"%s\" %s>"
3528 (case (org-element-property :type el)
3529 (ordered "OrgNumberedList")
3530 (unordered "OrgBulletedList")
3531 (descriptive-1 "OrgDescriptionList")
3532 (descriptive-2 "OrgDescriptionList"))
3533 "text:continue-numbering=\"true\"")))
3534 (item
3535 (cond
3536 ((not parent-list)
3537 (if (funcall --element-preceded-by-table-p table info)
3538 '("</text:list-header>" . "<text:list-header>")
3539 '("</text:list-item>" . "<text:list-header>")))
3540 ((funcall --element-preceded-by-table-p
3541 parent-list info)
3542 '("</text:list-header>" . "<text:list-header>"))
3543 (t '("</text:list-item>" . "<text:list-item>"))))))
3544 ;; Handle low-level headlines.
3545 (loop for el in llh-genealogy
3546 with step = 'item collect
3547 (case step
3548 (plain-list
3549 (setq step 'item) ; Flip-flop
3550 (setq parent-list el)
3551 (cons "</text:list>"
3552 (format "\n<text:list text:style-name=\"%s\" %s>"
3553 (if (org-export-numbered-headline-p
3554 el info)
3555 "OrgNumberedList"
3556 "OrgBulletedList")
3557 "text:continue-numbering=\"true\"")))
3558 (item
3559 (setq step 'plain-list) ; Flip-flop
3560 (cond
3561 ((not parent-list)
3562 (if (funcall --element-preceded-by-table-p table info)
3563 '("</text:list-header>" . "<text:list-header>")
3564 '("</text:list-item>" . "<text:list-header>")))
3565 ((let ((section? (org-export-get-previous-element
3566 parent-list info)))
3567 (and section?
3568 (eq (org-element-type section?) 'section)
3569 (assq 'table (org-element-contents section?))))
3570 '("</text:list-header>" . "<text:list-header>"))
3572 '("</text:list-item>" . "<text:list-item>")))))))))))
3573 (close-open-tags (funcall --walk-list-genealogy-and-collect-tags
3574 table info)))
3575 ;; OpenDocument schema does not permit table to occur within a
3576 ;; list item.
3578 ;; One solution - the easiest and lightweight, in terms of
3579 ;; implementation - is to put the table in an indented text box
3580 ;; and make the text box part of the list-item. Unfortunately if
3581 ;; the table is big and spans multiple pages, the text box could
3582 ;; overflow. In this case, the following attribute will come
3583 ;; handy.
3585 ;; ,---- From OpenDocument-v1.1.pdf
3586 ;; | 15.27.28 Overflow behavior
3587 ;; |
3588 ;; | For text boxes contained within text document, the
3589 ;; | style:overflow-behavior property specifies the behavior of text
3590 ;; | boxes where the containing text does not fit into the text
3591 ;; | box.
3592 ;; |
3593 ;; | If the attribute's value is clip, the text that does not fit
3594 ;; | into the text box is not displayed.
3595 ;; |
3596 ;; | If the attribute value is auto-create-new-frame, a new frame
3597 ;; | will be created on the next page, with the same position and
3598 ;; | dimensions of the original frame.
3599 ;; |
3600 ;; | If the style:overflow-behavior property's value is
3601 ;; | auto-create-new-frame and the text box has a minimum width or
3602 ;; | height specified, then the text box will grow until the page
3603 ;; | bounds are reached before a new frame is created.
3604 ;; `----
3606 ;; Unfortunately, LibreOffice-3.4.6 doesn't honor
3607 ;; auto-create-new-frame property and always resorts to clipping
3608 ;; the text box. This results in table being truncated.
3610 ;; So we solve the problem the hard (and fun) way using list
3611 ;; continuations.
3613 ;; The problem only becomes more interesting if you take in to
3614 ;; account the following facts:
3616 ;; - Description lists are simulated as plain lists.
3617 ;; - Low-level headlines can be listified.
3618 ;; - In Org-mode, a table can occur not only as a regular list
3619 ;; item, but also within description lists and low-level
3620 ;; headlines.
3622 ;; See `org-odt-translate-description-lists' and
3623 ;; `org-odt-translate-low-level-headlines' for how this is
3624 ;; tackled.
3626 (concat "\n"
3627 ;; Discontinue the list.
3628 (mapconcat 'car close-open-tags "\n")
3629 ;; Put the table in an indented section.
3630 (let* ((table (org-odt--table table contents info))
3631 (level (/ (length (mapcar 'car close-open-tags)) 2))
3632 (style (format "OrgIndentedSection-Level-%d" level)))
3633 (when table (org-odt-format-section table style)))
3634 ;; Continue the list.
3635 (mapconcat 'cdr (nreverse close-open-tags) "\n"))))
3638 ;;;; Target
3640 (defun org-odt-target (target contents info)
3641 "Transcode a TARGET object from Org to ODT.
3642 CONTENTS is nil. INFO is a plist holding contextual
3643 information."
3644 (let ((value (org-element-property :value target)))
3645 (org-odt--target "" (org-export-solidify-link-text value))))
3648 ;;;; Timestamp
3650 (defun org-odt-timestamp (timestamp contents info)
3651 "Transcode a TIMESTAMP object from Org to ODT.
3652 CONTENTS is nil. INFO is a plist used as a communication
3653 channel."
3654 (let* ((raw-value (org-element-property :raw-value timestamp))
3655 (type (org-element-property :type timestamp)))
3656 (if (not org-odt-use-date-fields)
3657 (let ((value (org-odt-plain-text
3658 (org-timestamp-translate timestamp) info)))
3659 (case (org-element-property :type timestamp)
3660 ((active active-range)
3661 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3662 "OrgActiveTimestamp" value))
3663 ((inactive inactive-range)
3664 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3665 "OrgInactiveTimestamp" value))
3666 (otherwise value)))
3667 (case type
3668 (active
3669 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3670 "OrgActiveTimestamp"
3671 (format "&lt;%s&gt;" (org-odt--format-timestamp timestamp))))
3672 (inactive
3673 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3674 "OrgInactiveTimestamp"
3675 (format "[%s]" (org-odt--format-timestamp timestamp))))
3676 (active-range
3677 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3678 "OrgActiveTimestamp"
3679 (format "&lt;%s&gt;&#x2013;&lt;%s&gt;"
3680 (org-odt--format-timestamp timestamp)
3681 (org-odt--format-timestamp timestamp 'end))))
3682 (inactive-range
3683 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3684 "OrgInactiveTimestamp"
3685 (format "[%s]&#x2013;[%s]"
3686 (org-odt--format-timestamp timestamp)
3687 (org-odt--format-timestamp timestamp 'end))))
3688 (otherwise
3689 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3690 "OrgDiaryTimestamp"
3691 (org-odt-plain-text (org-timestamp-translate timestamp)
3692 info)))))))
3695 ;;;; Underline
3697 (defun org-odt-underline (underline contents info)
3698 "Transcode UNDERLINE from Org to ODT.
3699 CONTENTS is the text with underline markup. INFO is a plist
3700 holding contextual information."
3701 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3702 "Underline" contents))
3705 ;;;; Verbatim
3707 (defun org-odt-verbatim (verbatim contents info)
3708 "Transcode a VERBATIM object from Org to ODT.
3709 CONTENTS is nil. INFO is a plist used as a communication
3710 channel."
3711 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3712 "OrgCode" (org-odt--encode-plain-text
3713 (org-element-property :value verbatim))))
3716 ;;;; Verse Block
3718 (defun org-odt-verse-block (verse-block contents info)
3719 "Transcode a VERSE-BLOCK element from Org to ODT.
3720 CONTENTS is verse block contents. INFO is a plist holding
3721 contextual information."
3722 ;; Add line breaks to each line of verse.
3723 (setq contents (replace-regexp-in-string
3724 "\\(<text:line-break/>\\)?[ \t]*\n"
3725 "<text:line-break/>" contents))
3726 ;; Replace tabs and spaces.
3727 (setq contents (org-odt--encode-tabs-and-spaces contents))
3728 ;; Surround it in a verse environment.
3729 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3730 "OrgVerse" contents))
3734 ;;; Filters
3736 ;;;; LaTeX fragments
3738 (defun org-odt--translate-latex-fragments (tree backend info)
3739 (let ((processing-type (plist-get info :with-latex))
3740 (count 0))
3741 ;; Normalize processing-type to one of dvipng, mathml or verbatim.
3742 ;; If the desired converter is not available, force verbatim
3743 ;; processing.
3744 (case processing-type
3745 ((t mathml)
3746 (if (and (fboundp 'org-format-latex-mathml-available-p)
3747 (org-format-latex-mathml-available-p))
3748 (setq processing-type 'mathml)
3749 (message "LaTeX to MathML converter not available.")
3750 (setq processing-type 'verbatim)))
3751 ((dvipng imagemagick)
3752 (unless (and (org-check-external-command "latex" "" t)
3753 (org-check-external-command
3754 (if (eq processing-type 'dvipng) "dvipng" "convert") "" t))
3755 (message "LaTeX to PNG converter not available.")
3756 (setq processing-type 'verbatim)))
3757 (otherwise
3758 (message "Unknown LaTeX option. Forcing verbatim.")
3759 (setq processing-type 'verbatim)))
3761 ;; Store normalized value for later use.
3762 (when (plist-get info :with-latex)
3763 (plist-put info :with-latex processing-type))
3764 (message "Formatting LaTeX using %s" processing-type)
3766 ;; Convert `latex-fragment's and `latex-environment's.
3767 (when (memq processing-type '(mathml dvipng imagemagick))
3768 (org-element-map tree '(latex-fragment latex-environment)
3769 (lambda (latex-*)
3770 (incf count)
3771 (let* ((latex-frag (org-element-property :value latex-*))
3772 (input-file (plist-get info :input-file))
3773 (cache-dir (file-name-directory input-file))
3774 (cache-subdir (concat
3775 (case processing-type
3776 ((dvipng imagemagick) "ltxpng/")
3777 (mathml "ltxmathml/"))
3778 (file-name-sans-extension
3779 (file-name-nondirectory input-file))))
3780 (display-msg
3781 (case processing-type
3782 ((dvipng imagemagick) (format "Creating LaTeX Image %d..." count))
3783 (mathml (format "Creating MathML snippet %d..." count))))
3784 ;; Get an Org-style link to PNG image or the MathML
3785 ;; file.
3786 (org-link
3787 (let ((link (with-temp-buffer
3788 (insert latex-frag)
3789 (org-format-latex cache-subdir cache-dir
3790 nil display-msg
3791 nil nil processing-type)
3792 (buffer-substring-no-properties
3793 (point-min) (point-max)))))
3794 (if (not (string-match "file:\\([^]]*\\)" link))
3795 (prog1 nil (message "LaTeX Conversion failed."))
3796 link))))
3797 (when org-link
3798 ;; Conversion succeeded. Parse above Org-style link to a
3799 ;; `link' object.
3800 (let* ((link (car (org-element-map (with-temp-buffer
3801 (org-mode)
3802 (insert org-link)
3803 (org-element-parse-buffer))
3804 'link 'identity))))
3805 ;; Orphan the link.
3806 (org-element-put-property link :parent nil)
3807 (let* (
3808 (replacement
3809 (case (org-element-type latex-*)
3810 ;; Case 1: LaTeX environment.
3811 ;; Mimic a "standalone image or formula" by
3812 ;; enclosing the `link' in a `paragraph'.
3813 ;; Copy over original attributes, captions to
3814 ;; the enclosing paragraph.
3815 (latex-environment
3816 (org-element-adopt-elements
3817 (list 'paragraph
3818 (list :style "OrgFormula"
3819 :name (org-element-property :name
3820 latex-*)
3821 :caption (org-element-property :caption
3822 latex-*)))
3823 link))
3824 ;; Case 2: LaTeX fragment.
3825 ;; No special action.
3826 (latex-fragment link))))
3827 ;; Note down the object that link replaces.
3828 (org-element-put-property replacement :replaces
3829 (list (org-element-type latex-*)
3830 (list :value latex-frag)))
3831 ;; Replace now.
3832 (org-element-set-element latex-* replacement))))))
3833 info)))
3834 tree)
3837 ;;;; Description lists
3839 ;; This translator is necessary to handle indented tables in a uniform
3840 ;; manner. See comment in `org-odt--table'.
3842 (defun org-odt--translate-description-lists (tree backend info)
3843 ;; OpenDocument has no notion of a description list. So simulate it
3844 ;; using plain lists. Description lists in the exported document
3845 ;; are typeset in the same manner as they are in a typical HTML
3846 ;; document.
3848 ;; Specifically, a description list like this:
3850 ;; ,----
3851 ;; | - term-1 :: definition-1
3852 ;; | - term-2 :: definition-2
3853 ;; `----
3855 ;; gets translated in to the following form:
3857 ;; ,----
3858 ;; | - term-1
3859 ;; | - definition-1
3860 ;; | - term-2
3861 ;; | - definition-2
3862 ;; `----
3864 ;; Further effect is achieved by fixing the OD styles as below:
3866 ;; 1. Set the :type property of the simulated lists to
3867 ;; `descriptive-1' and `descriptive-2'. Map these to list-styles
3868 ;; that has *no* bullets whatsoever.
3870 ;; 2. The paragraph containing the definition term is styled to be
3871 ;; in bold.
3873 (org-element-map tree 'plain-list
3874 (lambda (el)
3875 (when (equal (org-element-property :type el) 'descriptive)
3876 (org-element-set-element
3878 (apply 'org-element-adopt-elements
3879 (list 'plain-list (list :type 'descriptive-1))
3880 (mapcar
3881 (lambda (item)
3882 (org-element-adopt-elements
3883 (list 'item (list :checkbox (org-element-property
3884 :checkbox item)))
3885 (list 'paragraph (list :style "Text_20_body_20_bold")
3886 (or (org-element-property :tag item) "(no term)"))
3887 (org-element-adopt-elements
3888 (list 'plain-list (list :type 'descriptive-2))
3889 (apply 'org-element-adopt-elements
3890 (list 'item nil)
3891 (org-element-contents item)))))
3892 (org-element-contents el)))))
3893 nil)
3894 info)
3895 tree)
3897 ;;;; List tables
3899 ;; Lists that are marked with attribute `:list-table' are called as
3900 ;; list tables. They will be rendered as a table within the exported
3901 ;; document.
3903 ;; Consider an example. The following list table
3905 ;; #+attr_odt :list-table t
3906 ;; - Row 1
3907 ;; - 1.1
3908 ;; - 1.2
3909 ;; - 1.3
3910 ;; - Row 2
3911 ;; - 2.1
3912 ;; - 2.2
3913 ;; - 2.3
3915 ;; will be exported as though it were an Org table like the one show
3916 ;; below.
3918 ;; | Row 1 | 1.1 | 1.2 | 1.3 |
3919 ;; | Row 2 | 2.1 | 2.2 | 2.3 |
3921 ;; Note that org-tables are NOT multi-line and each line is mapped to
3922 ;; a unique row in the exported document. So if an exported table
3923 ;; needs to contain a single paragraph (with copious text) it needs to
3924 ;; be typed up in a single line. Editing such long lines using the
3925 ;; table editor will be a cumbersome task. Furthermore inclusion of
3926 ;; multi-paragraph text in a table cell is well-nigh impossible.
3928 ;; A LIST-TABLE circumvents above problems.
3930 ;; Note that in the example above the list items could be paragraphs
3931 ;; themselves and the list can be arbitrarily deep.
3933 ;; Inspired by following thread:
3934 ;; https://lists.gnu.org/archive/html/emacs-orgmode/2011-03/msg01101.html
3936 ;; Translate lists to tables
3938 (defun org-odt--translate-list-tables (tree backend info)
3939 (org-element-map tree 'plain-list
3940 (lambda (l1-list)
3941 (when (org-export-read-attribute :attr_odt l1-list :list-table)
3942 ;; Replace list with table.
3943 (org-element-set-element
3944 l1-list
3945 ;; Build replacement table.
3946 (apply 'org-element-adopt-elements
3947 (list 'table '(:type org :attr_odt (":style \"GriddedTable\"")))
3948 (org-element-map l1-list 'item
3949 (lambda (l1-item)
3950 (let* ((l1-item-contents (org-element-contents l1-item))
3951 l1-item-leading-text l2-list)
3952 ;; Remove Level-2 list from the Level-item. It
3953 ;; will be subsequently attached as table-cells.
3954 (let ((cur l1-item-contents) prev)
3955 (while (and cur (not (eq (org-element-type (car cur))
3956 'plain-list)))
3957 (setq prev cur)
3958 (setq cur (cdr cur)))
3959 (when prev
3960 (setcdr prev nil)
3961 (setq l2-list (car cur)))
3962 (setq l1-item-leading-text l1-item-contents))
3963 ;; Level-1 items start a table row.
3964 (apply 'org-element-adopt-elements
3965 (list 'table-row (list :type 'standard))
3966 ;; Leading text of level-1 item define
3967 ;; the first table-cell.
3968 (apply 'org-element-adopt-elements
3969 (list 'table-cell nil)
3970 l1-item-leading-text)
3971 ;; Level-2 items define subsequent
3972 ;; table-cells of the row.
3973 (org-element-map l2-list 'item
3974 (lambda (l2-item)
3975 (apply 'org-element-adopt-elements
3976 (list 'table-cell nil)
3977 (org-element-contents l2-item)))
3978 info nil 'item))))
3979 info nil 'item))))
3980 nil)
3981 info)
3982 tree)
3985 ;;; Interactive functions
3987 (defun org-odt-create-manifest-file-entry (&rest args)
3988 (push args org-odt-manifest-file-entries))
3990 (defun org-odt-write-manifest-file ()
3991 (make-directory (concat org-odt-zip-dir "META-INF"))
3992 (let ((manifest-file (concat org-odt-zip-dir "META-INF/manifest.xml")))
3993 (with-current-buffer
3994 (let ((nxml-auto-insert-xml-declaration-flag nil))
3995 (find-file-noselect manifest-file t))
3996 (insert
3997 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
3998 <manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"1.2\">\n")
3999 (mapc
4000 (lambda (file-entry)
4001 (let* ((version (nth 2 file-entry))
4002 (extra (if (not version) ""
4003 (format " manifest:version=\"%s\"" version))))
4004 (insert
4005 (format org-odt-manifest-file-entry-tag
4006 (nth 0 file-entry) (nth 1 file-entry) extra))))
4007 org-odt-manifest-file-entries)
4008 (insert "\n</manifest:manifest>"))))
4010 (defmacro org-odt--export-wrap (out-file &rest body)
4011 `(let* ((--out-file ,out-file)
4012 (out-file-type (file-name-extension --out-file))
4013 (org-odt-xml-files '("META-INF/manifest.xml" "content.xml"
4014 "meta.xml" "styles.xml"))
4015 ;; Initialize temporary workarea. All files that end up in
4016 ;; the exported document get parked/created here.
4017 (org-odt-zip-dir (file-name-as-directory
4018 (make-temp-file (format "%s-" out-file-type) t)))
4019 (org-odt-manifest-file-entries nil)
4020 (--cleanup-xml-buffers
4021 (function
4022 (lambda nil
4023 ;; Kill all XML buffers.
4024 (mapc (lambda (file)
4025 (let ((buf (find-buffer-visiting
4026 (concat org-odt-zip-dir file))))
4027 (when buf
4028 (with-current-buffer buf
4029 (set-buffer-modified-p nil)
4030 (kill-buffer buf)))))
4031 org-odt-xml-files)
4032 ;; Delete temporary directory and also other embedded
4033 ;; files that get copied there.
4034 (delete-directory org-odt-zip-dir t)))))
4035 (condition-case err
4036 (progn
4037 (unless (executable-find "zip")
4038 ;; Not at all OSes ship with zip by default
4039 (error "Executable \"zip\" needed for creating OpenDocument files"))
4040 ;; Do export. This creates a bunch of xml files ready to be
4041 ;; saved and zipped.
4042 (progn ,@body)
4043 ;; Create a manifest entry for content.xml.
4044 (org-odt-create-manifest-file-entry "text/xml" "content.xml")
4045 ;; Write mimetype file
4046 (let* ((mimetypes
4047 '(("odt" . "application/vnd.oasis.opendocument.text")
4048 ("odf" . "application/vnd.oasis.opendocument.formula")))
4049 (mimetype (cdr (assoc-string out-file-type mimetypes t))))
4050 (unless mimetype
4051 (error "Unknown OpenDocument backend %S" out-file-type))
4052 (write-region mimetype nil (concat org-odt-zip-dir "mimetype"))
4053 (org-odt-create-manifest-file-entry mimetype "/" "1.2"))
4054 ;; Write out the manifest entries before zipping
4055 (org-odt-write-manifest-file)
4056 ;; Save all XML files.
4057 (mapc (lambda (file)
4058 (let ((buf (find-buffer-visiting
4059 (concat org-odt-zip-dir file))))
4060 (when buf
4061 (with-current-buffer buf
4062 ;; Prettify output if needed.
4063 (when org-odt-prettify-xml
4064 (indent-region (point-min) (point-max)))
4065 (save-buffer 0)))))
4066 org-odt-xml-files)
4067 ;; Run zip.
4068 (let* ((target --out-file)
4069 (target-name (file-name-nondirectory target))
4070 (cmds `(("zip" "-mX0" ,target-name "mimetype")
4071 ("zip" "-rmTq" ,target-name "."))))
4072 ;; If a file with same name as the desired output file
4073 ;; exists, remove it.
4074 (when (file-exists-p target)
4075 (delete-file target))
4076 ;; Zip up the xml files.
4077 (let ((coding-system-for-write 'no-conversion) exitcode err-string)
4078 (message "Creating ODT file...")
4079 ;; Switch temporarily to content.xml. This way Zip
4080 ;; process will inherit `org-odt-zip-dir' as the current
4081 ;; directory.
4082 (with-current-buffer
4083 (find-file-noselect (concat org-odt-zip-dir "content.xml") t)
4084 (mapc
4085 (lambda (cmd)
4086 (message "Running %s" (mapconcat 'identity cmd " "))
4087 (setq err-string
4088 (with-output-to-string
4089 (setq exitcode
4090 (apply 'call-process (car cmd)
4091 nil standard-output nil (cdr cmd)))))
4092 (or (zerop exitcode)
4093 (error (concat "Unable to create OpenDocument file."
4094 (format " Zip failed with error (%s)"
4095 err-string)))))
4096 cmds)))
4097 ;; Move the zip file from temporary work directory to
4098 ;; user-mandated location.
4099 (rename-file (concat org-odt-zip-dir target-name) target)
4100 (message "Created %s" (expand-file-name target))
4101 ;; Cleanup work directory and work files.
4102 (funcall --cleanup-xml-buffers)
4103 ;; Open the OpenDocument file in archive-mode for
4104 ;; examination.
4105 (find-file-noselect target t)
4106 ;; Return exported file.
4107 (cond
4108 ;; Case 1: Conversion desired on exported file. Run the
4109 ;; converter on the OpenDocument file. Return the
4110 ;; converted file.
4111 (org-odt-preferred-output-format
4112 (or (org-odt-convert target org-odt-preferred-output-format)
4113 target))
4114 ;; Case 2: No further conversion. Return exported
4115 ;; OpenDocument file.
4116 (t target))))
4117 (error
4118 ;; Cleanup work directory and work files.
4119 (funcall --cleanup-xml-buffers)
4120 (message "OpenDocument export failed: %s"
4121 (error-message-string err))))))
4124 ;;;; Export to OpenDocument formula
4126 ;;;###autoload
4127 (defun org-odt-export-as-odf (latex-frag &optional odf-file)
4128 "Export LATEX-FRAG as OpenDocument formula file ODF-FILE.
4129 Use `org-create-math-formula' to convert LATEX-FRAG first to
4130 MathML. When invoked as an interactive command, use
4131 `org-latex-regexps' to infer LATEX-FRAG from currently active
4132 region. If no LaTeX fragments are found, prompt for it. Push
4133 MathML source to kill ring depending on the value of
4134 `org-export-copy-to-kill-ring'."
4135 (interactive
4136 `(,(let (frag)
4137 (setq frag (and (setq frag (and (region-active-p)
4138 (buffer-substring (region-beginning)
4139 (region-end))))
4140 (loop for e in org-latex-regexps
4141 thereis (when (string-match (nth 1 e) frag)
4142 (match-string (nth 2 e) frag)))))
4143 (read-string "LaTeX Fragment: " frag nil frag))
4144 ,(let ((odf-filename (expand-file-name
4145 (concat
4146 (file-name-sans-extension
4147 (or (file-name-nondirectory buffer-file-name)))
4148 "." "odf")
4149 (file-name-directory buffer-file-name))))
4150 (read-file-name "ODF filename: " nil odf-filename nil
4151 (file-name-nondirectory odf-filename)))))
4152 (let ((filename (or odf-file
4153 (expand-file-name
4154 (concat
4155 (file-name-sans-extension
4156 (or (file-name-nondirectory buffer-file-name)))
4157 "." "odf")
4158 (file-name-directory buffer-file-name)))))
4159 (org-odt--export-wrap
4160 filename
4161 (let* ((buffer (progn
4162 (require 'nxml-mode)
4163 (let ((nxml-auto-insert-xml-declaration-flag nil))
4164 (find-file-noselect (concat org-odt-zip-dir
4165 "content.xml") t))))
4166 (coding-system-for-write 'utf-8)
4167 (save-buffer-coding-system 'utf-8))
4168 (set-buffer buffer)
4169 (set-buffer-file-coding-system coding-system-for-write)
4170 (let ((mathml (org-create-math-formula latex-frag)))
4171 (unless mathml (error "No Math formula created"))
4172 (insert mathml)
4173 ;; Add MathML to kill ring, if needed.
4174 (when (org-export--copy-to-kill-ring-p)
4175 (org-kill-new (buffer-string))))))))
4177 ;;;###autoload
4178 (defun org-odt-export-as-odf-and-open ()
4179 "Export LaTeX fragment as OpenDocument formula and immediately open it.
4180 Use `org-odt-export-as-odf' to read LaTeX fragment and OpenDocument
4181 formula file."
4182 (interactive)
4183 (org-open-file (call-interactively 'org-odt-export-as-odf) 'system))
4186 ;;;; Export to OpenDocument Text
4188 ;;;###autoload
4189 (defun org-odt-export-to-odt (&optional async subtreep visible-only ext-plist)
4190 "Export current buffer to a ODT file.
4192 If narrowing is active in the current buffer, only export its
4193 narrowed part.
4195 If a region is active, export that region.
4197 A non-nil optional argument ASYNC means the process should happen
4198 asynchronously. The resulting file should be accessible through
4199 the `org-export-stack' interface.
4201 When optional argument SUBTREEP is non-nil, export the sub-tree
4202 at point, extracting information from the headline properties
4203 first.
4205 When optional argument VISIBLE-ONLY is non-nil, don't export
4206 contents of hidden elements.
4208 EXT-PLIST, when provided, is a property list with external
4209 parameters overriding Org default settings, but still inferior to
4210 file-local settings.
4212 Return output file's name."
4213 (interactive)
4214 (let ((outfile (org-export-output-file-name ".odt" subtreep)))
4215 (if async
4216 (org-export-async-start (lambda (f) (org-export-add-to-stack f 'odt))
4217 `(expand-file-name
4218 (org-odt--export-wrap
4219 ,outfile
4220 (let* ((org-odt-embedded-images-count 0)
4221 (org-odt-embedded-formulas-count 0)
4222 (org-odt-automatic-styles nil)
4223 (org-odt-object-counters nil)
4224 ;; Let `htmlfontify' know that we are interested in
4225 ;; collecting styles.
4226 (hfy-user-sheet-assoc nil))
4227 ;; Initialize content.xml and kick-off the export
4228 ;; process.
4229 (let ((out-buf
4230 (progn
4231 (require 'nxml-mode)
4232 (let ((nxml-auto-insert-xml-declaration-flag nil))
4233 (find-file-noselect
4234 (concat org-odt-zip-dir "content.xml") t))))
4235 (output (org-export-as
4236 'odt ,subtreep ,visible-only nil ,ext-plist)))
4237 (with-current-buffer out-buf
4238 (erase-buffer)
4239 (insert output)))))))
4240 (org-odt--export-wrap
4241 outfile
4242 (let* ((org-odt-embedded-images-count 0)
4243 (org-odt-embedded-formulas-count 0)
4244 (org-odt-automatic-styles nil)
4245 (org-odt-object-counters nil)
4246 ;; Let `htmlfontify' know that we are interested in collecting
4247 ;; styles.
4248 (hfy-user-sheet-assoc nil))
4249 ;; Initialize content.xml and kick-off the export process.
4250 (let ((output (org-export-as 'odt subtreep visible-only nil ext-plist))
4251 (out-buf (progn
4252 (require 'nxml-mode)
4253 (let ((nxml-auto-insert-xml-declaration-flag nil))
4254 (find-file-noselect
4255 (concat org-odt-zip-dir "content.xml") t)))))
4256 (with-current-buffer out-buf (erase-buffer) (insert output))))))))
4259 ;;;; Convert between OpenDocument and other formats
4261 (defun org-odt-reachable-p (in-fmt out-fmt)
4262 "Return non-nil if IN-FMT can be converted to OUT-FMT."
4263 (catch 'done
4264 (let ((reachable-formats (org-odt-do-reachable-formats in-fmt)))
4265 (dolist (e reachable-formats)
4266 (let ((out-fmt-spec (assoc out-fmt (cdr e))))
4267 (when out-fmt-spec
4268 (throw 'done (cons (car e) out-fmt-spec))))))))
4270 (defun org-odt-do-convert (in-file out-fmt &optional prefix-arg)
4271 "Workhorse routine for `org-odt-convert'."
4272 (require 'browse-url)
4273 (let* ((in-file (expand-file-name (or in-file buffer-file-name)))
4274 (dummy (or (file-readable-p in-file)
4275 (error "Cannot read %s" in-file)))
4276 (in-fmt (file-name-extension in-file))
4277 (out-fmt (or out-fmt (error "Output format unspecified")))
4278 (how (or (org-odt-reachable-p in-fmt out-fmt)
4279 (error "Cannot convert from %s format to %s format?"
4280 in-fmt out-fmt)))
4281 (convert-process (car how))
4282 (out-file (concat (file-name-sans-extension in-file) "."
4283 (nth 1 (or (cdr how) out-fmt))))
4284 (extra-options (or (nth 2 (cdr how)) ""))
4285 (out-dir (file-name-directory in-file))
4286 (cmd (format-spec convert-process
4287 `((?i . ,(shell-quote-argument in-file))
4288 (?I . ,(browse-url-file-url in-file))
4289 (?f . ,out-fmt)
4290 (?o . ,out-file)
4291 (?O . ,(browse-url-file-url out-file))
4292 (?d . , (shell-quote-argument out-dir))
4293 (?D . ,(browse-url-file-url out-dir))
4294 (?x . ,extra-options)))))
4295 (when (file-exists-p out-file)
4296 (delete-file out-file))
4298 (message "Executing %s" cmd)
4299 (let ((cmd-output (shell-command-to-string cmd)))
4300 (message "%s" cmd-output))
4302 (cond
4303 ((file-exists-p out-file)
4304 (message "Exported to %s" out-file)
4305 (when prefix-arg
4306 (message "Opening %s..." out-file)
4307 (org-open-file out-file 'system))
4308 out-file)
4310 (message "Export to %s failed" out-file)
4311 nil))))
4313 (defun org-odt-do-reachable-formats (in-fmt)
4314 "Return verbose info about formats to which IN-FMT can be converted.
4315 Return a list where each element is of the
4316 form (CONVERTER-PROCESS . OUTPUT-FMT-ALIST). See
4317 `org-odt-convert-processes' for CONVERTER-PROCESS and see
4318 `org-odt-convert-capabilities' for OUTPUT-FMT-ALIST."
4319 (let* ((converter
4320 (and org-odt-convert-process
4321 (cadr (assoc-string org-odt-convert-process
4322 org-odt-convert-processes t))))
4323 (capabilities
4324 (and org-odt-convert-process
4325 (cadr (assoc-string org-odt-convert-process
4326 org-odt-convert-processes t))
4327 org-odt-convert-capabilities))
4328 reachable-formats)
4329 (when converter
4330 (dolist (c capabilities)
4331 (when (member in-fmt (nth 1 c))
4332 (push (cons converter (nth 2 c)) reachable-formats))))
4333 reachable-formats))
4335 (defun org-odt-reachable-formats (in-fmt)
4336 "Return list of formats to which IN-FMT can be converted.
4337 The list of the form (OUTPUT-FMT-1 OUTPUT-FMT-2 ...)."
4338 (let (l)
4339 (mapc (lambda (e) (add-to-list 'l e))
4340 (apply 'append (mapcar
4341 (lambda (e) (mapcar 'car (cdr e)))
4342 (org-odt-do-reachable-formats in-fmt))))
4345 (defun org-odt-convert-read-params ()
4346 "Return IN-FILE and OUT-FMT params for `org-odt-do-convert'.
4347 This is a helper routine for interactive use."
4348 (let* ((input (if (featurep 'ido) 'ido-completing-read 'completing-read))
4349 (in-file (read-file-name "File to be converted: "
4350 nil buffer-file-name t))
4351 (in-fmt (file-name-extension in-file))
4352 (out-fmt-choices (org-odt-reachable-formats in-fmt))
4353 (out-fmt
4354 (or (and out-fmt-choices
4355 (funcall input "Output format: "
4356 out-fmt-choices nil nil nil))
4357 (error
4358 "No known converter or no known output formats for %s files"
4359 in-fmt))))
4360 (list in-file out-fmt)))
4362 ;;;###autoload
4363 (defun org-odt-convert (&optional in-file out-fmt prefix-arg)
4364 "Convert IN-FILE to format OUT-FMT using a command line converter.
4365 IN-FILE is the file to be converted. If unspecified, it defaults
4366 to variable `buffer-file-name'. OUT-FMT is the desired output
4367 format. Use `org-odt-convert-process' as the converter.
4368 If PREFIX-ARG is non-nil then the newly converted file is opened
4369 using `org-open-file'."
4370 (interactive
4371 (append (org-odt-convert-read-params) current-prefix-arg))
4372 (org-odt-do-convert in-file out-fmt prefix-arg))
4374 ;;; Library Initializations
4376 (mapc
4377 (lambda (desc)
4378 ;; Let Emacs open all OpenDocument files in archive mode
4379 (add-to-list 'auto-mode-alist
4380 (cons (concat "\\." (car desc) "\\'") 'archive-mode)))
4381 org-odt-file-extensions)
4383 (provide 'ox-odt)
4385 ;; Local variables:
4386 ;; generated-autoload-file: "org-loaddefs.el"
4387 ;; End:
4389 ;;; ox-odt.el ends here