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