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