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