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