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