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