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