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