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