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