ox-odt: Small fix
[org-mode.git] / lisp / ox-odt.el
blob9fe5e9f00a64df2dc722cfb2c48742e596104604
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 (plist-get info :keywords))
1333 (description (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 (let ((creator-info (plist-get info :with-creator)))
1363 (if (or (not creator-info) (eq creator-info 'comment)) ""
1364 (plist-get info :creator))))
1365 (format "<meta:keyword>%s</meta:keyword>\n" keywords)
1366 (format "<dc:subject>%s</dc:subject>\n" description)
1367 (format "<dc:title>%s</dc:title>\n" title)
1368 "\n"
1369 " </office:meta>\n" "</office:document-meta>")
1370 nil (concat org-odt-zip-dir "meta.xml"))
1371 ;; Add meta.xml in to manifest.
1372 (org-odt-create-manifest-file-entry "text/xml" "meta.xml"))
1374 ;; Update styles file.
1375 ;; Copy styles.xml. Also dump htmlfontify styles, if there is any.
1376 ;; Write styles file.
1377 (let* ((styles-file (plist-get info :odt-styles-file))
1378 (styles-file (and styles-file (read (org-trim styles-file))))
1379 ;; Non-availability of styles.xml is not a critical
1380 ;; error. For now, throw an error.
1381 (styles-file (or styles-file
1382 (plist-get info :odt-styles-file)
1383 (expand-file-name "OrgOdtStyles.xml"
1384 org-odt-styles-dir)
1385 (error "org-odt: Missing styles file?"))))
1386 (cond
1387 ((listp styles-file)
1388 (let ((archive (nth 0 styles-file))
1389 (members (nth 1 styles-file)))
1390 (org-odt--zip-extract archive members org-odt-zip-dir)
1391 (mapc
1392 (lambda (member)
1393 (when (org-file-image-p member)
1394 (let* ((image-type (file-name-extension member))
1395 (media-type (format "image/%s" image-type)))
1396 (org-odt-create-manifest-file-entry media-type member))))
1397 members)))
1398 ((and (stringp styles-file) (file-exists-p styles-file))
1399 (let ((styles-file-type (file-name-extension styles-file)))
1400 (cond
1401 ((string= styles-file-type "xml")
1402 (copy-file styles-file (concat org-odt-zip-dir "styles.xml") t))
1403 ((member styles-file-type '("odt" "ott"))
1404 (org-odt--zip-extract styles-file "styles.xml" org-odt-zip-dir)))))
1406 (error (format "Invalid specification of styles.xml file: %S"
1407 (plist-get info :odt-styles-file)))))
1409 ;; create a manifest entry for styles.xml
1410 (org-odt-create-manifest-file-entry "text/xml" "styles.xml")
1412 ;; FIXME: Who is opening an empty styles.xml before this point?
1413 (with-current-buffer
1414 (find-file-noselect (concat org-odt-zip-dir "styles.xml") t)
1415 (revert-buffer t t)
1417 ;; Write custom styles for source blocks
1418 ;; Save STYLES used for colorizing of source blocks.
1419 ;; Update styles.xml with styles that were collected as part of
1420 ;; `org-odt-hfy-face-to-css' callbacks.
1421 (let ((styles (mapconcat (lambda (style) (format " %s\n" (cddr style)))
1422 hfy-user-sheet-assoc "")))
1423 (when styles
1424 (goto-char (point-min))
1425 (when (re-search-forward "</office:styles>" nil t)
1426 (goto-char (match-beginning 0))
1427 (insert "\n<!-- Org Htmlfontify Styles -->\n" styles "\n"))))
1429 ;; Update styles.xml - take care of outline numbering
1431 ;; Don't make automatic backup of styles.xml file. This setting
1432 ;; prevents the backed-up styles.xml file from being zipped in to
1433 ;; odt file. This is more of a hackish fix. Better alternative
1434 ;; would be to fix the zip command so that the output odt file
1435 ;; includes only the needed files and excludes any auto-generated
1436 ;; extra files like backups and auto-saves etc etc. Note that
1437 ;; currently the zip command zips up the entire temp directory so
1438 ;; that any auto-generated files created under the hood ends up in
1439 ;; the resulting odt file.
1440 (set (make-local-variable 'backup-inhibited) t)
1442 ;; Outline numbering is retained only upto LEVEL.
1443 ;; To disable outline numbering pass a LEVEL of 0.
1445 (goto-char (point-min))
1446 (let ((regex
1447 "<text:outline-level-style\\([^>]*\\)text:level=\"\\([^\"]*\\)\"\\([^>]*\\)>")
1448 (replacement
1449 "<text:outline-level-style\\1text:level=\"\\2\" style:num-format=\"\">"))
1450 (while (re-search-forward regex nil t)
1451 (unless (let ((sec-num (plist-get info :section-numbers))
1452 (level (string-to-number (match-string 2))))
1453 (if (wholenump sec-num) (<= level sec-num) sec-num))
1454 (replace-match replacement t nil))))
1455 (save-buffer 0)))
1456 ;; Update content.xml.
1458 (let* ( ;; `org-display-custom-times' should be accessed right
1459 ;; within the context of the Org buffer. So obtain its
1460 ;; value before moving on to temp-buffer context down below.
1461 (custom-time-fmts
1462 (if org-display-custom-times
1463 (cons (substring (car org-time-stamp-custom-formats) 1 -1)
1464 (substring (cdr org-time-stamp-custom-formats) 1 -1))
1465 '("%Y-%M-%d %a" . "%Y-%M-%d %a %H:%M"))))
1466 (with-temp-buffer
1467 (insert-file-contents
1468 (or (plist-get info :odt-content-template-file)
1469 (expand-file-name "OrgOdtContentTemplate.xml"
1470 org-odt-styles-dir)))
1471 ;; Write automatic styles.
1472 ;; - Position the cursor.
1473 (goto-char (point-min))
1474 (re-search-forward " </office:automatic-styles>" nil t)
1475 (goto-char (match-beginning 0))
1476 ;; - Dump automatic table styles.
1477 (loop for (style-name props) in
1478 (plist-get org-odt-automatic-styles 'Table) do
1479 (when (setq props (or (plist-get props :rel-width) "96"))
1480 (insert (format org-odt-table-style-format style-name props))))
1481 ;; - Dump date-styles.
1482 (when (plist-get info :odt-use-date-fields)
1483 (insert (org-odt--build-date-styles (car custom-time-fmts)
1484 "OrgDate1")
1485 (org-odt--build-date-styles (cdr custom-time-fmts)
1486 "OrgDate2")))
1487 ;; Update display level.
1488 ;; - Remove existing sequence decls. Also position the cursor.
1489 (goto-char (point-min))
1490 (when (re-search-forward "<text:sequence-decls" nil t)
1491 (delete-region (match-beginning 0)
1492 (re-search-forward "</text:sequence-decls>" nil nil)))
1493 ;; Update sequence decls according to user preference.
1494 (insert
1495 (format
1496 "\n<text:sequence-decls>\n%s\n</text:sequence-decls>"
1497 (mapconcat
1498 (lambda (x)
1499 (format
1500 "<text:sequence-decl text:display-outline-level=\"%d\" text:name=\"%s\"/>"
1501 (plist-get info :odt-display-outline-level)
1502 (nth 1 x)))
1503 org-odt-category-map-alist "\n")))
1504 ;; Position the cursor to document body.
1505 (goto-char (point-min))
1506 (re-search-forward "</office:text>" nil nil)
1507 (goto-char (match-beginning 0))
1509 ;; Preamble - Title, Author, Date etc.
1510 (insert
1511 (let* ((title (and (plist-get info :with-title)
1512 (org-export-data (plist-get info :title) info)))
1513 (author (and (plist-get info :with-author)
1514 (let ((auth (plist-get info :author)))
1515 (and auth (org-export-data auth info)))))
1516 (email (plist-get info :email))
1517 ;; Switch on or off above vars based on user settings
1518 (author (and (plist-get info :with-author) (or author email)))
1519 (email (and (plist-get info :with-email) email)))
1520 (concat
1521 ;; Title.
1522 (when (org-string-nw-p title)
1523 (concat
1524 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1525 "OrgTitle" (format "\n<text:title>%s</text:title>" title))
1526 ;; Separator.
1527 "\n<text:p text:style-name=\"OrgTitle\"/>"))
1528 (cond
1529 ((and author (not email))
1530 ;; Author only.
1531 (concat
1532 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1533 "OrgSubtitle"
1534 (format "<text:initial-creator>%s</text:initial-creator>" author))
1535 ;; Separator.
1536 "\n<text:p text:style-name=\"OrgSubtitle\"/>"))
1537 ((and author email)
1538 ;; Author and E-mail.
1539 (concat
1540 (format
1541 "\n<text:p text:style-name=\"%s\">%s</text:p>"
1542 "OrgSubtitle"
1543 (format
1544 "<text:a xlink:type=\"simple\" xlink:href=\"%s\">%s</text:a>"
1545 (concat "mailto:" email)
1546 (format "<text:initial-creator>%s</text:initial-creator>" author)))
1547 ;; Separator.
1548 "\n<text:p text:style-name=\"OrgSubtitle\"/>")))
1549 ;; Date, if required.
1550 (when (plist-get info :with-date)
1551 (let* ((date (plist-get info :date))
1552 ;; Check if DATE is specified as a timestamp.
1553 (timestamp (and (not (cdr date))
1554 (eq (org-element-type (car date)) 'timestamp)
1555 (car date))))
1556 (concat
1557 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1558 "OrgSubtitle"
1559 (if (and (plist-get info :odt-use-date-fields) timestamp)
1560 (org-odt--format-timestamp (car date))
1561 (org-export-data (plist-get info :date) info)))
1562 ;; Separator
1563 "<text:p text:style-name=\"OrgSubtitle\"/>"))))))
1564 ;; Table of Contents
1565 (let* ((with-toc (plist-get info :with-toc))
1566 (depth (and with-toc (if (wholenump with-toc)
1567 with-toc
1568 (plist-get info :headline-levels)))))
1569 (when depth (insert (or (org-odt-toc depth info) ""))))
1570 ;; Contents.
1571 (insert contents)
1572 ;; Return contents.
1573 (buffer-substring-no-properties (point-min) (point-max)))))
1577 ;;; Transcode Functions
1579 ;;;; Bold
1581 (defun org-odt-bold (bold contents info)
1582 "Transcode BOLD from Org to ODT.
1583 CONTENTS is the text with bold markup. INFO is a plist holding
1584 contextual information."
1585 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1586 "Bold" contents))
1589 ;;;; Center Block
1591 (defun org-odt-center-block (center-block contents info)
1592 "Transcode a CENTER-BLOCK element from Org to ODT.
1593 CONTENTS holds the contents of the center block. INFO is a plist
1594 holding contextual information."
1595 contents)
1598 ;;;; Clock
1600 (defun org-odt-clock (clock contents info)
1601 "Transcode a CLOCK element from Org to ODT.
1602 CONTENTS is nil. INFO is a plist used as a communication
1603 channel."
1604 (let ((timestamp (org-element-property :value clock))
1605 (duration (org-element-property :duration clock)))
1606 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1607 (if (eq (org-element-type (org-export-get-next-element clock info))
1608 'clock) "OrgClock" "OrgClockLastLine")
1609 (concat
1610 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1611 "OrgClockKeyword" org-clock-string)
1612 (org-odt-timestamp timestamp contents info)
1613 (and duration (format " (%s)" duration))))))
1616 ;;;; Code
1618 (defun org-odt-code (code contents info)
1619 "Transcode a CODE object from Org to ODT.
1620 CONTENTS is nil. INFO is a plist used as a communication
1621 channel."
1622 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1623 "OrgCode" (org-odt--encode-plain-text
1624 (org-element-property :value code))))
1627 ;;;; Comment
1629 ;; Comments are ignored.
1632 ;;;; Comment Block
1634 ;; Comment Blocks are ignored.
1637 ;;;; Drawer
1639 (defun org-odt-drawer (drawer contents info)
1640 "Transcode a DRAWER element from Org to ODT.
1641 CONTENTS holds the contents of the block. INFO is a plist
1642 holding contextual information."
1643 (let* ((name (org-element-property :drawer-name drawer))
1644 (output (funcall (plist-get info :odt-format-drawer-function)
1645 name contents)))
1646 output))
1649 ;;;; Dynamic Block
1651 (defun org-odt-dynamic-block (dynamic-block contents info)
1652 "Transcode a DYNAMIC-BLOCK element from Org to ODT.
1653 CONTENTS holds the contents of the block. INFO is a plist
1654 holding contextual information. See `org-export-data'."
1655 contents)
1658 ;;;; Entity
1660 (defun org-odt-entity (entity contents info)
1661 "Transcode an ENTITY object from Org to ODT.
1662 CONTENTS are the definition itself. INFO is a plist holding
1663 contextual information."
1664 (org-element-property :utf-8 entity))
1667 ;;;; Example Block
1669 (defun org-odt-example-block (example-block contents info)
1670 "Transcode a EXAMPLE-BLOCK element from Org to ODT.
1671 CONTENTS is nil. INFO is a plist holding contextual information."
1672 (org-odt-format-code example-block info))
1675 ;;;; Export Snippet
1677 (defun org-odt-export-snippet (export-snippet contents info)
1678 "Transcode a EXPORT-SNIPPET object from Org to ODT.
1679 CONTENTS is nil. INFO is a plist holding contextual information."
1680 (when (eq (org-export-snippet-backend export-snippet) 'odt)
1681 (org-element-property :value export-snippet)))
1684 ;;;; Export Block
1686 (defun org-odt-export-block (export-block contents info)
1687 "Transcode a EXPORT-BLOCK element from Org to ODT.
1688 CONTENTS is nil. INFO is a plist holding contextual information."
1689 (when (string= (org-element-property :type export-block) "ODT")
1690 (org-remove-indentation (org-element-property :value export-block))))
1693 ;;;; Fixed Width
1695 (defun org-odt-fixed-width (fixed-width contents info)
1696 "Transcode a FIXED-WIDTH element from Org to ODT.
1697 CONTENTS is nil. INFO is a plist holding contextual information."
1698 (org-odt-do-format-code (org-element-property :value fixed-width) info))
1701 ;;;; Footnote Definition
1703 ;; Footnote Definitions are ignored.
1706 ;;;; Footnote Reference
1708 (defun org-odt-footnote-reference (footnote-reference contents info)
1709 "Transcode a FOOTNOTE-REFERENCE element from Org to ODT.
1710 CONTENTS is nil. INFO is a plist holding contextual information."
1711 (let ((--format-footnote-definition
1712 (function
1713 (lambda (n def)
1714 (setq n (format "%d" n))
1715 (let ((id (concat "fn" n))
1716 (note-class "footnote")
1717 (par-style "Footnote"))
1718 (format
1719 "<text:note text:id=\"%s\" text:note-class=\"%s\">%s</text:note>"
1720 id note-class
1721 (concat
1722 (format "<text:note-citation>%s</text:note-citation>" n)
1723 (format "<text:note-body>%s</text:note-body>" def)))))))
1724 (--format-footnote-reference
1725 (function
1726 (lambda (n)
1727 (setq n (format "%d" n))
1728 (let ((note-class "footnote")
1729 (ref-format "text")
1730 (ref-name (concat "fn" n)))
1731 (format
1732 "<text:span text:style-name=\"%s\">%s</text:span>"
1733 "OrgSuperscript"
1734 (format "<text:note-ref text:note-class=\"%s\" text:reference-format=\"%s\" text:ref-name=\"%s\">%s</text:note-ref>"
1735 note-class ref-format ref-name n)))))))
1736 (concat
1737 ;; Insert separator between two footnotes in a row.
1738 (let ((prev (org-export-get-previous-element footnote-reference info)))
1739 (and (eq (org-element-type prev) 'footnote-reference)
1740 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1741 "OrgSuperscript" ",")))
1742 ;; Transcode footnote reference.
1743 (let ((n (org-export-get-footnote-number footnote-reference info nil t)))
1744 (cond
1745 ((not
1746 (org-export-footnote-first-reference-p footnote-reference info nil t))
1747 (funcall --format-footnote-reference n))
1748 ;; Inline definitions are secondary strings.
1749 ;; Non-inline footnotes definitions are full Org data.
1751 (let* ((raw (org-export-get-footnote-definition
1752 footnote-reference info))
1753 (def
1754 (let ((def (org-trim
1755 (org-export-data-with-backend
1757 (org-export-create-backend
1758 :parent 'odt
1759 :transcoders
1760 '((paragraph . (lambda (p c i)
1761 (org-odt--format-paragraph
1762 p c i
1763 "Footnote"
1764 "OrgFootnoteCenter"
1765 "OrgFootnoteQuotations")))))
1766 info))))
1767 (if (eq (org-element-type raw) 'org-data) def
1768 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1769 "Footnote" def)))))
1770 (funcall --format-footnote-definition n def))))))))
1773 ;;;; Headline
1775 (defun org-odt-format-headline--wrap (headline backend info
1776 &optional format-function
1777 &rest extra-keys)
1778 "Transcode a HEADLINE element using BACKEND.
1779 INFO is a plist holding contextual information."
1780 (setq backend (or backend (plist-get info :back-end)))
1781 (let* ((level (+ (org-export-get-relative-level headline info)))
1782 (headline-number (org-export-get-headline-number headline info))
1783 (section-number (and (org-export-numbered-headline-p headline info)
1784 (mapconcat 'number-to-string
1785 headline-number ".")))
1786 (todo (and (plist-get info :with-todo-keywords)
1787 (let ((todo (org-element-property :todo-keyword headline)))
1788 (and todo
1789 (org-export-data-with-backend todo backend info)))))
1790 (todo-type (and todo (org-element-property :todo-type headline)))
1791 (priority (and (plist-get info :with-priority)
1792 (org-element-property :priority headline)))
1793 (text (org-export-data-with-backend
1794 (org-element-property :title headline) backend info))
1795 (tags (and (plist-get info :with-tags)
1796 (org-export-get-tags headline info)))
1797 (headline-label (org-export-get-headline-id headline info))
1798 (format-function
1799 (if (functionp format-function) format-function
1800 (function*
1801 (lambda (todo todo-type priority text tags
1802 &key level section-number headline-label
1803 &allow-other-keys)
1804 (funcall (plist-get info :odt-format-headline-function)
1805 todo todo-type priority text tags))))))
1806 (apply format-function
1807 todo todo-type priority text tags
1808 :headline-label headline-label :level level
1809 :section-number section-number extra-keys)))
1811 (defun org-odt-headline (headline contents info)
1812 "Transcode a HEADLINE element from Org to ODT.
1813 CONTENTS holds the contents of the headline. INFO is a plist
1814 holding contextual information."
1815 ;; Case 1: This is a footnote section: ignore it.
1816 (unless (org-element-property :footnote-section-p headline)
1817 (let* ((text (org-export-data (org-element-property :title headline) info))
1818 ;; Create the headline text.
1819 (full-text (org-odt-format-headline--wrap headline nil info))
1820 ;; Get level relative to current parsed data.
1821 (level (org-export-get-relative-level headline info))
1822 (numbered (org-export-numbered-headline-p headline info))
1823 ;; Get canonical label for the headline.
1824 (id (org-export-get-headline-id headline info))
1825 ;; Get user-specified labels for the headline.
1826 (extra-ids (list (org-element-property :CUSTOM_ID headline)
1827 (org-element-property :ID headline)))
1828 ;; Extra targets.
1829 (extra-targets
1830 (mapconcat (lambda (x)
1831 (when x
1832 (let ((x (if (org-uuidgen-p x) (concat "ID-" x) x)))
1833 (org-odt--target
1834 "" (org-export-solidify-link-text x)))))
1835 extra-ids ""))
1836 ;; Title.
1837 (anchored-title (org-odt--target full-text id)))
1838 (cond
1839 ;; Case 2. This is a deep sub-tree: export it as a list item.
1840 ;; Also export as items headlines for which no section
1841 ;; format has been found.
1842 ((org-export-low-level-p headline info)
1843 ;; Build the real contents of the sub-tree.
1844 (concat
1845 (and (org-export-first-sibling-p headline info)
1846 (format "\n<text:list text:style-name=\"%s\" %s>"
1847 ;; Choose style based on list type.
1848 (if numbered "OrgNumberedList" "OrgBulletedList")
1849 ;; If top-level list, re-start numbering. Otherwise,
1850 ;; continue numbering.
1851 (format "text:continue-numbering=\"%s\""
1852 (let* ((parent (org-export-get-parent-headline
1853 headline)))
1854 (if (and parent
1855 (org-export-low-level-p parent info))
1856 "true" "false")))))
1857 (let ((headline-has-table-p
1858 (let ((section (assq 'section (org-element-contents headline))))
1859 (assq 'table (and section (org-element-contents section))))))
1860 (format "\n<text:list-item>\n%s\n%s"
1861 (concat
1862 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1863 "Text_20_body"
1864 (concat extra-targets anchored-title))
1865 contents)
1866 (if headline-has-table-p
1867 "</text:list-header>"
1868 "</text:list-item>")))
1869 (and (org-export-last-sibling-p headline info)
1870 "</text:list>")))
1871 ;; Case 3. Standard headline. Export it as a section.
1873 (concat
1874 (format
1875 "\n<text:h text:style-name=\"%s\" text:outline-level=\"%s\" text:is-list-header=\"%s\">%s</text:h>"
1876 (format "Heading_20_%s%s"
1877 level (if numbered "" "_unnumbered"))
1878 level
1879 (if numbered "false" "true")
1880 (concat extra-targets anchored-title))
1881 contents))))))
1883 (defun org-odt-format-headline-default-function
1884 (todo todo-type priority text tags)
1885 "Default format function for a headline.
1886 See `org-odt-format-headline-function' for details."
1887 (concat
1888 ;; Todo.
1889 (when todo
1890 (let ((style (if (eq todo-type 'done) "OrgDone" "OrgTodo")))
1891 (format "<text:span text:style-name=\"%s\">%s</text:span> " style todo)))
1892 (when priority
1893 (let* ((style (format "OrgPriority-%s" priority))
1894 (priority (format "[#%c]" priority)))
1895 (format "<text:span text:style-name=\"%s\">%s</text:span> "
1896 style priority)))
1897 ;; Title.
1898 text
1899 ;; Tags.
1900 (when tags
1901 (concat
1902 "<text:tab/>"
1903 (format "<text:span text:style-name=\"%s\">[%s]</text:span>"
1904 "OrgTags" (mapconcat
1905 (lambda (tag)
1906 (format
1907 "<text:span text:style-name=\"%s\">%s</text:span>"
1908 "OrgTag" tag)) tags " : "))))))
1911 ;;;; Horizontal Rule
1913 (defun org-odt-horizontal-rule (horizontal-rule contents info)
1914 "Transcode an HORIZONTAL-RULE object from Org to ODT.
1915 CONTENTS is nil. INFO is a plist holding contextual information."
1916 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1917 "Horizontal_20_Line" ""))
1920 ;;;; Inline Babel Call
1922 ;; Inline Babel Calls are ignored.
1925 ;;;; Inline Src Block
1927 (defun org-odt--find-verb-separator (s)
1928 "Return a character not used in string S.
1929 This is used to choose a separator for constructs like \\verb."
1930 (let ((ll "~,./?;':\"|!@#%^&-_=+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>()[]{}"))
1931 (loop for c across ll
1932 when (not (string-match (regexp-quote (char-to-string c)) s))
1933 return (char-to-string c))))
1935 (defun org-odt-inline-src-block (inline-src-block contents info)
1936 "Transcode an INLINE-SRC-BLOCK element from Org to ODT.
1937 CONTENTS holds the contents of the item. INFO is a plist holding
1938 contextual information."
1939 (let* ((org-lang (org-element-property :language inline-src-block))
1940 (code (org-element-property :value inline-src-block))
1941 (separator (org-odt--find-verb-separator code)))
1942 (error "FIXME")))
1945 ;;;; Inlinetask
1947 (defun org-odt-inlinetask (inlinetask contents info)
1948 "Transcode an INLINETASK element from Org to ODT.
1949 CONTENTS holds the contents of the block. INFO is a plist
1950 holding contextual information."
1951 (let* ((todo
1952 (and (plist-get info :with-todo-keywords)
1953 (let ((todo (org-element-property :todo-keyword inlinetask)))
1954 (and todo (org-export-data todo info)))))
1955 (todo-type (and todo (org-element-property :todo-type inlinetask)))
1956 (priority (and (plist-get info :with-priority)
1957 (org-element-property :priority inlinetask)))
1958 (text (org-export-data (org-element-property :title inlinetask) info))
1959 (tags (and (plist-get info :with-tags)
1960 (org-export-get-tags inlinetask info))))
1961 (funcall (plist-get info :odt-format-inlinetask-function)
1962 todo todo-type priority text tags contents)))
1964 (defun org-odt-format-inlinetask-default-function
1965 (todo todo-type priority name tags contents)
1966 "Default format function for a inlinetasks.
1967 See `org-odt-format-inlinetask-function' for details."
1968 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1969 "Text_20_body"
1970 (org-odt--textbox
1971 (concat
1972 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1973 "OrgInlineTaskHeading"
1974 (org-odt-format-headline-default-function
1975 todo todo-type priority name tags))
1976 contents)
1977 nil nil "OrgInlineTaskFrame" " style:rel-width=\"100%\"")))
1979 ;;;; Italic
1981 (defun org-odt-italic (italic contents info)
1982 "Transcode ITALIC from Org to ODT.
1983 CONTENTS is the text with italic markup. INFO is a plist holding
1984 contextual information."
1985 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1986 "Emphasis" contents))
1989 ;;;; Item
1991 (defun org-odt-item (item contents info)
1992 "Transcode an ITEM element from Org to ODT.
1993 CONTENTS holds the contents of the item. INFO is a plist holding
1994 contextual information."
1995 (let* ((plain-list (org-export-get-parent item))
1996 (type (org-element-property :type plain-list))
1997 (counter (org-element-property :counter item))
1998 (tag (let ((tag (org-element-property :tag item)))
1999 (and tag
2000 (concat (org-odt--checkbox item)
2001 (org-export-data tag info))))))
2002 (case type
2003 ((ordered unordered descriptive-1 descriptive-2)
2004 (format "\n<text:list-item>\n%s\n%s"
2005 contents
2006 (let* ((--element-has-a-table-p
2007 (function
2008 (lambda (element info)
2009 (loop for el in (org-element-contents element)
2010 thereis (eq (org-element-type el) 'table))))))
2011 (cond
2012 ((funcall --element-has-a-table-p item info)
2013 "</text:list-header>")
2014 (t "</text:list-item>")))))
2015 (t (error "Unknown list type: %S" type)))))
2017 ;;;; Keyword
2019 (defun org-odt-keyword (keyword contents info)
2020 "Transcode a KEYWORD element from Org to ODT.
2021 CONTENTS is nil. INFO is a plist holding contextual
2022 information."
2023 (let ((key (org-element-property :key keyword))
2024 (value (org-element-property :value keyword)))
2025 (cond
2026 ((string= key "ODT") value)
2027 ((string= key "INDEX")
2028 ;; FIXME
2029 (ignore))
2030 ((string= key "TOC")
2031 (let ((case-fold-search t))
2032 (cond
2033 ((org-string-match-p "\\<headlines\\>" value)
2034 (let ((depth (or (and (string-match "\\<[0-9]+\\>" value)
2035 (string-to-number (match-string 0 value)))
2036 (plist-get info :headline-levels)))
2037 (localp (org-string-match-p "\\<local\\>" value)))
2038 (org-odt-toc depth info (and localp keyword))))
2039 ((org-string-match-p "tables\\|figures\\|listings" value)
2040 ;; FIXME
2041 (ignore))))))))
2044 ;;;; Latex Environment
2047 ;; (eval-after-load 'ox-odt '(ad-deactivate 'org-format-latex-as-mathml))
2048 ;; (defadvice org-format-latex-as-mathml ; FIXME
2049 ;; (after org-odt-protect-latex-fragment activate)
2050 ;; "Encode LaTeX fragment as XML.
2051 ;; Do this when translation to MathML fails."
2052 ;; (unless (> (length ad-return-value) 0)
2053 ;; (setq ad-return-value (org-odt--encode-plain-text (ad-get-arg 0)))))
2055 (defun org-odt-latex-environment (latex-environment contents info)
2056 "Transcode a LATEX-ENVIRONMENT element from Org to ODT.
2057 CONTENTS is nil. INFO is a plist holding contextual information."
2058 (let* ((latex-frag (org-remove-indentation
2059 (org-element-property :value latex-environment))))
2060 (org-odt-do-format-code latex-frag info)))
2063 ;;;; Latex Fragment
2065 ;; (when latex-frag ; FIXME
2066 ;; (setq href (org-propertize href :title "LaTeX Fragment"
2067 ;; :description latex-frag)))
2068 ;; handle verbatim
2069 ;; provide descriptions
2071 (defun org-odt-latex-fragment (latex-fragment contents info)
2072 "Transcode a LATEX-FRAGMENT object from Org to ODT.
2073 CONTENTS is nil. INFO is a plist holding contextual information."
2074 (let* ((latex-frag (org-element-property :value latex-fragment))
2075 (processing-type (plist-get info :with-latex)))
2076 (format "<text:span text:style-name=\"%s\">%s</text:span>"
2077 "OrgCode" (org-odt--encode-plain-text latex-frag t))))
2080 ;;;; Line Break
2082 (defun org-odt-line-break (line-break contents info)
2083 "Transcode a LINE-BREAK object from Org to ODT.
2084 CONTENTS is nil. INFO is a plist holding contextual information."
2085 "<text:line-break/>")
2088 ;;;; Link
2090 ;;;; Links :: Label references
2092 (defun org-odt--enumerate (element info &optional predicate n)
2093 (when predicate (assert (funcall predicate element info)))
2094 (let* ((--numbered-parent-headline-at-<=-n
2095 (function
2096 (lambda (element n info)
2097 (loop for x in (org-element-lineage element)
2098 thereis (and (eq (org-element-type x) 'headline)
2099 (<= (org-export-get-relative-level x info) n)
2100 (org-export-numbered-headline-p x info)
2101 x)))))
2102 (--enumerate
2103 (function
2104 (lambda (element scope info &optional predicate)
2105 (let ((counter 0))
2106 (org-element-map (or scope (plist-get info :parse-tree))
2107 (org-element-type element)
2108 (lambda (el)
2109 (and (or (not predicate) (funcall predicate el info))
2110 (incf counter)
2111 (eq element el)
2112 counter))
2113 info 'first-match)))))
2114 (scope (funcall --numbered-parent-headline-at-<=-n
2115 element
2116 (or n (plist-get info :odt-display-outline-level))
2117 info))
2118 (ordinal (funcall --enumerate element scope info predicate))
2119 (tag
2120 (concat
2121 ;; Section number.
2122 (and scope
2123 (mapconcat 'number-to-string
2124 (org-export-get-headline-number scope info) "."))
2125 ;; Separator.
2126 (and scope ".")
2127 ;; Ordinal.
2128 (number-to-string ordinal))))
2129 tag))
2131 (defun org-odt-format-label (element info op)
2132 "Return a label for ELEMENT.
2134 ELEMENT is a `link', `table', `src-block' or `paragraph' type
2135 element. INFO is a plist used as a communication channel. OP is
2136 either `definition' or `reference', depending on the purpose of
2137 the generated string.
2139 Return value is a string if OP is set to `reference' or a cons
2140 cell like CAPTION . SHORT-CAPTION) where CAPTION and
2141 SHORT-CAPTION are strings."
2142 (assert (memq (org-element-type element) '(link table src-block paragraph)))
2143 (let* ((caption-from
2144 (case (org-element-type element)
2145 (link (org-export-get-parent-element element))
2146 (t element)))
2147 ;; Get label and caption.
2148 (label (org-element-property :name caption-from))
2149 (caption (org-export-get-caption caption-from))
2150 (caption (and caption (org-export-data caption info)))
2151 ;; FIXME: We don't use short-caption for now
2152 (short-caption nil))
2153 (when (or label caption)
2154 (let* ((default-category
2155 (case (org-element-type element)
2156 (table "__Table__")
2157 (src-block "__Listing__")
2158 ((link paragraph)
2159 (cond
2160 ((org-odt--enumerable-latex-image-p element info)
2161 "__DvipngImage__")
2162 ((org-odt--enumerable-image-p element info)
2163 "__Figure__")
2164 ((org-odt--enumerable-formula-p element info)
2165 "__MathFormula__")
2166 (t (error "Don't know how to format label for link: %S"
2167 element))))
2168 (t (error "Don't know how to format label for element type: %s"
2169 (org-element-type element)))))
2170 seqno)
2171 (assert default-category)
2172 (destructuring-bind (counter label-style category predicate)
2173 (assoc-default default-category org-odt-category-map-alist)
2174 ;; Compute sequence number of the element.
2175 (setq seqno (org-odt--enumerate element info predicate))
2176 ;; Localize category string.
2177 (setq category (org-export-translate category :utf-8 info))
2178 (case op
2179 ;; Case 1: Handle Label definition.
2180 (definition
2181 ;; Assign an internal label, if user has not provided one
2182 (setq label (org-export-solidify-link-text
2183 (or label (format "%s-%s" default-category seqno))))
2184 (cons
2185 (concat
2186 ;; Sneak in a bookmark. The bookmark is used when the
2187 ;; labeled element is referenced with a link that
2188 ;; provides its own description.
2189 (format "\n<text:bookmark text:name=\"%s\"/>" label)
2190 ;; Label definition: Typically formatted as below:
2191 ;; CATEGORY SEQ-NO: LONG CAPTION
2192 ;; with translation for correct punctuation.
2193 (format-spec
2194 (org-export-translate
2195 (cadr (assoc-string label-style org-odt-label-styles t))
2196 :utf-8 info)
2197 `((?e . ,category)
2198 (?n . ,(format
2199 "<text:sequence text:ref-name=\"%s\" text:name=\"%s\" text:formula=\"ooow:%s+1\" style:num-format=\"1\">%s</text:sequence>"
2200 label counter counter seqno))
2201 (?c . ,(or caption "")))))
2202 short-caption))
2203 ;; Case 2: Handle Label reference.
2204 (reference
2205 (assert label)
2206 (setq label (org-export-solidify-link-text label))
2207 (let* ((fmt (cddr (assoc-string label-style org-odt-label-styles t)))
2208 (fmt1 (car fmt))
2209 (fmt2 (cadr fmt)))
2210 (format "<text:sequence-ref text:reference-format=\"%s\" text:ref-name=\"%s\">%s</text:sequence-ref>"
2211 fmt1 label (format-spec fmt2 `((?e . ,category)
2212 (?n . ,seqno))))))
2213 (t (error "Unknown %S on label" op))))))))
2216 ;;;; Links :: Inline Images
2218 (defun org-odt--copy-image-file (path)
2219 "Returns the internal name of the file"
2220 (let* ((image-type (file-name-extension path))
2221 (media-type (format "image/%s" image-type))
2222 (target-dir "Images/")
2223 (target-file
2224 (format "%s%04d.%s" target-dir
2225 (incf org-odt-embedded-images-count) image-type)))
2226 (message "Embedding %s as %s..."
2227 (substring-no-properties path) target-file)
2229 (when (= 1 org-odt-embedded-images-count)
2230 (make-directory (concat org-odt-zip-dir target-dir))
2231 (org-odt-create-manifest-file-entry "" target-dir))
2233 (copy-file path (concat org-odt-zip-dir target-file) 'overwrite)
2234 (org-odt-create-manifest-file-entry media-type target-file)
2235 target-file))
2237 (defun org-odt--image-size
2238 (file info &optional user-width user-height scale dpi embed-as)
2239 (let* ((--pixels-to-cms
2240 (function (lambda (pixels dpi)
2241 (let ((cms-per-inch 2.54)
2242 (inches (/ pixels dpi)))
2243 (* cms-per-inch inches)))))
2244 (--size-in-cms
2245 (function
2246 (lambda (size-in-pixels dpi)
2247 (and size-in-pixels
2248 (cons (funcall --pixels-to-cms (car size-in-pixels) dpi)
2249 (funcall --pixels-to-cms (cdr size-in-pixels) dpi))))))
2250 (dpi (or dpi (plist-get info :odt-pixels-per-inch)))
2251 (anchor-type (or embed-as "paragraph"))
2252 (user-width (and (not scale) user-width))
2253 (user-height (and (not scale) user-height))
2254 (size
2255 (and
2256 (not (and user-height user-width))
2258 ;; Use Imagemagick.
2259 (and (executable-find "identify")
2260 (let ((size-in-pixels
2261 (let ((dim (shell-command-to-string
2262 (format "identify -format \"%%w:%%h\" \"%s\""
2263 file))))
2264 (when (string-match "\\([0-9]+\\):\\([0-9]+\\)" dim)
2265 (cons (string-to-number (match-string 1 dim))
2266 (string-to-number (match-string 2 dim)))))))
2267 (funcall --size-in-cms size-in-pixels dpi)))
2268 ;; Use Emacs.
2269 (let ((size-in-pixels
2270 (ignore-errors ; Emacs could be in batch mode
2271 (clear-image-cache)
2272 (image-size (create-image file) 'pixels))))
2273 (funcall --size-in-cms size-in-pixels dpi))
2274 ;; Use hard-coded values.
2275 (cdr (assoc-string anchor-type
2276 org-odt-default-image-sizes-alist))
2277 ;; Error out.
2278 (error "Cannot determine image size, aborting"))))
2279 (width (car size)) (height (cdr size)))
2280 (cond
2281 (scale
2282 (setq width (* width scale) height (* height scale)))
2283 ((and user-height user-width)
2284 (setq width user-width height user-height))
2285 (user-height
2286 (setq width (* user-height (/ width height)) height user-height))
2287 (user-width
2288 (setq height (* user-width (/ height width)) width user-width))
2289 (t (ignore)))
2290 ;; ensure that an embedded image fits comfortably within a page
2291 (let ((max-width (car org-odt-max-image-size))
2292 (max-height (cdr org-odt-max-image-size)))
2293 (when (or (> width max-width) (> height max-height))
2294 (let* ((scale1 (/ max-width width))
2295 (scale2 (/ max-height height))
2296 (scale (min scale1 scale2)))
2297 (setq width (* scale width) height (* scale height)))))
2298 (cons width height)))
2300 (defun org-odt-link--inline-image (element info)
2301 "Return ODT code for an inline image.
2302 LINK is the link pointing to the inline image. INFO is a plist
2303 used as a communication channel."
2304 (assert (eq (org-element-type element) 'link))
2305 (let* ((src (let* ((type (org-element-property :type element))
2306 (raw-path (org-element-property :path element)))
2307 (cond ((member type '("http" "https"))
2308 (concat type ":" raw-path))
2309 ((file-name-absolute-p raw-path)
2310 (expand-file-name raw-path))
2311 (t raw-path))))
2312 (src-expanded (if (file-name-absolute-p src) src
2313 (expand-file-name src (file-name-directory
2314 (plist-get info :input-file)))))
2315 (href (format
2316 "\n<draw:image xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>"
2317 (org-odt--copy-image-file src-expanded)))
2318 ;; Extract attributes from #+ATTR_ODT line.
2319 (attr-from (case (org-element-type element)
2320 (link (org-export-get-parent-element element))
2321 (t element)))
2322 ;; Convert attributes to a plist.
2323 (attr-plist (org-export-read-attribute :attr_odt attr-from))
2324 ;; Handle `:anchor', `:style' and `:attributes' properties.
2325 (user-frame-anchor
2326 (car (assoc-string (plist-get attr-plist :anchor)
2327 '(("as-char") ("paragraph") ("page")) t)))
2328 (user-frame-style
2329 (and user-frame-anchor (plist-get attr-plist :style)))
2330 (user-frame-attrs
2331 (and user-frame-anchor (plist-get attr-plist :attributes)))
2332 (user-frame-params
2333 (list user-frame-style user-frame-attrs user-frame-anchor))
2334 ;; (embed-as (or embed-as user-frame-anchor "paragraph"))
2336 ;; Handle `:width', `:height' and `:scale' properties. Read
2337 ;; them as numbers since we need them for computations.
2338 (size (org-odt--image-size
2339 src-expanded info
2340 (let ((width (plist-get attr-plist :width)))
2341 (and width (read width)))
2342 (let ((length (plist-get attr-plist :length)))
2343 (and length (read length)))
2344 (let ((scale (plist-get attr-plist :scale)))
2345 (and scale (read scale)))
2346 nil ; embed-as
2347 "paragraph" ; FIXME
2349 (width (car size)) (height (cdr size))
2350 (standalone-link-p (org-odt--standalone-link-p element info))
2351 (embed-as (if standalone-link-p "paragraph" "as-char"))
2352 (captions (org-odt-format-label element info 'definition))
2353 (caption (car captions)) (short-caption (cdr captions))
2354 (entity (concat (and caption "Captioned") embed-as "Image"))
2355 ;; Check if this link was created by LaTeX-to-PNG converter.
2356 (replaces (org-element-property
2357 :replaces (if (not standalone-link-p) element
2358 (org-export-get-parent-element element))))
2359 ;; If yes, note down the type of the element - LaTeX Fragment
2360 ;; or LaTeX environment. It will go in to frame title.
2361 (title (and replaces (capitalize
2362 (symbol-name (org-element-type replaces)))))
2364 ;; If yes, note down its contents. It will go in to frame
2365 ;; description. This quite useful for debugging.
2366 (desc (and replaces (org-element-property :value replaces))))
2367 (org-odt--render-image/formula entity href width height
2368 captions user-frame-params title desc)))
2371 ;;;; Links :: Math formula
2373 (defun org-odt-link--inline-formula (element info)
2374 (let* ((src (let* ((type (org-element-property :type element))
2375 (raw-path (org-element-property :path element)))
2376 (cond
2377 ((file-name-absolute-p raw-path)
2378 (expand-file-name raw-path))
2379 (t raw-path))))
2380 (src-expanded (if (file-name-absolute-p src) src
2381 (expand-file-name src (file-name-directory
2382 (plist-get info :input-file)))))
2383 (href
2384 (format
2385 "\n<draw:object %s xlink:href=\"%s\" xlink:type=\"simple\"/>"
2386 " xlink:show=\"embed\" xlink:actuate=\"onLoad\""
2387 (file-name-directory (org-odt--copy-formula-file src-expanded))))
2388 (standalone-link-p (org-odt--standalone-link-p element info))
2389 (embed-as (if standalone-link-p 'paragraph 'character))
2390 (captions (org-odt-format-label element info 'definition))
2391 (caption (car captions)) (short-caption (cdr captions))
2392 ;; Check if this link was created by LaTeX-to-MathML
2393 ;; converter.
2394 (replaces (org-element-property
2395 :replaces (if (not standalone-link-p) element
2396 (org-export-get-parent-element element))))
2397 ;; If yes, note down the type of the element - LaTeX Fragment
2398 ;; or LaTeX environment. It will go in to frame title.
2399 (title (and replaces (capitalize
2400 (symbol-name (org-element-type replaces)))))
2402 ;; If yes, note down its contents. It will go in to frame
2403 ;; description. This quite useful for debugging.
2404 (desc (and replaces (org-element-property :value replaces)))
2405 width height)
2406 (cond
2407 ((eq embed-as 'character)
2408 (org-odt--render-image/formula "InlineFormula" href width height
2409 nil nil title desc))
2411 (let* ((equation (org-odt--render-image/formula
2412 "CaptionedDisplayFormula" href width height
2413 captions nil title desc))
2414 (label
2415 (let* ((org-odt-category-map-alist
2416 '(("__MathFormula__" "Text" "math-label" "Equation"
2417 org-odt--enumerable-formula-p))))
2418 (car (org-odt-format-label element info 'definition)))))
2419 (concat equation "<text:tab/>" label))))))
2421 (defun org-odt--copy-formula-file (src-file)
2422 "Returns the internal name of the file"
2423 (let* ((target-dir (format "Formula-%04d/"
2424 (incf org-odt-embedded-formulas-count)))
2425 (target-file (concat target-dir "content.xml")))
2426 ;; Create a directory for holding formula file. Also enter it in
2427 ;; to manifest.
2428 (make-directory (concat org-odt-zip-dir target-dir))
2429 (org-odt-create-manifest-file-entry
2430 "application/vnd.oasis.opendocument.formula" target-dir "1.2")
2431 ;; Copy over the formula file from user directory to zip
2432 ;; directory.
2433 (message "Embedding %s as %s..." src-file target-file)
2434 (let ((case-fold-search nil))
2435 (cond
2436 ;; Case 1: Mathml.
2437 ((string-match "\\.\\(mathml\\|mml\\)\\'" src-file)
2438 (copy-file src-file (concat org-odt-zip-dir target-file) 'overwrite))
2439 ;; Case 2: OpenDocument formula.
2440 ((string-match "\\.odf\\'" src-file)
2441 (org-odt--zip-extract src-file "content.xml"
2442 (concat org-odt-zip-dir target-dir)))
2443 (t (error "%s is not a formula file" src-file))))
2444 ;; Enter the formula file in to manifest.
2445 (org-odt-create-manifest-file-entry "text/xml" target-file)
2446 target-file))
2448 ;;;; Targets
2450 (defun org-odt--render-image/formula (cfg-key href width height &optional
2451 captions user-frame-params
2452 &rest title-and-desc)
2453 (let* ((frame-cfg-alist
2454 ;; Each element of this alist is of the form (CFG-HANDLE
2455 ;; INNER-FRAME-PARAMS OUTER-FRAME-PARAMS).
2457 ;; CFG-HANDLE is the key to the alist.
2459 ;; INNER-FRAME-PARAMS and OUTER-FRAME-PARAMS specify the
2460 ;; frame params for INNER-FRAME and OUTER-FRAME
2461 ;; respectively. See below.
2463 ;; Configurations that are meant to be applied to
2464 ;; non-captioned image/formula specifies no
2465 ;; OUTER-FRAME-PARAMS.
2467 ;; TERMINOLOGY
2468 ;; ===========
2469 ;; INNER-FRAME :: Frame that directly surrounds an
2470 ;; image/formula.
2472 ;; OUTER-FRAME :: Frame that encloses the INNER-FRAME. This
2473 ;; frame also contains the caption, if any.
2475 ;; FRAME-PARAMS :: List of the form (FRAME-STYLE-NAME
2476 ;; FRAME-ATTRIBUTES FRAME-ANCHOR). Note
2477 ;; that these are the last three arguments
2478 ;; to `org-odt--frame'.
2480 ;; Note that an un-captioned image/formula requires just an
2481 ;; INNER-FRAME, while a captioned image/formula requires
2482 ;; both an INNER and an OUTER-FRAME.
2483 '(("As-CharImage" ("OrgInlineImage" nil "as-char"))
2484 ("ParagraphImage" ("OrgDisplayImage" nil "paragraph"))
2485 ("PageImage" ("OrgPageImage" nil "page"))
2486 ("CaptionedAs-CharImage"
2487 ("OrgCaptionedImage"
2488 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
2489 ("OrgInlineImage" nil "as-char"))
2490 ("CaptionedParagraphImage"
2491 ("OrgCaptionedImage"
2492 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
2493 ("OrgImageCaptionFrame" nil "paragraph"))
2494 ("CaptionedPageImage"
2495 ("OrgCaptionedImage"
2496 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
2497 ("OrgPageImageCaptionFrame" nil "page"))
2498 ("InlineFormula" ("OrgInlineFormula" nil "as-char"))
2499 ("DisplayFormula" ("OrgDisplayFormula" nil "as-char"))
2500 ("CaptionedDisplayFormula"
2501 ("OrgCaptionedFormula" nil "paragraph")
2502 ("OrgFormulaCaptionFrame" nil "paragraph"))))
2503 (caption (car captions)) (short-caption (cdr captions))
2504 ;; Retrieve inner and outer frame params, from configuration.
2505 (frame-cfg (assoc-string cfg-key frame-cfg-alist t))
2506 (inner (nth 1 frame-cfg))
2507 (outer (nth 2 frame-cfg))
2508 ;; User-specified frame params (from #+ATTR_ODT spec)
2509 (user user-frame-params)
2510 (--merge-frame-params (function
2511 (lambda (default user)
2512 "Merge default and user frame params."
2513 (if (not user) default
2514 (assert (= (length default) 3))
2515 (assert (= (length user) 3))
2516 (loop for u in user
2517 for d in default
2518 collect (or u d)))))))
2519 (cond
2520 ;; Case 1: Image/Formula has no caption.
2521 ;; There is only one frame, one that surrounds the image
2522 ;; or formula.
2523 ((not caption)
2524 ;; Merge user frame params with that from configuration.
2525 (setq inner (funcall --merge-frame-params inner user))
2526 (apply 'org-odt--frame href width height
2527 (append inner title-and-desc)))
2528 ;; Case 2: Image/Formula is captioned or labeled.
2529 ;; There are two frames: The inner one surrounds the
2530 ;; image or formula. The outer one contains the
2531 ;; caption/sequence number.
2533 ;; Merge user frame params with outer frame params.
2534 (setq outer (funcall --merge-frame-params outer user))
2535 ;; Short caption, if specified, goes as part of inner frame.
2536 (setq inner (let ((frame-params (copy-sequence inner)))
2537 (setcar (cdr frame-params)
2538 (concat
2539 (cadr frame-params)
2540 (when short-caption
2541 (format " draw:name=\"%s\" " short-caption))))
2542 frame-params))
2543 (apply 'org-odt--textbox
2544 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
2545 "Illustration"
2546 (concat
2547 (apply 'org-odt--frame href width height
2548 (append inner title-and-desc))
2549 caption))
2550 width height outer)))))
2552 (defun org-odt--enumerable-p (element info)
2553 ;; Element should have a caption or label.
2554 (or (org-element-property :caption element)
2555 (org-element-property :name element)))
2557 (defun org-odt--enumerable-image-p (element info)
2558 (org-odt--standalone-link-p
2559 element info
2560 ;; Paragraph should have a caption or label. It SHOULD NOT be a
2561 ;; replacement element. (i.e., It SHOULD NOT be a result of LaTeX
2562 ;; processing.)
2563 (lambda (p)
2564 (and (not (org-element-property :replaces p))
2565 (or (org-element-property :caption p)
2566 (org-element-property :name p))))
2567 ;; Link should point to an image file.
2568 (lambda (l)
2569 (assert (eq (org-element-type l) 'link))
2570 (org-export-inline-image-p l (plist-get info :odt-inline-image-rules)))))
2572 (defun org-odt--enumerable-latex-image-p (element info)
2573 (org-odt--standalone-link-p
2574 element info
2575 ;; Paragraph should have a caption or label. It SHOULD also be a
2576 ;; replacement element. (i.e., It SHOULD be a result of LaTeX
2577 ;; processing.)
2578 (lambda (p)
2579 (and (org-element-property :replaces p)
2580 (or (org-element-property :caption p)
2581 (org-element-property :name p))))
2582 ;; Link should point to an image file.
2583 (lambda (l)
2584 (assert (eq (org-element-type l) 'link))
2585 (org-export-inline-image-p l (plist-get info :odt-inline-image-rules)))))
2587 (defun org-odt--enumerable-formula-p (element info)
2588 (org-odt--standalone-link-p
2589 element info
2590 ;; Paragraph should have a caption or label.
2591 (lambda (p)
2592 (or (org-element-property :caption p)
2593 (org-element-property :name p)))
2594 ;; Link should point to a MathML or ODF file.
2595 (lambda (l)
2596 (assert (eq (org-element-type l) 'link))
2597 (org-export-inline-image-p l (plist-get info :odt-inline-formula-rules)))))
2599 (defun org-odt--standalone-link-p (element info &optional
2600 paragraph-predicate
2601 link-predicate)
2602 "Test if ELEMENT is a standalone link for the purpose ODT export.
2603 INFO is a plist holding contextual information.
2605 Return non-nil, if ELEMENT is of type paragraph satisfying
2606 PARAGRAPH-PREDICATE and its sole content, save for whitespaces,
2607 is a link that satisfies LINK-PREDICATE.
2609 Return non-nil, if ELEMENT is of type link satisfying
2610 LINK-PREDICATE and its containing paragraph satisfies
2611 PARAGRAPH-PREDICATE in addition to having no other content save for
2612 leading and trailing whitespaces.
2614 Return nil, otherwise."
2615 (let ((p (case (org-element-type element)
2616 (paragraph element)
2617 (link (and (or (not link-predicate)
2618 (funcall link-predicate element))
2619 (org-export-get-parent element)))
2620 (t nil))))
2621 (when (and p (eq (org-element-type p) 'paragraph))
2622 (when (or (not paragraph-predicate)
2623 (funcall paragraph-predicate p))
2624 (let ((contents (org-element-contents p)))
2625 (loop for x in contents
2626 with inline-image-count = 0
2627 always (case (org-element-type x)
2628 (plain-text
2629 (not (org-string-nw-p x)))
2630 (link
2631 (and (or (not link-predicate)
2632 (funcall link-predicate x))
2633 (= (incf inline-image-count) 1)))
2634 (t nil))))))))
2636 (defun org-odt-link--infer-description (destination info)
2637 ;; DESTINATION is a headline or an element (like paragraph,
2638 ;; verse-block etc) to which a "#+NAME: label" can be attached.
2640 ;; Note that labels that are attached to captioned entities - inline
2641 ;; images, math formulae and tables - get resolved as part of
2642 ;; `org-odt-format-label' and `org-odt--enumerate'.
2644 ;; Create a cross-reference to DESTINATION but make best-efforts to
2645 ;; create a *meaningful* description. Check item numbers, section
2646 ;; number and section title in that order.
2648 ;; NOTE: Counterpart of `org-export-get-ordinal'.
2649 ;; FIXME: Handle footnote-definition footnote-reference?
2650 (let* ((genealogy (org-element-lineage destination))
2651 (data (reverse genealogy))
2652 (label (case (org-element-type destination)
2653 (headline (org-export-get-headline-id destination info))
2654 (target
2655 (org-element-property :value destination))
2656 (t (error "FIXME: Resolve %S" destination)))))
2658 (let* ( ;; Locate top-level list.
2659 (top-level-list
2660 (loop for x on data
2661 when (eq (org-element-type (car x)) 'plain-list)
2662 return x))
2663 ;; Get list item nos.
2664 (item-numbers
2665 (loop for (plain-list item . rest) on top-level-list by #'cddr
2666 until (not (eq (org-element-type plain-list) 'plain-list))
2667 collect (when (eq (org-element-property :type
2668 plain-list)
2669 'ordered)
2670 (1+ (length (org-export-get-previous-element
2671 item info t))))))
2672 ;; Locate top-most listified headline.
2673 (listified-headlines
2674 (loop for x on data
2675 when (and (eq (org-element-type (car x)) 'headline)
2676 (org-export-low-level-p (car x) info))
2677 return x))
2678 ;; Get listified headline numbers.
2679 (listified-headline-nos
2680 (loop for el in listified-headlines
2681 when (eq (org-element-type el) 'headline)
2682 collect (when (org-export-numbered-headline-p el info)
2683 (1+ (length (org-export-get-previous-element
2684 el info t)))))))
2685 ;; Combine item numbers from both the listified headlines and
2686 ;; regular list items.
2688 ;; Case 1: Check if all the parents of list item are numbered.
2689 ;; If yes, link to the item proper.
2690 (let ((item-numbers (append listified-headline-nos item-numbers)))
2691 (when (and item-numbers (not (memq nil item-numbers)))
2692 (format "<text:bookmark-ref text:reference-format=\"number-all-superior\" text:ref-name=\"%s\">%s</text:bookmark-ref>"
2693 (org-export-solidify-link-text label)
2694 (mapconcat (lambda (n) (if (not n) " "
2695 (concat (number-to-string n) ".")))
2696 item-numbers "")))))
2697 ;; Case 2: Locate a regular and numbered headline in the
2698 ;; hierarchy. Display its section number.
2699 (let ((headline
2700 (and
2701 ;; Test if destination is a numbered headline.
2702 (org-export-numbered-headline-p destination info)
2703 (loop for el in (cons destination genealogy)
2704 when (and (eq (org-element-type el) 'headline)
2705 (not (org-export-low-level-p el info))
2706 (org-export-numbered-headline-p el info))
2707 return el))))
2708 ;; We found one.
2709 (when headline
2710 (format "<text:bookmark-ref text:reference-format=\"chapter\" text:ref-name=\"OrgXref.%s\">%s</text:bookmark-ref>"
2711 (org-export-solidify-link-text label)
2712 (mapconcat 'number-to-string (org-export-get-headline-number
2713 headline info) "."))))
2714 ;; Case 4: Locate a regular headline in the hierarchy. Display
2715 ;; its title.
2716 (let ((headline (loop for el in (cons destination genealogy)
2717 when (and (eq (org-element-type el) 'headline)
2718 (not (org-export-low-level-p el info)))
2719 return el)))
2720 ;; We found one.
2721 (when headline
2722 (format "<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"OrgXref.%s\">%s</text:bookmark-ref>"
2723 (org-export-solidify-link-text label)
2724 (let ((title (org-element-property :title headline)))
2725 (org-export-data title info)))))
2726 (error "FIXME?"))))
2728 (defun org-odt-link (link desc info)
2729 "Transcode a LINK object from Org to ODT.
2731 DESC is the description part of the link, or the empty string.
2732 INFO is a plist holding contextual information. See
2733 `org-export-data'."
2734 (let* ((type (org-element-property :type link))
2735 (raw-path (org-element-property :path link))
2736 ;; Ensure DESC really exists, or set it to nil.
2737 (desc (and (not (string= desc "")) desc))
2738 (imagep (org-export-inline-image-p
2739 link (plist-get info :odt-inline-image-rules)))
2740 (path (cond
2741 ((member type '("http" "https" "ftp" "mailto"))
2742 (concat type ":" raw-path))
2743 ((and (string= type "file") (file-name-absolute-p raw-path))
2744 (concat "file:" raw-path))
2745 (t raw-path)))
2746 ;; Convert & to &amp; for correct XML representation
2747 (path (replace-regexp-in-string "&" "&amp;" path)))
2748 (cond
2749 ;; Link type is handled by a special function.
2750 ((org-export-custom-protocol-maybe link desc 'odt))
2751 ;; Image file.
2752 ((and (not desc) (org-export-inline-image-p
2753 link (plist-get info :odt-inline-image-rules)))
2754 (org-odt-link--inline-image link info))
2755 ;; Formula file.
2756 ((and (not desc) (org-export-inline-image-p
2757 link (plist-get info :odt-inline-formula-rules)))
2758 (org-odt-link--inline-formula link info))
2759 ;; Radio target: Transcode target's contents and use them as
2760 ;; link's description.
2761 ((string= type "radio")
2762 (let ((destination (org-export-resolve-radio-link link info)))
2763 (if (not destination) desc
2764 (format
2765 "<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"OrgXref.%s\">%s</text:bookmark-ref>"
2766 (org-export-solidify-link-text
2767 (org-element-property :value destination))
2768 desc))))
2769 ;; Links pointing to a headline: Find destination and build
2770 ;; appropriate referencing command.
2771 ((member type '("custom-id" "fuzzy" "id"))
2772 (let ((destination (if (string= type "fuzzy")
2773 (org-export-resolve-fuzzy-link link info)
2774 (org-export-resolve-id-link link info))))
2775 (case (org-element-type destination)
2776 ;; Case 1: Fuzzy link points nowhere.
2777 ('nil
2778 (format "<text:span text:style-name=\"%s\">%s</text:span>"
2779 "Emphasis"
2780 (or desc
2781 (org-export-data (org-element-property :raw-link link)
2782 info))))
2783 ;; Case 2: Fuzzy link points to a headline.
2784 (headline
2785 ;; If there's a description, create a hyperlink.
2786 ;; Otherwise, try to provide a meaningful description.
2787 (if (not desc) (org-odt-link--infer-description destination info)
2788 (let ((label (or (and (string= type "custom-id")
2789 (org-element-property :CUSTOM_ID destination))
2790 (org-export-get-headline-id destination info))))
2791 (format
2792 "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
2793 label desc))))
2794 ;; Case 3: Fuzzy link points to a target.
2795 (target
2796 ;; If there's a description, create a hyperlink.
2797 ;; Otherwise, try to provide a meaningful description.
2798 (let ((label (org-element-property :value destination)))
2799 (format "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
2800 (org-export-solidify-link-text label)
2801 (or desc (org-export-get-ordinal destination info)))))
2802 ;; Case 4: Fuzzy link points to some element (e.g., an
2803 ;; inline image, a math formula or a table).
2804 (otherwise
2805 (let ((label-reference
2806 (ignore-errors (org-odt-format-label
2807 destination info 'reference))))
2808 (cond ((not label-reference)
2809 (org-odt-link--infer-description destination info))
2810 ;; LINK has no description. Create
2811 ;; a cross-reference showing entity's sequence
2812 ;; number.
2813 ((not desc) label-reference)
2814 ;; LINK has description. Insert a hyperlink with
2815 ;; user-provided description.
2817 (let ((label (org-element-property :name destination)))
2818 (format "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
2819 (org-export-solidify-link-text label)
2820 desc)))))))))
2821 ;; Coderef: replace link with the reference name or the
2822 ;; equivalent line number.
2823 ((string= type "coderef")
2824 (let* ((line-no (format "%d" (org-export-resolve-coderef path info)))
2825 (href (concat "coderef-" path)))
2826 (format
2827 (org-export-get-coderef-format path desc)
2828 (format
2829 "<text:bookmark-ref text:reference-format=\"number\" text:ref-name=\"OrgXref.%s\">%s</text:bookmark-ref>"
2830 href line-no))))
2831 ;; External link with a description part.
2832 ((and path desc)
2833 (let ((link-contents (org-element-contents link)))
2834 ;; Check if description is a link to an inline image.
2835 (if (and (not (cdr link-contents))
2836 (let ((desc-element (car link-contents)))
2837 (and (eq (org-element-type desc-element) 'link)
2838 (org-export-inline-image-p
2839 desc-element
2840 (plist-get info :odt-inline-image-rules)))))
2841 ;; Format link as a clickable image.
2842 (format "\n<draw:a xlink:type=\"simple\" xlink:href=\"%s\">\n%s\n</draw:a>"
2843 path desc)
2844 ;; Otherwise, format it as a regular link.
2845 (format "<text:a xlink:type=\"simple\" xlink:href=\"%s\">%s</text:a>"
2846 path desc))))
2847 ;; External link without a description part.
2848 (path
2849 (format "<text:a xlink:type=\"simple\" xlink:href=\"%s\">%s</text:a>"
2850 path path))
2851 ;; No path, only description. Try to do something useful.
2852 (t (format "<text:span text:style-name=\"%s\">%s</text:span>"
2853 "Emphasis" desc)))))
2856 ;;;; Node Property
2858 (defun org-odt-node-property (node-property contents info)
2859 "Transcode a NODE-PROPERTY element from Org to ODT.
2860 CONTENTS is nil. INFO is a plist holding contextual
2861 information."
2862 (org-odt--encode-plain-text
2863 (format "%s:%s"
2864 (org-element-property :key node-property)
2865 (let ((value (org-element-property :value node-property)))
2866 (if value (concat " " value) "")))))
2868 ;;;; Paragraph
2870 (defun org-odt--paragraph-style (paragraph)
2871 "Return style of PARAGRAPH.
2872 Style is a symbol among `quoted', `centered' and nil."
2873 (let ((up paragraph))
2874 (while (and (setq up (org-element-property :parent up))
2875 (not (memq (org-element-type up)
2876 '(center-block quote-block section)))))
2877 (case (org-element-type up)
2878 (center-block 'centered)
2879 (quote-block 'quoted))))
2881 (defun org-odt--format-paragraph (paragraph contents info default center quote)
2882 "Format paragraph according to given styles.
2883 PARAGRAPH is a paragraph type element. CONTENTS is the
2884 transcoded contents of that paragraph, as a string. INFO is
2885 a plist used as a communication channel. DEFAULT, CENTER and
2886 QUOTE are, respectively, style to use when paragraph belongs to
2887 no special environment, a center block, or a quote block."
2888 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
2889 (case (org-odt--paragraph-style paragraph)
2890 (quoted quote)
2891 (centered center)
2892 (otherwise default))
2893 ;; If PARAGRAPH is a leading paragraph in an item that has
2894 ;; a checkbox, splice checkbox and paragraph contents
2895 ;; together.
2896 (concat (let ((parent (org-element-property :parent paragraph)))
2897 (and (eq (org-element-type parent) 'item)
2898 (not (org-export-get-previous-element paragraph info))
2899 (org-odt--checkbox parent)))
2900 contents)))
2902 (defun org-odt-paragraph (paragraph contents info)
2903 "Transcode a PARAGRAPH element from Org to ODT.
2904 CONTENTS is the contents of the paragraph, as a string. INFO is
2905 the plist used as a communication channel."
2906 (org-odt--format-paragraph
2907 paragraph contents info
2908 (or (org-element-property :style paragraph) "Text_20_body")
2909 "OrgCenter"
2910 "Quotations"))
2913 ;;;; Plain List
2915 (defun org-odt-plain-list (plain-list contents info)
2916 "Transcode a PLAIN-LIST element from Org to ODT.
2917 CONTENTS is the contents of the list. INFO is a plist holding
2918 contextual information."
2919 (format "\n<text:list text:style-name=\"%s\" %s>\n%s</text:list>"
2920 ;; Choose style based on list type.
2921 (case (org-element-property :type plain-list)
2922 (ordered "OrgNumberedList")
2923 (unordered "OrgBulletedList")
2924 (descriptive-1 "OrgDescriptionList")
2925 (descriptive-2 "OrgDescriptionList"))
2926 ;; If top-level list, re-start numbering. Otherwise,
2927 ;; continue numbering.
2928 (format "text:continue-numbering=\"%s\""
2929 (let* ((parent (org-export-get-parent plain-list)))
2930 (if (and parent (eq (org-element-type parent) 'item))
2931 "true" "false")))
2932 contents))
2934 ;;;; Plain Text
2936 (defun org-odt--encode-tabs-and-spaces (line)
2937 (replace-regexp-in-string
2938 "\\([\t]\\|\\([ ]+\\)\\)"
2939 (lambda (s)
2940 (cond
2941 ((string= s "\t") "<text:tab/>")
2942 (t (let ((n (length s)))
2943 (cond
2944 ((= n 1) " ")
2945 ((> n 1) (concat " " (format "<text:s text:c=\"%d\"/>" (1- n))))
2946 (t ""))))))
2947 line))
2949 (defun org-odt--encode-plain-text (text &optional no-whitespace-filling)
2950 (mapc
2951 (lambda (pair)
2952 (setq text (replace-regexp-in-string (car pair) (cdr pair) text t t)))
2953 '(("&" . "&amp;") ("<" . "&lt;") (">" . "&gt;")))
2954 (if no-whitespace-filling text
2955 (org-odt--encode-tabs-and-spaces text)))
2957 (defun org-odt-plain-text (text info)
2958 "Transcode a TEXT string from Org to ODT.
2959 TEXT is the string to transcode. INFO is a plist holding
2960 contextual information."
2961 (let ((output text))
2962 ;; Protect &, < and >.
2963 (setq output (org-odt--encode-plain-text output t))
2964 ;; Handle smart quotes. Be sure to provide original string since
2965 ;; OUTPUT may have been modified.
2966 (when (plist-get info :with-smart-quotes)
2967 (setq output (org-export-activate-smart-quotes output :utf-8 info text)))
2968 ;; Convert special strings.
2969 (when (plist-get info :with-special-strings)
2970 (mapc
2971 (lambda (pair)
2972 (setq output
2973 (replace-regexp-in-string (car pair) (cdr pair) output t nil)))
2974 org-odt-special-string-regexps))
2975 ;; Handle break preservation if required.
2976 (when (plist-get info :preserve-breaks)
2977 (setq output (replace-regexp-in-string
2978 "\\(\\\\\\\\\\)?[ \t]*\n" "<text:line-break/>" output t)))
2979 ;; Return value.
2980 output))
2983 ;;;; Planning
2985 (defun org-odt-planning (planning contents info)
2986 "Transcode a PLANNING element from Org to ODT.
2987 CONTENTS is nil. INFO is a plist used as a communication
2988 channel."
2989 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
2990 "OrgPlanning"
2991 (concat
2992 (let ((closed (org-element-property :closed planning)))
2993 (when closed
2994 (concat
2995 (format "<text:span text:style-name=\"%s\">%s</text:span>"
2996 "OrgClosedKeyword" org-closed-string)
2997 (org-odt-timestamp closed contents info))))
2998 (let ((deadline (org-element-property :deadline planning)))
2999 (when deadline
3000 (concat
3001 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3002 "OrgDeadlineKeyword" org-deadline-string)
3003 (org-odt-timestamp deadline contents info))))
3004 (let ((scheduled (org-element-property :scheduled planning)))
3005 (when scheduled
3006 (concat
3007 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3008 "OrgScheduledKeyword" org-deadline-string)
3009 (org-odt-timestamp scheduled contents info)))))))
3012 ;;;; Property Drawer
3014 (defun org-odt-property-drawer (property-drawer contents info)
3015 "Transcode a PROPERTY-DRAWER element from Org to ODT.
3016 CONTENTS holds the contents of the drawer. INFO is a plist
3017 holding contextual information."
3018 (and (org-string-nw-p contents)
3019 (format "<text:p text:style-name=\"OrgFixedWidthBlock\">%s</text:p>"
3020 contents)))
3023 ;;;; Quote Block
3025 (defun org-odt-quote-block (quote-block contents info)
3026 "Transcode a QUOTE-BLOCK element from Org to ODT.
3027 CONTENTS holds the contents of the block. INFO is a plist
3028 holding contextual information."
3029 contents)
3032 ;;;; Section
3034 (defun org-odt-format-section (text style &optional name)
3035 (let ((default-name (car (org-odt-add-automatic-style "Section"))))
3036 (format "\n<text:section text:style-name=\"%s\" %s>\n%s\n</text:section>"
3037 style
3038 (format "text:name=\"%s\"" (or name default-name))
3039 text)))
3042 (defun org-odt-section (section contents info) ; FIXME
3043 "Transcode a SECTION element from Org to ODT.
3044 CONTENTS holds the contents of the section. INFO is a plist
3045 holding contextual information."
3046 contents)
3048 ;;;; Radio Target
3050 (defun org-odt-radio-target (radio-target text info)
3051 "Transcode a RADIO-TARGET object from Org to ODT.
3052 TEXT is the text of the target. INFO is a plist holding
3053 contextual information."
3054 (org-odt--target
3055 text (org-export-solidify-link-text
3056 (org-element-property :value radio-target))))
3059 ;;;; Special Block
3061 (defun org-odt-special-block (special-block contents info)
3062 "Transcode a SPECIAL-BLOCK element from Org to ODT.
3063 CONTENTS holds the contents of the block. INFO is a plist
3064 holding contextual information."
3065 (let ((type (org-element-property :type special-block))
3066 (attributes (org-export-read-attribute :attr_odt special-block)))
3067 (cond
3068 ;; Annotation.
3069 ((string= type "annotation")
3070 (let* ((author (or (plist-get attributes :author)
3071 (let ((author (plist-get info :author)))
3072 (and author (org-export-data author info)))))
3073 (date (or (plist-get attributes :date)
3074 ;; FIXME: Is `car' right thing to do below?
3075 (car (plist-get info :date)))))
3076 (format "\n<text:p>%s</text:p>"
3077 (format "<office:annotation>\n%s\n</office:annotation>"
3078 (concat
3079 (and author
3080 (format "<dc:creator>%s</dc:creator>" author))
3081 (and date
3082 (format "<dc:date>%s</dc:date>"
3083 (org-odt--format-timestamp date nil 'iso-date)))
3084 contents)))))
3085 ;; Textbox.
3086 ((string= type "textbox")
3087 (let ((width (plist-get attributes :width))
3088 (height (plist-get attributes :height))
3089 (style (plist-get attributes :style))
3090 (extra (plist-get attributes :extra))
3091 (anchor (plist-get attributes :anchor)))
3092 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3093 "Text_20_body" (org-odt--textbox contents width height
3094 style extra anchor))))
3095 (t contents))))
3098 ;;;; Src Block
3100 (defun org-odt-hfy-face-to-css (fn)
3101 "Create custom style for face FN.
3102 When FN is the default face, use its foreground and background
3103 properties to create \"OrgSrcBlock\" paragraph style. Otherwise
3104 use its color attribute to create a character style whose name
3105 is obtained from FN. Currently all attributes of FN other than
3106 color are ignored.
3108 The style name for a face FN is derived using the following
3109 operations on the face name in that order - de-dash, CamelCase
3110 and prefix with \"OrgSrc\". For example,
3111 `font-lock-function-name-face' is associated with
3112 \"OrgSrcFontLockFunctionNameFace\"."
3113 (let* ((css-list (hfy-face-to-style fn))
3114 (style-name (concat "OrgSrc"
3115 (mapconcat
3116 'capitalize (split-string
3117 (hfy-face-or-def-to-name fn) "-")
3118 "")))
3119 (color-val (cdr (assoc "color" css-list)))
3120 (background-color-val (cdr (assoc "background" css-list)))
3121 (style (and org-odt-create-custom-styles-for-srcblocks
3122 (cond
3123 ((eq fn 'default)
3124 (format org-odt-src-block-paragraph-format
3125 background-color-val color-val))
3127 (format
3129 <style:style style:name=\"%s\" style:family=\"text\">
3130 <style:text-properties fo:color=\"%s\"/>
3131 </style:style>" style-name color-val))))))
3132 (cons style-name style)))
3134 (defun org-odt-htmlfontify-string (line)
3135 (let* ((hfy-html-quote-regex "\\([<\"&> ]\\)")
3136 (hfy-html-quote-map '(("\"" "&quot;")
3137 ("<" "&lt;")
3138 ("&" "&amp;")
3139 (">" "&gt;")
3140 (" " "<text:s/>")
3141 (" " "<text:tab/>")))
3142 (hfy-face-to-css 'org-odt-hfy-face-to-css)
3143 (hfy-optimisations-1 (copy-sequence hfy-optimisations))
3144 (hfy-optimisations (add-to-list 'hfy-optimisations-1
3145 'body-text-only))
3146 (hfy-begin-span-handler
3147 (lambda (style text-block text-id text-begins-block-p)
3148 (insert (format "<text:span text:style-name=\"%s\">" style))))
3149 (hfy-end-span-handler (lambda nil (insert "</text:span>"))))
3150 (org-no-warnings (htmlfontify-string line))))
3152 (defun org-odt-do-format-code
3153 (code info &optional lang refs retain-labels num-start)
3154 (let* ((lang (or (assoc-default lang org-src-lang-modes) lang))
3155 (lang-mode (and lang (intern (format "%s-mode" lang))))
3156 (code-lines (org-split-string code "\n"))
3157 (code-length (length code-lines))
3158 (use-htmlfontify-p (and (functionp lang-mode)
3159 (plist-get info :odt-fontify-srcblocks)
3160 (require 'htmlfontify nil t)
3161 (fboundp 'htmlfontify-string)))
3162 (code (if (not use-htmlfontify-p) code
3163 (with-temp-buffer
3164 (insert code)
3165 (funcall lang-mode)
3166 (font-lock-ensure)
3167 (buffer-string))))
3168 (fontifier (if use-htmlfontify-p 'org-odt-htmlfontify-string
3169 'org-odt--encode-plain-text))
3170 (par-style (if use-htmlfontify-p "OrgSrcBlock"
3171 "OrgFixedWidthBlock"))
3172 (i 0))
3173 (assert (= code-length (length (org-split-string code "\n"))))
3174 (setq code
3175 (org-export-format-code
3176 code
3177 (lambda (loc line-num ref)
3178 (setq par-style
3179 (concat par-style (and (= (incf i) code-length) "LastLine")))
3181 (setq loc (concat loc (and ref retain-labels (format " (%s)" ref))))
3182 (setq loc (funcall fontifier loc))
3183 (when ref
3184 (setq loc (org-odt--target loc (concat "coderef-" ref))))
3185 (assert par-style)
3186 (setq loc (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3187 par-style loc))
3188 (if (not line-num) loc
3189 (format "\n<text:list-item>%s\n</text:list-item>" loc)))
3190 num-start refs))
3191 (cond
3192 ((not num-start) code)
3193 ((= num-start 0)
3194 (format
3195 "\n<text:list text:style-name=\"OrgSrcBlockNumberedLine\"%s>%s</text:list>"
3196 " text:continue-numbering=\"false\"" code))
3198 (format
3199 "\n<text:list text:style-name=\"OrgSrcBlockNumberedLine\"%s>%s</text:list>"
3200 " text:continue-numbering=\"true\"" code)))))
3202 (defun org-odt-format-code (element info)
3203 (let* ((lang (org-element-property :language element))
3204 ;; Extract code and references.
3205 (code-info (org-export-unravel-code element))
3206 (code (car code-info))
3207 (refs (cdr code-info))
3208 ;; Does the src block contain labels?
3209 (retain-labels (org-element-property :retain-labels element))
3210 ;; Does it have line numbers?
3211 (num-start (case (org-element-property :number-lines element)
3212 (continued (org-export-get-loc element info))
3213 (new 0))))
3214 (org-odt-do-format-code code info lang refs retain-labels num-start)))
3216 (defun org-odt-src-block (src-block contents info)
3217 "Transcode a SRC-BLOCK element from Org to ODT.
3218 CONTENTS holds the contents of the item. INFO is a plist holding
3219 contextual information."
3220 (let* ((lang (org-element-property :language src-block))
3221 (attributes (org-export-read-attribute :attr_odt src-block))
3222 (captions (org-odt-format-label src-block info 'definition))
3223 (caption (car captions)) (short-caption (cdr captions)))
3224 (concat
3225 (and caption
3226 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3227 "Listing" caption))
3228 (let ((--src-block (org-odt-format-code src-block info)))
3229 (if (not (plist-get attributes :textbox)) --src-block
3230 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3231 "Text_20_body"
3232 (org-odt--textbox --src-block nil nil nil)))))))
3235 ;;;; Statistics Cookie
3237 (defun org-odt-statistics-cookie (statistics-cookie contents info)
3238 "Transcode a STATISTICS-COOKIE object from Org to ODT.
3239 CONTENTS is nil. INFO is a plist holding contextual information."
3240 (let ((cookie-value (org-element-property :value statistics-cookie)))
3241 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3242 "OrgCode" cookie-value)))
3245 ;;;; Strike-Through
3247 (defun org-odt-strike-through (strike-through contents info)
3248 "Transcode STRIKE-THROUGH from Org to ODT.
3249 CONTENTS is the text with strike-through markup. INFO is a plist
3250 holding contextual information."
3251 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3252 "Strikethrough" contents))
3255 ;;;; Subscript
3257 (defun org-odt-subscript (subscript contents info)
3258 "Transcode a SUBSCRIPT object from Org to ODT.
3259 CONTENTS is the contents of the object. INFO is a plist holding
3260 contextual information."
3261 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3262 "OrgSubscript" contents))
3265 ;;;; Superscript
3267 (defun org-odt-superscript (superscript contents info)
3268 "Transcode a SUPERSCRIPT object from Org to ODT.
3269 CONTENTS is the contents of the object. INFO is a plist holding
3270 contextual information."
3271 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3272 "OrgSuperscript" contents))
3275 ;;;; Table Cell
3277 (defun org-odt-table-style-spec (element info)
3278 (let* ((table (org-export-get-parent-table element))
3279 (table-attributes (org-export-read-attribute :attr_odt table))
3280 (table-style (plist-get table-attributes :style)))
3281 (assoc table-style (plist-get info :odt-table-styles))))
3283 (defun org-odt-get-table-cell-styles (table-cell info)
3284 "Retrieve styles applicable to a table cell.
3285 R and C are (zero-based) row and column numbers of the table
3286 cell. STYLE-SPEC is an entry in `org-odt-table-styles'
3287 applicable to the current table. It is nil if the table is not
3288 associated with any style attributes.
3290 Return a cons of (TABLE-CELL-STYLE-NAME . PARAGRAPH-STYLE-NAME).
3292 When STYLE-SPEC is nil, style the table cell the conventional way
3293 - choose cell borders based on row and column groupings and
3294 choose paragraph alignment based on `org-col-cookies' text
3295 property. See also
3296 `org-odt-get-paragraph-style-cookie-for-table-cell'.
3298 When STYLE-SPEC is non-nil, ignore the above cookie and return
3299 styles congruent with the ODF-1.2 specification."
3300 (let* ((table-cell-address (org-export-table-cell-address table-cell info))
3301 (r (car table-cell-address)) (c (cdr table-cell-address))
3302 (style-spec (org-odt-table-style-spec table-cell info))
3303 (table-dimensions (org-export-table-dimensions
3304 (org-export-get-parent-table table-cell)
3305 info)))
3306 (when style-spec
3307 ;; LibreOffice - particularly the Writer - honors neither table
3308 ;; templates nor custom table-cell styles. Inorder to retain
3309 ;; inter-operability with LibreOffice, only automatic styles are
3310 ;; used for styling of table-cells. The current implementation is
3311 ;; congruent with ODF-1.2 specification and hence is
3312 ;; future-compatible.
3314 ;; Additional Note: LibreOffice's AutoFormat facility for tables -
3315 ;; which recognizes as many as 16 different cell types - is much
3316 ;; richer. Unfortunately it is NOT amenable to easy configuration
3317 ;; by hand.
3318 (let* ((template-name (nth 1 style-spec))
3319 (cell-style-selectors (nth 2 style-spec))
3320 (cell-type
3321 (cond
3322 ((and (cdr (assoc 'use-first-column-styles cell-style-selectors))
3323 (= c 0)) "FirstColumn")
3324 ((and (cdr (assoc 'use-last-column-styles cell-style-selectors))
3325 (= (1+ c) (cdr table-dimensions)))
3326 "LastColumn")
3327 ((and (cdr (assoc 'use-first-row-styles cell-style-selectors))
3328 (= r 0)) "FirstRow")
3329 ((and (cdr (assoc 'use-last-row-styles cell-style-selectors))
3330 (= (1+ r) (car table-dimensions)))
3331 "LastRow")
3332 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
3333 (= (% r 2) 1)) "EvenRow")
3334 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
3335 (= (% r 2) 0)) "OddRow")
3336 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
3337 (= (% c 2) 1)) "EvenColumn")
3338 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
3339 (= (% c 2) 0)) "OddColumn")
3340 (t ""))))
3341 (concat template-name cell-type)))))
3343 (defun org-odt-table-cell (table-cell contents info)
3344 "Transcode a TABLE-CELL element from Org to ODT.
3345 CONTENTS is nil. INFO is a plist used as a communication
3346 channel."
3347 (let* ((table-cell-address (org-export-table-cell-address table-cell info))
3348 (r (car table-cell-address))
3349 (c (cdr table-cell-address))
3350 (horiz-span (or (org-export-table-cell-width table-cell info) 0))
3351 (table-row (org-export-get-parent table-cell))
3352 (custom-style-prefix (org-odt-get-table-cell-styles
3353 table-cell info))
3354 (paragraph-style
3356 (and custom-style-prefix
3357 (format "%sTableParagraph" custom-style-prefix))
3358 (concat
3359 (cond
3360 ((and (= 1 (org-export-table-row-group table-row info))
3361 (org-export-table-has-header-p
3362 (org-export-get-parent-table table-row) info))
3363 "OrgTableHeading")
3364 ((let* ((table (org-export-get-parent-table table-cell))
3365 (table-attrs (org-export-read-attribute :attr_odt table))
3366 (table-header-columns
3367 (let ((cols (plist-get table-attrs :header-columns)))
3368 (and cols (read cols)))))
3369 (<= c (cond ((wholenump table-header-columns)
3370 (- table-header-columns 1))
3371 (table-header-columns 0)
3372 (t -1))))
3373 "OrgTableHeading")
3374 (t "OrgTableContents"))
3375 (capitalize (symbol-name (org-export-table-cell-alignment
3376 table-cell info))))))
3377 (cell-style-name
3379 (and custom-style-prefix (format "%sTableCell"
3380 custom-style-prefix))
3381 (concat
3382 "OrgTblCell"
3383 (when (or (org-export-table-row-starts-rowgroup-p table-row info)
3384 (zerop r)) "T")
3385 (when (org-export-table-row-ends-rowgroup-p table-row info) "B")
3386 (when (and (org-export-table-cell-starts-colgroup-p table-cell info)
3387 (not (zerop c)) ) "L"))))
3388 (cell-attributes
3389 (concat
3390 (format " table:style-name=\"%s\"" cell-style-name)
3391 (and (> horiz-span 0)
3392 (format " table:number-columns-spanned=\"%d\""
3393 (1+ horiz-span))))))
3394 (unless contents (setq contents ""))
3395 (concat
3396 (assert paragraph-style)
3397 (format "\n<table:table-cell%s>\n%s\n</table:table-cell>"
3398 cell-attributes
3399 (let ((table-cell-contents (org-element-contents table-cell)))
3400 (if (memq (org-element-type (car table-cell-contents))
3401 org-element-all-elements)
3402 contents
3403 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3404 paragraph-style contents))))
3405 (let (s)
3406 (dotimes (i horiz-span s)
3407 (setq s (concat s "\n<table:covered-table-cell/>"))))
3408 "\n")))
3411 ;;;; Table Row
3413 (defun org-odt-table-row (table-row contents info)
3414 "Transcode a TABLE-ROW element from Org to ODT.
3415 CONTENTS is the contents of the row. INFO is a plist used as a
3416 communication channel."
3417 ;; Rules are ignored since table separators are deduced from
3418 ;; borders of the current row.
3419 (when (eq (org-element-property :type table-row) 'standard)
3420 (let* ((rowgroup-tags
3421 (if (and (= 1 (org-export-table-row-group table-row info))
3422 (org-export-table-has-header-p
3423 (org-export-get-parent-table table-row) info))
3424 ;; If the row belongs to the first rowgroup and the
3425 ;; table has more than one row groups, then this row
3426 ;; belongs to the header row group.
3427 '("\n<table:table-header-rows>" . "\n</table:table-header-rows>")
3428 ;; Otherwise, it belongs to non-header row group.
3429 '("\n<table:table-rows>" . "\n</table:table-rows>"))))
3430 (concat
3431 ;; Does this row begin a rowgroup?
3432 (when (org-export-table-row-starts-rowgroup-p table-row info)
3433 (car rowgroup-tags))
3434 ;; Actual table row
3435 (format "\n<table:table-row>\n%s\n</table:table-row>" contents)
3436 ;; Does this row end a rowgroup?
3437 (when (org-export-table-row-ends-rowgroup-p table-row info)
3438 (cdr rowgroup-tags))))))
3441 ;;;; Table
3443 (defun org-odt-table-first-row-data-cells (table info)
3444 (let ((table-row
3445 (org-element-map table 'table-row
3446 (lambda (row)
3447 (unless (eq (org-element-property :type row) 'rule) row))
3448 info 'first-match))
3449 (special-column-p (org-export-table-has-special-column-p table)))
3450 (if (not special-column-p) (org-element-contents table-row)
3451 (cdr (org-element-contents table-row)))))
3453 (defun org-odt--table (table contents info)
3454 "Transcode a TABLE element from Org to ODT.
3455 CONTENTS is the contents of the table. INFO is a plist holding
3456 contextual information."
3457 (case (org-element-property :type table)
3458 ;; Case 1: table.el doesn't support export to OD format. Strip
3459 ;; such tables from export.
3460 (table.el
3461 (prog1 nil
3462 (message
3463 (concat
3464 "(ox-odt): Found table.el-type table in the source Org file."
3465 " table.el doesn't support export to ODT format."
3466 " Stripping the table from export."))))
3467 ;; Case 2: Native Org tables.
3468 (otherwise
3469 (let* ((captions (org-odt-format-label table info 'definition))
3470 (caption (car captions)) (short-caption (cdr captions))
3471 (attributes (org-export-read-attribute :attr_odt table))
3472 (custom-table-style (nth 1 (org-odt-table-style-spec table info)))
3473 (table-column-specs
3474 (function
3475 (lambda (table info)
3476 (let* ((table-style (or custom-table-style "OrgTable"))
3477 (column-style (format "%sColumn" table-style)))
3478 (mapconcat
3479 (lambda (table-cell)
3480 (let ((width (1+ (or (org-export-table-cell-width
3481 table-cell info) 0)))
3482 (s (format
3483 "\n<table:table-column table:style-name=\"%s\"/>"
3484 column-style))
3485 out)
3486 (dotimes (i width out) (setq out (concat s out)))))
3487 (org-odt-table-first-row-data-cells table info) "\n"))))))
3488 (concat
3489 ;; caption.
3490 (when caption
3491 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3492 "Table" caption))
3493 ;; begin table.
3494 (let* ((automatic-name
3495 (org-odt-add-automatic-style "Table" attributes)))
3496 (format
3497 "\n<table:table table:style-name=\"%s\"%s>"
3498 (or custom-table-style (cdr automatic-name) "OrgTable")
3499 (concat (when short-caption
3500 (format " table:name=\"%s\"" short-caption)))))
3501 ;; column specification.
3502 (funcall table-column-specs table info)
3503 ;; actual contents.
3504 "\n" contents
3505 ;; end table.
3506 "</table:table>")))))
3508 (defun org-odt-table (table contents info)
3509 "Transcode a TABLE element from Org to ODT.
3510 CONTENTS is the contents of the table. INFO is a plist holding
3511 contextual information.
3513 Use `org-odt--table' to typeset the table. Handle details
3514 pertaining to indentation here."
3515 (let* ((--element-preceded-by-table-p
3516 (function
3517 (lambda (element info)
3518 (loop for el in (org-export-get-previous-element element info t)
3519 thereis (eq (org-element-type el) 'table)))))
3520 (--walk-list-genealogy-and-collect-tags
3521 (function
3522 (lambda (table info)
3523 (let* ((genealogy (org-element-lineage table))
3524 (list-genealogy
3525 (when (eq (org-element-type (car genealogy)) 'item)
3526 (loop for el in genealogy
3527 when (memq (org-element-type el)
3528 '(item plain-list))
3529 collect el)))
3530 (llh-genealogy
3531 (apply 'nconc
3532 (loop for el in genealogy
3533 when (and (eq (org-element-type el) 'headline)
3534 (org-export-low-level-p el info))
3535 collect
3536 (list el
3537 (assq 'headline
3538 (org-element-contents
3539 (org-export-get-parent el)))))))
3540 parent-list)
3541 (nconc
3542 ;; Handle list genealogy.
3543 (loop for el in list-genealogy collect
3544 (case (org-element-type el)
3545 (plain-list
3546 (setq parent-list el)
3547 (cons "</text:list>"
3548 (format "\n<text:list text:style-name=\"%s\" %s>"
3549 (case (org-element-property :type el)
3550 (ordered "OrgNumberedList")
3551 (unordered "OrgBulletedList")
3552 (descriptive-1 "OrgDescriptionList")
3553 (descriptive-2 "OrgDescriptionList"))
3554 "text:continue-numbering=\"true\"")))
3555 (item
3556 (cond
3557 ((not parent-list)
3558 (if (funcall --element-preceded-by-table-p table info)
3559 '("</text:list-header>" . "<text:list-header>")
3560 '("</text:list-item>" . "<text:list-header>")))
3561 ((funcall --element-preceded-by-table-p
3562 parent-list info)
3563 '("</text:list-header>" . "<text:list-header>"))
3564 (t '("</text:list-item>" . "<text:list-item>"))))))
3565 ;; Handle low-level headlines.
3566 (loop for el in llh-genealogy
3567 with step = 'item collect
3568 (case step
3569 (plain-list
3570 (setq step 'item) ; Flip-flop
3571 (setq parent-list el)
3572 (cons "</text:list>"
3573 (format "\n<text:list text:style-name=\"%s\" %s>"
3574 (if (org-export-numbered-headline-p
3575 el info)
3576 "OrgNumberedList"
3577 "OrgBulletedList")
3578 "text:continue-numbering=\"true\"")))
3579 (item
3580 (setq step 'plain-list) ; Flip-flop
3581 (cond
3582 ((not parent-list)
3583 (if (funcall --element-preceded-by-table-p table info)
3584 '("</text:list-header>" . "<text:list-header>")
3585 '("</text:list-item>" . "<text:list-header>")))
3586 ((let ((section? (org-export-get-previous-element
3587 parent-list info)))
3588 (and section?
3589 (eq (org-element-type section?) 'section)
3590 (assq 'table (org-element-contents section?))))
3591 '("</text:list-header>" . "<text:list-header>"))
3593 '("</text:list-item>" . "<text:list-item>")))))))))))
3594 (close-open-tags (funcall --walk-list-genealogy-and-collect-tags
3595 table info)))
3596 ;; OpenDocument schema does not permit table to occur within a
3597 ;; list item.
3599 ;; One solution - the easiest and lightweight, in terms of
3600 ;; implementation - is to put the table in an indented text box
3601 ;; and make the text box part of the list-item. Unfortunately if
3602 ;; the table is big and spans multiple pages, the text box could
3603 ;; overflow. In this case, the following attribute will come
3604 ;; handy.
3606 ;; ,---- From OpenDocument-v1.1.pdf
3607 ;; | 15.27.28 Overflow behavior
3608 ;; |
3609 ;; | For text boxes contained within text document, the
3610 ;; | style:overflow-behavior property specifies the behavior of text
3611 ;; | boxes where the containing text does not fit into the text
3612 ;; | box.
3613 ;; |
3614 ;; | If the attribute's value is clip, the text that does not fit
3615 ;; | into the text box is not displayed.
3616 ;; |
3617 ;; | If the attribute value is auto-create-new-frame, a new frame
3618 ;; | will be created on the next page, with the same position and
3619 ;; | dimensions of the original frame.
3620 ;; |
3621 ;; | If the style:overflow-behavior property's value is
3622 ;; | auto-create-new-frame and the text box has a minimum width or
3623 ;; | height specified, then the text box will grow until the page
3624 ;; | bounds are reached before a new frame is created.
3625 ;; `----
3627 ;; Unfortunately, LibreOffice-3.4.6 doesn't honor
3628 ;; auto-create-new-frame property and always resorts to clipping
3629 ;; the text box. This results in table being truncated.
3631 ;; So we solve the problem the hard (and fun) way using list
3632 ;; continuations.
3634 ;; The problem only becomes more interesting if you take in to
3635 ;; account the following facts:
3637 ;; - Description lists are simulated as plain lists.
3638 ;; - Low-level headlines can be listified.
3639 ;; - In Org-mode, a table can occur not only as a regular list
3640 ;; item, but also within description lists and low-level
3641 ;; headlines.
3643 ;; See `org-odt-translate-description-lists' and
3644 ;; `org-odt-translate-low-level-headlines' for how this is
3645 ;; tackled.
3647 (concat "\n"
3648 ;; Discontinue the list.
3649 (mapconcat 'car close-open-tags "\n")
3650 ;; Put the table in an indented section.
3651 (let* ((table (org-odt--table table contents info))
3652 (level (/ (length (mapcar 'car close-open-tags)) 2))
3653 (style (format "OrgIndentedSection-Level-%d" level)))
3654 (when table (org-odt-format-section table style)))
3655 ;; Continue the list.
3656 (mapconcat 'cdr (nreverse close-open-tags) "\n"))))
3659 ;;;; Target
3661 (defun org-odt-target (target contents info)
3662 "Transcode a TARGET object from Org to ODT.
3663 CONTENTS is nil. INFO is a plist holding contextual
3664 information."
3665 (let ((value (org-element-property :value target)))
3666 (org-odt--target "" (org-export-solidify-link-text value))))
3669 ;;;; Timestamp
3671 (defun org-odt-timestamp (timestamp contents info)
3672 "Transcode a TIMESTAMP object from Org to ODT.
3673 CONTENTS is nil. INFO is a plist used as a communication
3674 channel."
3675 (let* ((raw-value (org-element-property :raw-value timestamp))
3676 (type (org-element-property :type timestamp)))
3677 (if (not (plist-get info :odt-use-date-fields))
3678 (let ((value (org-odt-plain-text
3679 (org-timestamp-translate timestamp) info)))
3680 (case (org-element-property :type timestamp)
3681 ((active active-range)
3682 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3683 "OrgActiveTimestamp" value))
3684 ((inactive inactive-range)
3685 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3686 "OrgInactiveTimestamp" value))
3687 (otherwise value)))
3688 (case type
3689 (active
3690 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3691 "OrgActiveTimestamp"
3692 (format "&lt;%s&gt;" (org-odt--format-timestamp timestamp))))
3693 (inactive
3694 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3695 "OrgInactiveTimestamp"
3696 (format "[%s]" (org-odt--format-timestamp timestamp))))
3697 (active-range
3698 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3699 "OrgActiveTimestamp"
3700 (format "&lt;%s&gt;&#x2013;&lt;%s&gt;"
3701 (org-odt--format-timestamp timestamp)
3702 (org-odt--format-timestamp timestamp 'end))))
3703 (inactive-range
3704 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3705 "OrgInactiveTimestamp"
3706 (format "[%s]&#x2013;[%s]"
3707 (org-odt--format-timestamp timestamp)
3708 (org-odt--format-timestamp timestamp 'end))))
3709 (otherwise
3710 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3711 "OrgDiaryTimestamp"
3712 (org-odt-plain-text (org-timestamp-translate timestamp)
3713 info)))))))
3716 ;;;; Underline
3718 (defun org-odt-underline (underline contents info)
3719 "Transcode UNDERLINE from Org to ODT.
3720 CONTENTS is the text with underline markup. INFO is a plist
3721 holding contextual information."
3722 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3723 "Underline" contents))
3726 ;;;; Verbatim
3728 (defun org-odt-verbatim (verbatim contents info)
3729 "Transcode a VERBATIM object from Org to ODT.
3730 CONTENTS is nil. INFO is a plist used as a communication
3731 channel."
3732 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3733 "OrgCode" (org-odt--encode-plain-text
3734 (org-element-property :value verbatim))))
3737 ;;;; Verse Block
3739 (defun org-odt-verse-block (verse-block contents info)
3740 "Transcode a VERSE-BLOCK element from Org to ODT.
3741 CONTENTS is verse block contents. INFO is a plist holding
3742 contextual information."
3743 ;; Add line breaks to each line of verse.
3744 (setq contents (replace-regexp-in-string
3745 "\\(<text:line-break/>\\)?[ \t]*\n"
3746 "<text:line-break/>" contents))
3747 ;; Replace tabs and spaces.
3748 (setq contents (org-odt--encode-tabs-and-spaces contents))
3749 ;; Surround it in a verse environment.
3750 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3751 "OrgVerse" contents))
3755 ;;; Filters
3757 ;;;; LaTeX fragments
3759 (defun org-odt--translate-latex-fragments (tree backend info)
3760 (let ((processing-type (plist-get info :with-latex))
3761 (count 0))
3762 ;; Normalize processing-type to one of dvipng, mathml or verbatim.
3763 ;; If the desired converter is not available, force verbatim
3764 ;; processing.
3765 (case processing-type
3766 ((t mathml)
3767 (if (and (fboundp 'org-format-latex-mathml-available-p)
3768 (org-format-latex-mathml-available-p))
3769 (setq processing-type 'mathml)
3770 (message "LaTeX to MathML converter not available.")
3771 (setq processing-type 'verbatim)))
3772 ((dvipng imagemagick)
3773 (unless (and (org-check-external-command "latex" "" t)
3774 (org-check-external-command
3775 (if (eq processing-type 'dvipng) "dvipng" "convert") "" t))
3776 (message "LaTeX to PNG converter not available.")
3777 (setq processing-type 'verbatim)))
3778 (otherwise
3779 (message "Unknown LaTeX option. Forcing verbatim.")
3780 (setq processing-type 'verbatim)))
3782 ;; Store normalized value for later use.
3783 (when (plist-get info :with-latex)
3784 (plist-put info :with-latex processing-type))
3785 (message "Formatting LaTeX using %s" processing-type)
3787 ;; Convert `latex-fragment's and `latex-environment's.
3788 (when (memq processing-type '(mathml dvipng imagemagick))
3789 (org-element-map tree '(latex-fragment latex-environment)
3790 (lambda (latex-*)
3791 (incf count)
3792 (let* ((latex-frag (org-element-property :value latex-*))
3793 (input-file (plist-get info :input-file))
3794 (cache-dir (file-name-directory input-file))
3795 (cache-subdir (concat
3796 (case processing-type
3797 ((dvipng imagemagick) "ltxpng/")
3798 (mathml "ltxmathml/"))
3799 (file-name-sans-extension
3800 (file-name-nondirectory input-file))))
3801 (display-msg
3802 (case processing-type
3803 ((dvipng imagemagick) (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 (org-element-map
3822 (org-element-parse-secondary-string
3823 org-link 'paragraph)
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