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