ox-odt.el: Remove some export options associated to variables
[org-mode/org-cv.git] / lisp / ox-odt.el
blob0f0203ad6b039cf1206083eaae068e66c4cc52a3
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-block . org-odt-export-block)
47 (export-snippet . org-odt-export-snippet)
48 (fixed-width . org-odt-fixed-width)
49 (footnote-definition . org-odt-footnote-definition)
50 (footnote-reference . org-odt-footnote-reference)
51 (headline . org-odt-headline)
52 (horizontal-rule . org-odt-horizontal-rule)
53 (inline-src-block . org-odt-inline-src-block)
54 (inlinetask . org-odt-inlinetask)
55 (italic . org-odt-italic)
56 (item . org-odt-item)
57 (keyword . org-odt-keyword)
58 (latex-environment . org-odt-latex-environment)
59 (latex-fragment . org-odt-latex-fragment)
60 (line-break . org-odt-line-break)
61 (link . org-odt-link)
62 (node-property . org-odt-node-property)
63 (paragraph . org-odt-paragraph)
64 (plain-list . org-odt-plain-list)
65 (plain-text . org-odt-plain-text)
66 (planning . org-odt-planning)
67 (property-drawer . org-odt-property-drawer)
68 (quote-block . org-odt-quote-block)
69 (radio-target . org-odt-radio-target)
70 (section . org-odt-section)
71 (special-block . org-odt-special-block)
72 (src-block . org-odt-src-block)
73 (statistics-cookie . org-odt-statistics-cookie)
74 (strike-through . org-odt-strike-through)
75 (subscript . org-odt-subscript)
76 (superscript . org-odt-superscript)
77 (table . org-odt-table)
78 (table-cell . org-odt-table-cell)
79 (table-row . org-odt-table-row)
80 (target . org-odt-target)
81 (template . org-odt-template)
82 (timestamp . org-odt-timestamp)
83 (underline . org-odt-underline)
84 (verbatim . org-odt-verbatim)
85 (verse-block . org-odt-verse-block))
86 :export-block "ODT"
87 :filters-alist '((:filter-parse-tree
88 . (org-odt--translate-latex-fragments
89 org-odt--translate-description-lists ; Dummy symbol
90 org-odt--translate-list-tables)))
91 :menu-entry
92 '(?o "Export to ODT"
93 ((?o "As ODT file" org-odt-export-to-odt)
94 (?O "As ODT file and open"
95 (lambda (a s v b)
96 (if a (org-odt-export-to-odt t s v)
97 (org-open-file (org-odt-export-to-odt nil s v) 'system))))))
98 :options-alist
99 '((:odt-styles-file "ODT_STYLES_FILE" nil nil t)
100 ;; Other variables.
101 (:odt-content-template-file nil nil org-odt-content-template-file)
102 (:odt-display-outline-level nil nil org-odt-display-outline-level)
103 (:odt-fontify-srcblocks nil nil org-odt-fontify-srcblocks)
104 (:odt-format-drawer-function nil nil org-odt-format-drawer-function)
105 (:odt-format-headline-function nil nil org-odt-format-headline-function)
106 (:odt-format-inlinetask-function nil nil org-odt-format-inlinetask-function)
107 (:odt-inline-formula-rules nil nil org-odt-inline-formula-rules)
108 (:odt-inline-image-rules nil nil org-odt-inline-image-rules)
109 (:odt-pixels-per-inch nil nil org-odt-pixels-per-inch)
110 (:odt-styles-file nil nil org-odt-styles-file)
111 (:odt-table-styles nil nil org-odt-table-styles)
112 (:odt-use-date-fields nil nil org-odt-use-date-fields)
113 ;; Redefine regular option.
114 (:with-latex nil "tex" org-odt-with-latex)))
117 ;;; Dependencies
119 ;;; Hooks
121 ;;; Function Declarations
123 (declare-function hfy-face-to-style "htmlfontify" (fn))
124 (declare-function hfy-face-or-def-to-name "htmlfontify" (fn))
125 (declare-function archive-zip-extract "arc-mode" (archive name))
126 (declare-function org-create-math-formula "org" (latex-frag &optional mathml-file))
127 (declare-function browse-url-file-url "browse-url" (file))
131 ;;; Internal Variables
133 (defconst org-odt-lib-dir
134 (file-name-directory (or load-file-name (buffer-file-name)))
135 "Location of ODT exporter.
136 Use this to infer values of `org-odt-styles-dir' and
137 `org-odt-schema-dir'.")
139 (defvar org-odt-data-dir nil
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 (expand-file-name "../etc/schema/" org-odt-lib-dir) ; git
159 (expand-file-name "./etc/schema/" org-odt-lib-dir) ; elpa
161 "List of directories to search for OpenDocument schema files.
162 Use this list to set the default value of
163 `org-odt-schema-dir'. The entries in this list are
164 populated heuristically based on the values of `org-odt-lib-dir'
165 and `org-odt-data-dir'.")
167 (defconst org-odt-styles-dir-list
168 (list
169 (and org-odt-data-dir
170 (expand-file-name "./styles/" org-odt-data-dir)) ; bail out
171 (eval-when-compile
172 (and (boundp 'org-odt-data-dir) org-odt-data-dir ; see make install
173 (expand-file-name "./styles/" org-odt-data-dir)))
174 (expand-file-name "../etc/styles/" org-odt-lib-dir) ; git
175 (expand-file-name "./etc/styles/" org-odt-lib-dir) ; elpa
176 (expand-file-name "./org/" data-directory) ; system
178 "List of directories to search for OpenDocument styles files.
179 See `org-odt-styles-dir'. The entries in this list are populated
180 heuristically based on the values of `org-odt-lib-dir' and
181 `org-odt-data-dir'.")
183 (defconst org-odt-styles-dir
184 (let* ((styles-dir
185 (catch 'styles-dir
186 (message "Debug (ox-odt): Searching for OpenDocument styles files...")
187 (mapc (lambda (styles-dir)
188 (when styles-dir
189 (message "Debug (ox-odt): Trying %s..." styles-dir)
190 (when (and (file-readable-p
191 (expand-file-name
192 "OrgOdtContentTemplate.xml" styles-dir))
193 (file-readable-p
194 (expand-file-name
195 "OrgOdtStyles.xml" styles-dir)))
196 (message "Debug (ox-odt): Using styles under %s"
197 styles-dir)
198 (throw 'styles-dir styles-dir))))
199 org-odt-styles-dir-list)
200 nil)))
201 (unless styles-dir
202 (error "Error (ox-odt): Cannot find factory styles files, aborting"))
203 styles-dir)
204 "Directory that holds auxiliary XML files used by the ODT exporter.
206 This directory contains the following XML files -
207 \"OrgOdtStyles.xml\" and \"OrgOdtContentTemplate.xml\". These
208 XML files are used as the default values of
209 `org-odt-styles-file' and
210 `org-odt-content-template-file'.
212 The default value of this variable varies depending on the
213 version of org in use and is initialized from
214 `org-odt-styles-dir-list'. Note that the user could be using org
215 from one of: org's own private git repository, GNU ELPA tar or
216 standard Emacs.")
218 (defconst org-odt-manifest-file-entry-tag
219 "\n<manifest:file-entry manifest:media-type=\"%s\" manifest:full-path=\"%s\"%s/>")
221 (defconst org-odt-file-extensions
222 '(("odt" . "OpenDocument Text")
223 ("ott" . "OpenDocument Text Template")
224 ("odm" . "OpenDocument Master Document")
225 ("ods" . "OpenDocument Spreadsheet")
226 ("ots" . "OpenDocument Spreadsheet Template")
227 ("odg" . "OpenDocument Drawing (Graphics)")
228 ("otg" . "OpenDocument Drawing Template")
229 ("odp" . "OpenDocument Presentation")
230 ("otp" . "OpenDocument Presentation Template")
231 ("odi" . "OpenDocument Image")
232 ("odf" . "OpenDocument Formula")
233 ("odc" . "OpenDocument Chart")))
235 (defconst org-odt-table-style-format
237 <style:style style:name=\"%s\" style:family=\"table\">
238 <style:table-properties style:rel-width=\"%d%%\" fo:margin-top=\"0cm\" fo:margin-bottom=\"0.20cm\" table:align=\"center\"/>
239 </style:style>
241 "Template for auto-generated Table styles.")
243 (defvar org-odt-automatic-styles '()
244 "Registry of automatic styles for various OBJECT-TYPEs.
245 The variable has the following form:
246 \(\(OBJECT-TYPE-A
247 \(\(OBJECT-NAME-A.1 OBJECT-PROPS-A.1\)
248 \(OBJECT-NAME-A.2 OBJECT-PROPS-A.2\) ...\)\)
249 \(OBJECT-TYPE-B
250 \(\(OBJECT-NAME-B.1 OBJECT-PROPS-B.1\)
251 \(OBJECT-NAME-B.2 OBJECT-PROPS-B.2\) ...\)\)
252 ...\).
254 OBJECT-TYPEs could be \"Section\", \"Table\", \"Figure\" etc.
255 OBJECT-PROPS is (typically) a plist created by passing
256 \"#+ATTR_ODT: \" option to `org-odt-parse-block-attributes'.
258 Use `org-odt-add-automatic-style' to add update this variable.'")
260 (defvar org-odt-object-counters nil
261 "Running counters for various OBJECT-TYPEs.
262 Use this to generate automatic names and style-names. See
263 `org-odt-add-automatic-style'.")
265 (defvar org-odt-src-block-paragraph-format
266 "<style:style style:name=\"OrgSrcBlock\" style:family=\"paragraph\" style:parent-style-name=\"Preformatted_20_Text\">
267 <style:paragraph-properties fo:background-color=\"%s\" fo:padding=\"0.049cm\" fo:border=\"0.51pt solid #000000\" style:shadow=\"none\">
268 <style:background-image/>
269 </style:paragraph-properties>
270 <style:text-properties fo:color=\"%s\"/>
271 </style:style>"
272 "Custom paragraph style for colorized source and example blocks.
273 This style is much the same as that of \"OrgFixedWidthBlock\"
274 except that the foreground and background colors are set
275 according to the default face identified by the `htmlfontify'.")
277 (defvar hfy-optimisations)
278 (defvar org-odt-embedded-formulas-count 0)
279 (defvar org-odt-embedded-images-count 0)
280 (defvar org-odt-image-size-probe-method
281 (append (and (executable-find "identify") '(imagemagick)) ; See Bug#10675
282 '(emacs fixed))
283 "Ordered list of methods for determining image sizes.")
285 (defvar org-odt-default-image-sizes-alist
286 '(("as-char" . (5 . 0.4))
287 ("paragraph" . (5 . 5)))
288 "Hardcoded image dimensions one for each of the anchor
289 methods.")
291 ;; A4 page size is 21.0 by 29.7 cms
292 ;; The default page settings has 2cm margin on each of the sides. So
293 ;; the effective text area is 17.0 by 25.7 cm
294 (defvar org-odt-max-image-size '(17.0 . 20.0)
295 "Limiting dimensions for an embedded image.")
297 (defvar org-odt-category-map-alist
298 '((:TABLE: "Table" "Table" org-odt--enumerable-p )
299 (:FIGURE: "Illustration" "Figure" org-odt--enumerable-image-p )
300 (:MATH-FORMULA: "Text" "Equation" org-odt--enumerable-formula-p )
301 (:DVIPNG-IMAGE: "Equation" "Equation" org-odt--enumerable-latex-image-p)
302 (:LISTING: "Listing" "Listing" org-odt--enumerable-p ))
303 "Map a CATEGORY-HANDLE to OD-VARIABLE and LABEL-STYLE.
305 This is a list where each entry is of the form:
307 \(CATEGORY-HANDLE OD-VARIABLE CATEGORY-NAME ENUMERATOR-PREDICATE)
309 CATEGORY_HANDLE identifies the captionable entity in question.
311 OD-VARIABLE is the OpenDocument sequence counter associated with
312 the entity. These counters are declared within
313 \"<text:sequence-decls>...</text:sequence-decls>\" block of
314 `org-odt-content-template-file'.
316 CATEGORY-NAME is used for qualifying captions on export.
318 ENUMERATOR-PREDICATE is used for assigning a sequence number to
319 the entity. See `org-odt--enumerate'.")
321 (defvar org-odt-manifest-file-entries nil)
322 (defvar hfy-user-sheet-assoc)
324 (defvar org-odt-zip-dir nil
325 "Temporary work directory for OpenDocument exporter.")
329 ;;; User Configuration Variables
331 (defgroup org-export-odt nil
332 "Options for exporting Org mode files to ODT."
333 :tag "Org Export ODT"
334 :group 'org-export)
337 ;;;; Debugging
339 (defcustom org-odt-prettify-xml nil
340 "Specify whether or not the xml output should be prettified.
341 When this option is turned on, `indent-region' is run on all
342 component xml buffers before they are saved. Turn this off for
343 regular use. Turn this on if you need to examine the xml
344 visually."
345 :group 'org-export-odt
346 :version "24.1"
347 :type 'boolean)
350 ;;;; Document schema
352 (require 'rng-loc)
353 (defcustom org-odt-schema-dir
354 (let* ((schema-dir
355 (catch 'schema-dir
356 (message "Debug (ox-odt): Searching for OpenDocument schema files...")
357 (mapc
358 (lambda (schema-dir)
359 (when schema-dir
360 (message "Debug (ox-odt): Trying %s..." schema-dir)
361 (when (and (file-expand-wildcards
362 (expand-file-name "od-manifest-schema*.rnc"
363 schema-dir))
364 (file-expand-wildcards
365 (expand-file-name "od-schema*.rnc"
366 schema-dir))
367 (file-readable-p
368 (expand-file-name "schemas.xml" schema-dir)))
369 (message "Debug (ox-odt): Using schema files under %s"
370 schema-dir)
371 (throw 'schema-dir schema-dir))))
372 org-odt-schema-dir-list)
373 (message "Debug (ox-odt): No OpenDocument schema files installed")
374 nil)))
375 schema-dir)
376 "Directory that contains OpenDocument schema files.
378 This directory contains:
379 1. rnc files for OpenDocument schema
380 2. a \"schemas.xml\" file that specifies locating rules needed
381 for auto validation of OpenDocument XML files.
383 Use the customize interface to set this variable. This ensures
384 that `rng-schema-locating-files' is updated and auto-validation
385 of OpenDocument XML takes place based on the value
386 `rng-nxml-auto-validate-flag'.
388 The default value of this variable varies depending on the
389 version of org in use and is initialized from
390 `org-odt-schema-dir-list'. The OASIS schema files are available
391 only in the org's private git repository. It is *not* bundled
392 with GNU ELPA tar or standard Emacs distribution."
393 :type '(choice
394 (const :tag "Not set" nil)
395 (directory :tag "Schema directory"))
396 :group 'org-export-odt
397 :version "24.1"
398 :set
399 (lambda (var value)
400 "Set `org-odt-schema-dir'.
401 Also add it to `rng-schema-locating-files'."
402 (let ((schema-dir value))
403 (set var
404 (if (and
405 (file-expand-wildcards
406 (expand-file-name "od-manifest-schema*.rnc" schema-dir))
407 (file-expand-wildcards
408 (expand-file-name "od-schema*.rnc" schema-dir))
409 (file-readable-p
410 (expand-file-name "schemas.xml" schema-dir)))
411 schema-dir
412 (when value
413 (message "Error (ox-odt): %s has no OpenDocument schema files"
414 value))
415 nil)))
416 (when org-odt-schema-dir
417 (eval-after-load 'rng-loc
418 '(add-to-list 'rng-schema-locating-files
419 (expand-file-name "schemas.xml"
420 org-odt-schema-dir))))))
423 ;;;; Document styles
425 (defcustom org-odt-content-template-file nil
426 "Template file for \"content.xml\".
427 The exporter embeds the exported content just before
428 \"</office:text>\" element.
430 If unspecified, the file named \"OrgOdtContentTemplate.xml\"
431 under `org-odt-styles-dir' is used."
432 :type '(choice (const nil)
433 (file))
434 :group 'org-export-odt
435 :version "24.3")
437 (defcustom org-odt-styles-file nil
438 "Default styles file for use with ODT export.
439 Valid values are one of:
440 1. nil
441 2. path to a styles.xml file
442 3. path to a *.odt or a *.ott file
443 4. list of the form (ODT-OR-OTT-FILE (FILE-MEMBER-1 FILE-MEMBER-2
444 ...))
446 In case of option 1, an in-built styles.xml is used. See
447 `org-odt-styles-dir' for more information.
449 In case of option 3, the specified file is unzipped and the
450 styles.xml embedded therein is used.
452 In case of option 4, the specified ODT-OR-OTT-FILE is unzipped
453 and FILE-MEMBER-1, FILE-MEMBER-2 etc are copied in to the
454 generated odt file. Use relative path for specifying the
455 FILE-MEMBERS. styles.xml must be specified as one of the
456 FILE-MEMBERS.
458 Use options 1, 2 or 3 only if styles.xml alone suffices for
459 achieving the desired formatting. Use option 4, if the styles.xml
460 references additional files like header and footer images for
461 achieving the desired formatting.
463 Use \"#+ODT_STYLES_FILE: ...\" directive to set this variable on
464 a per-file basis. For example,
466 #+ODT_STYLES_FILE: \"/path/to/styles.xml\" or
467 #+ODT_STYLES_FILE: (\"/path/to/file.ott\" (\"styles.xml\" \"image/hdr.png\"))."
468 :group 'org-export-odt
469 :version "24.1"
470 :type
471 '(choice
472 (const :tag "Factory settings" nil)
473 (file :must-match t :tag "styles.xml")
474 (file :must-match t :tag "ODT or OTT file")
475 (list :tag "ODT or OTT file + Members"
476 (file :must-match t :tag "ODF Text or Text Template file")
477 (cons :tag "Members"
478 (file :tag " Member" "styles.xml")
479 (repeat (file :tag "Member"))))))
481 (defcustom org-odt-display-outline-level 2
482 "Outline levels considered for enumerating captioned entities."
483 :group 'org-export-odt
484 :version "24.4"
485 :package-version '(Org . "8.0")
486 :type 'integer)
488 ;;;; Document conversion
490 (defcustom org-odt-convert-processes
491 '(("LibreOffice"
492 "soffice --headless --convert-to %f%x --outdir %d %i")
493 ("unoconv"
494 "unoconv -f %f -o %d %i"))
495 "Specify a list of document converters and their usage.
496 The converters in this list are offered as choices while
497 customizing `org-odt-convert-process'.
499 This variable is a list where each element is of the
500 form (CONVERTER-NAME CONVERTER-CMD). CONVERTER-NAME is the name
501 of the converter. CONVERTER-CMD is the shell command for the
502 converter and can contain format specifiers. These format
503 specifiers are interpreted as below:
505 %i input file name in full
506 %I input file name as a URL
507 %f format of the output file
508 %o output file name in full
509 %O output file name as a URL
510 %d output dir in full
511 %D output dir as a URL.
512 %x extra options as set in `org-odt-convert-capabilities'."
513 :group 'org-export-odt
514 :version "24.1"
515 :type
516 '(choice
517 (const :tag "None" nil)
518 (alist :tag "Converters"
519 :key-type (string :tag "Converter Name")
520 :value-type (group (string :tag "Command line")))))
522 (defcustom org-odt-convert-process "LibreOffice"
523 "Use this converter to convert from \"odt\" format to other formats.
524 During customization, the list of converter names are populated
525 from `org-odt-convert-processes'."
526 :group 'org-export-odt
527 :version "24.1"
528 :type '(choice :convert-widget
529 (lambda (w)
530 (apply 'widget-convert (widget-type w)
531 (eval (car (widget-get w :args)))))
532 `((const :tag "None" nil)
533 ,@(mapcar (lambda (c)
534 `(const :tag ,(car c) ,(car c)))
535 org-odt-convert-processes))))
537 (defcustom org-odt-convert-capabilities
538 '(("Text"
539 ("odt" "ott" "doc" "rtf" "docx")
540 (("pdf" "pdf") ("odt" "odt") ("rtf" "rtf") ("ott" "ott")
541 ("doc" "doc" ":\"MS Word 97\"") ("docx" "docx") ("html" "html")
542 ("txt" "txt" ":\"Text (encoded)\"")))
543 ("Web"
544 ("html")
545 (("pdf" "pdf") ("odt" "odt") ("html" "html")))
546 ("Spreadsheet"
547 ("ods" "ots" "xls" "csv" "xlsx")
548 (("pdf" "pdf") ("ots" "ots") ("html" "html") ("csv" "csv") ("ods" "ods")
549 ("xls" "xls") ("xlsx" "xlsx")))
550 ("Presentation"
551 ("odp" "otp" "ppt" "pptx")
552 (("pdf" "pdf") ("swf" "swf") ("odp" "odp") ("otp" "otp") ("ppt" "ppt")
553 ("pptx" "pptx") ("odg" "odg"))))
554 "Specify input and output formats of `org-odt-convert-process'.
555 More correctly, specify the set of input and output formats that
556 the user is actually interested in.
558 This variable is an alist where each element is of the
559 form (DOCUMENT-CLASS INPUT-FMT-LIST OUTPUT-FMT-ALIST).
560 INPUT-FMT-LIST is a list of INPUT-FMTs. OUTPUT-FMT-ALIST is an
561 alist where each element is of the form (OUTPUT-FMT
562 OUTPUT-FILE-EXTENSION EXTRA-OPTIONS).
564 The variable is interpreted as follows:
565 `org-odt-convert-process' can take any document that is in
566 INPUT-FMT-LIST and produce any document that is in the
567 OUTPUT-FMT-LIST. A document converted to OUTPUT-FMT will have
568 OUTPUT-FILE-EXTENSION as the file name extension. OUTPUT-FMT
569 serves dual purposes:
570 - It is used for populating completion candidates during
571 `org-odt-convert' commands.
572 - It is used as the value of \"%f\" specifier in
573 `org-odt-convert-process'.
575 EXTRA-OPTIONS is used as the value of \"%x\" specifier in
576 `org-odt-convert-process'.
578 DOCUMENT-CLASS is used to group a set of file formats in
579 INPUT-FMT-LIST in to a single class.
581 Note that this variable inherently captures how LibreOffice based
582 converters work. LibreOffice maps documents of various formats
583 to classes like Text, Web, Spreadsheet, Presentation etc and
584 allow document of a given class (irrespective of its source
585 format) to be converted to any of the export formats associated
586 with that class.
588 See default setting of this variable for an typical
589 configuration."
590 :group 'org-export-odt
591 :version "24.1"
592 :type
593 '(choice
594 (const :tag "None" nil)
595 (alist :tag "Capabilities"
596 :key-type (string :tag "Document Class")
597 :value-type
598 (group (repeat :tag "Input formats" (string :tag "Input format"))
599 (alist :tag "Output formats"
600 :key-type (string :tag "Output format")
601 :value-type
602 (group (string :tag "Output file extension")
603 (choice
604 (const :tag "None" nil)
605 (string :tag "Extra options"))))))))
607 (defcustom org-odt-preferred-output-format nil
608 "Automatically post-process to this format after exporting to \"odt\".
609 Command `org-odt-export-to-odt' exports first to \"odt\" format
610 and then uses `org-odt-convert-process' to convert the
611 resulting document to this format. During customization of this
612 variable, the list of valid values are populated based on
613 `org-odt-convert-capabilities'.
615 You can set this option on per-file basis using file local
616 values. See Info node `(emacs) File Variables'."
617 :group 'org-export-odt
618 :version "24.1"
619 :type '(choice :convert-widget
620 (lambda (w)
621 (apply 'widget-convert (widget-type w)
622 (eval (car (widget-get w :args)))))
623 `((const :tag "None" nil)
624 ,@(mapcar (lambda (c)
625 `(const :tag ,c ,c))
626 (org-odt-reachable-formats "odt")))))
627 ;;;###autoload
628 (put 'org-odt-preferred-output-format 'safe-local-variable 'stringp)
631 ;;;; Drawers
633 (defcustom org-odt-format-drawer-function
634 (lambda (name contents) contents)
635 "Function called to format a drawer in ODT code.
637 The function must accept two parameters:
638 NAME the drawer name, like \"LOGBOOK\"
639 CONTENTS the contents of the drawer.
641 The function should return the string to be exported.
643 The default value simply returns the value of CONTENTS."
644 :group 'org-export-odt
645 :version "24.4"
646 :package-version '(Org . "8.3")
647 :type 'function)
650 ;;;; Headline
652 (defcustom org-odt-format-headline-function 'ignore
653 "Function to format headline text.
655 This function will be called with 5 arguments:
656 TODO the todo keyword \(string or nil\).
657 TODO-TYPE the type of todo \(symbol: `todo', `done', nil\)
658 PRIORITY the priority of the headline \(integer or nil\)
659 TEXT the main headline text \(string\).
660 TAGS the tags string, separated with colons \(string or nil\).
662 The function result will be used as headline text."
663 :group 'org-export-odt
664 :version "24.4"
665 :package-version '(Org . "8.0")
666 :type 'function)
669 ;;;; Inlinetasks
671 (defcustom org-odt-format-inlinetask-function 'ignore
672 "Function called to format an inlinetask in ODT code.
674 The function must accept six parameters:
675 TODO the todo keyword, as a string
676 TODO-TYPE the todo type, a symbol among `todo', `done' and nil.
677 PRIORITY the inlinetask priority, as a string
678 NAME the inlinetask name, as a string.
679 TAGS the inlinetask tags, as a string.
680 CONTENTS the contents of the inlinetask, as a string.
682 The function should return the string to be exported."
683 :group 'org-export-odt
684 :version "24.4"
685 :package-version '(Org . "8.0")
686 :type 'function)
689 ;;;; LaTeX
691 (defcustom org-odt-with-latex org-export-with-latex
692 "Non-nil means process LaTeX math snippets.
694 When set, the exporter will process LaTeX environments and
695 fragments.
697 This option can also be set with the +OPTIONS line,
698 e.g. \"tex:mathjax\". Allowed values are:
700 nil Ignore math snippets.
701 `verbatim' Keep everything in verbatim
702 `dvipng' Process the LaTeX fragments to images. This will also
703 include processing of non-math environments.
704 `imagemagick' Convert the LaTeX fragments to pdf files and use
705 imagemagick to convert pdf files to png files.
706 `mathjax' Do MathJax preprocessing and arrange for MathJax.js to
707 be loaded.
708 t Synonym for `mathjax'."
709 :group 'org-export-odt
710 :version "24.4"
711 :package-version '(Org . "8.0")
712 :type '(choice
713 (const :tag "Do not process math in any way" nil)
714 (const :tag "Use dvipng to make images" dvipng)
715 (const :tag "Use imagemagick to make images" imagemagick)
716 (const :tag "Use MathJax to display math" mathjax)
717 (const :tag "Leave math verbatim" verbatim)))
720 ;;;; Links
722 (defcustom org-odt-inline-formula-rules
723 '(("file" . "\\.\\(mathml\\|mml\\|odf\\)\\'"))
724 "Rules characterizing formula files that can be inlined into ODT.
726 A rule consists in an association whose key is the type of link
727 to consider, and value is a regexp that will be matched against
728 link's path."
729 :group 'org-export-odt
730 :version "24.4"
731 :package-version '(Org . "8.0")
732 :type '(alist :key-type (string :tag "Type")
733 :value-type (regexp :tag "Path")))
735 (defcustom org-odt-inline-image-rules
736 '(("file" . "\\.\\(jpeg\\|jpg\\|png\\|gif\\)\\'"))
737 "Rules characterizing image files that can be inlined into ODT.
739 A rule consists in an association whose key is the type of link
740 to consider, and value is a regexp that will be matched against
741 link's path."
742 :group 'org-export-odt
743 :version "24.4"
744 :package-version '(Org . "8.0")
745 :type '(alist :key-type (string :tag "Type")
746 :value-type (regexp :tag "Path")))
748 (defcustom org-odt-pixels-per-inch 96.0
749 "Scaling factor for converting images pixels to inches.
750 Use this for sizing of embedded images. See Info node `(org)
751 Images in ODT export' for more information."
752 :type 'float
753 :group 'org-export-odt
754 :version "24.4"
755 :package-version '(Org . "8.1"))
757 (defcustom org-odt-caption-and-xref-settings
758 '((:LISTING: :caption-position below :caption-format
759 (category " " counter ": " caption)
760 :xref-format
761 (value))
762 (:DVIPNG-IMAGE: :caption-position below :caption-format
763 (category " " counter ": " caption)
764 :xref-format
765 (value))
766 (:MATH-FORMULA: :caption-position below :caption-format
767 (caption)
768 :xref-format
769 (text)
770 :label-format
771 ("(" counter ")"))
772 (:FIGURE: :caption-position below :caption-format
773 (category " " counter ": " caption)
774 :xref-format
775 (value))
776 (:TABLE: :caption-position below :caption-format
777 (category " " counter ": " caption)
778 :xref-format
779 (value)))
780 "Specify how to format caption and cross-references.
782 Use this, for example, to control various aspects of caption (the
783 numbering format, its position etc.) or to generate page numbers
784 as part of cross-references. For a quick overview of this
785 variable, see examples towards the end of this docstring.
787 If you customize this option, the following text—\"[PLS. UPDATE
788 FIELDS]\"—is used as a placeholder for unresolvable
789 cross-reference fields (like page number etc). Use an external
790 application to synchronize these fields to their right values.
791 When using LibreOffice, use Tools -> Update-> Fields / Update
792 All.
794 This variable is an alist of pairs (RULE-TAG . RULE-PLIST).
795 RULE-TAG is a symbol. RULE-PLIST is a property list, the allowed
796 properties of which depend on the value of RULE-TAG. The details
797 are as below.
799 RULE-TAG takes following one of the values:
801 `:TABLE:' `:FIGURE:' `:MATH-FORMULA:' `:DVIPNG-IMAGE:'
802 `:LISTING:' `:TARGET:'.
804 The `:TARGET:' rule specifies how a cross-reference to a
805 HEADLINE, a TARGET or a non-captionable ELEMENT is typeset. Its
806 RULE-PLIST allow a single property `:xref-format'.
808 All RULE-TAGs (except for `:TARGET:') specify how a caption and a
809 cross-reference to the corresponding entity is typeset. Its
810 RULE-PLIST allow following properties.
812 `:caption-position' - a symbol - one of `above' or `below'
813 `:caption-format' - a mixed list of symbols and strings
814 `:xref-format' - a mixed list of symbols and strings
816 `:caption-format' and `:xref-format' are but format
817 specifiers (in disguise) and specify how a caption or a
818 cross-reference is transcoded. Their form and function are
819 better illustrated than described. So, consider the following
820 examples:
822 A `:caption-format' with the following value
824 (category \" \" counter \": \" caption)
826 will result in following caption.
828 Table 1: An Example Table
829 ^^^^^ ^ ^^^^^^^^^^^^^^^^
830 ^ | ^
831 | | |
832 category | caption
833 counter
835 A `:xref-format' with the following value
837 (\"Section \" chapter \" [\" text \"]\", \" page, \" t)
839 will result in following cross-reference.
841 See Section 3.1 [Tropical Storms], page 24.
842 ^ ^^^^^^^^^^^^^^^ ^^^
843 | | |
844 chapter no. chapter title page number
846 See `org-odt-link--infer-description' (specifically
847 `org-odt--xref-target') and `org-odt-format-label' for
848 implementation details."
849 :type
850 `(alist :options
851 ((:TARGET:
852 (plist :options
853 ((:xref-format
854 (choice
855 (const :tag "Simple page number" ("page " t))
856 (const :tag "TexInfo style"
857 ("Section " chapter " [" text "]," " page " t))
858 (repeat :tag "Format string"
859 (choice
860 (const :tag "Chapter" chapter)
861 (const :tag "Direction" direction)
862 (const :tag "Number" number)
863 (const :tag "Number (All superior)" number-all-superior)
864 (const :tag "Number (No superior)" number-no-superior)
865 (const :tag "Page" page)
866 (const :tag "Page style" t)
867 (const :tag "Text" text)
868 (string :tag "String" ""))))))))
869 ,@(mapcar
870 (lambda (dc)
871 `(,dc
872 (plist :options
873 ((:caption-position
874 (choice (const :tag "Below" below)
875 (const :tag "Above" above)))
876 (:caption-format
877 (repeat (choice
878 (const :tag "Category" category)
879 (const :tag "Counter" counter)
880 (const :tag "Caption" caption)
881 (string :tag "String" ""))))
882 (:xref-format
883 (repeat :tag "Format string"
884 (choice
885 (const :tag "Caption" caption)
886 (const :tag "Category & Value" category-and-value)
887 (const :tag "Chapter" chapter)
888 (const :tag "Direction" direction)
889 (const :tag "Page" page)
890 (const :tag "Text" text)
891 (const :tag "Value" value)
892 (string :tag "String" "")))))
894 '(:TABLE: :FIGURE: :MATH-FORMULA: :DVIPNG-IMAGE: :LISTING:))))
895 :group 'org-export-odt
896 :version "24.4")
898 ;;;; Lists
900 (defcustom org-odt-description-list-style #'org-odt--translate-description-lists/html
901 "Specify how description lists are rendered.
902 Choose one of HTML or LaTeX style."
903 :type '(choice
904 (const :tag "Use HTML style" org-odt--translate-description-lists/html )
905 (const :tag "Use LaTeX style" org-odt--translate-description-lists/latex ))
906 :group 'org-export-odt
907 :set (lambda (symbol value)
908 "Alias `org-odt--translate-description-lists'."
909 (set-default symbol value)
910 (fset 'org-odt--translate-description-lists value))
911 :version "24.1")
914 ;;;; Src Block
916 (defcustom org-odt-create-custom-styles-for-srcblocks t
917 "Whether custom styles for colorized source blocks be automatically created.
918 When this option is turned on, the exporter creates custom styles
919 for source blocks based on the advice of `htmlfontify'. Creation
920 of custom styles happen as part of `org-odt-hfy-face-to-css'.
922 When this option is turned off exporter does not create such
923 styles.
925 Use the latter option if you do not want the custom styles to be
926 based on your current display settings. It is necessary that the
927 styles.xml already contains needed styles for colorizing to work.
929 This variable is effective only if
930 `org-odt-fontify-srcblocks' is turned on."
931 :group 'org-export-odt
932 :version "24.1"
933 :type 'boolean)
935 (defcustom org-odt-fontify-srcblocks t
936 "Specify whether or not source blocks need to be fontified.
937 Turn this option on if you want to colorize the source code
938 blocks in the exported file. For colorization to work, you need
939 to make available an enhanced version of `htmlfontify' library."
940 :type 'boolean
941 :group 'org-export-odt
942 :version "24.1")
945 ;;;; Table
947 (defcustom org-odt-table-styles
948 '(("OrgEquation" "OrgEquation"
949 ((use-first-column-styles . t)
950 (use-last-column-styles . t)))
951 ("TableWithHeaderRowAndColumn" "Custom"
952 ((use-first-row-styles . t)
953 (use-first-column-styles . t)))
954 ("TableWithFirstRowandLastRow" "Custom"
955 ((use-first-row-styles . t)
956 (use-last-row-styles . t)))
957 ("GriddedTable" "Custom" nil))
958 "Specify how Table Styles should be derived from a Table Template.
959 This is a list where each element is of the
960 form (TABLE-STYLE-NAME TABLE-TEMPLATE-NAME TABLE-CELL-OPTIONS).
962 TABLE-STYLE-NAME is the style associated with the table through
963 \"#+ATTR_ODT: :style TABLE-STYLE-NAME\" line.
965 TABLE-TEMPLATE-NAME is a set of - upto 9 - automatic
966 TABLE-CELL-STYLE-NAMEs and PARAGRAPH-STYLE-NAMEs (as defined
967 below) that is included in
968 `org-odt-content-template-file'.
970 TABLE-CELL-STYLE-NAME := TABLE-TEMPLATE-NAME + TABLE-CELL-TYPE +
971 \"TableCell\"
972 PARAGRAPH-STYLE-NAME := TABLE-TEMPLATE-NAME + TABLE-CELL-TYPE +
973 \"TableParagraph\"
974 TABLE-CELL-TYPE := \"FirstRow\" | \"LastColumn\" |
975 \"FirstRow\" | \"LastRow\" |
976 \"EvenRow\" | \"OddRow\" |
977 \"EvenColumn\" | \"OddColumn\" | \"\"
978 where \"+\" above denotes string concatenation.
980 TABLE-CELL-OPTIONS is an alist where each element is of the
981 form (TABLE-CELL-STYLE-SELECTOR . ON-OR-OFF).
982 TABLE-CELL-STYLE-SELECTOR := `use-first-row-styles' |
983 `use-last-row-styles' |
984 `use-first-column-styles' |
985 `use-last-column-styles' |
986 `use-banding-rows-styles' |
987 `use-banding-columns-styles' |
988 `use-first-row-styles'
989 ON-OR-OFF := `t' | `nil'
991 For example, with the following configuration
993 \(setq org-odt-table-styles
994 '\(\(\"TableWithHeaderRowsAndColumns\" \"Custom\"
995 \(\(use-first-row-styles . t\)
996 \(use-first-column-styles . t\)\)\)
997 \(\"TableWithHeaderColumns\" \"Custom\"
998 \(\(use-first-column-styles . t\)\)\)\)\)
1000 1. A table associated with \"TableWithHeaderRowsAndColumns\"
1001 style will use the following table-cell styles -
1002 \"CustomFirstRowTableCell\", \"CustomFirstColumnTableCell\",
1003 \"CustomTableCell\" and the following paragraph styles
1004 \"CustomFirstRowTableParagraph\",
1005 \"CustomFirstColumnTableParagraph\", \"CustomTableParagraph\"
1006 as appropriate.
1008 2. A table associated with \"TableWithHeaderColumns\" style will
1009 use the following table-cell styles -
1010 \"CustomFirstColumnTableCell\", \"CustomTableCell\" and the
1011 following paragraph styles
1012 \"CustomFirstColumnTableParagraph\", \"CustomTableParagraph\"
1013 as appropriate..
1015 Note that TABLE-TEMPLATE-NAME corresponds to the
1016 \"<table:table-template>\" elements contained within
1017 \"<office:styles>\". The entries (TABLE-STYLE-NAME
1018 TABLE-TEMPLATE-NAME TABLE-CELL-OPTIONS) correspond to
1019 \"table:template-name\" and \"table:use-first-row-styles\" etc
1020 attributes of \"<table:table>\" element. Refer ODF-1.2
1021 specification for more information. Also consult the
1022 implementation filed under `org-odt-get-table-cell-styles'.
1024 The TABLE-STYLE-NAME \"OrgEquation\" is used internally for
1025 formatting of numbered display equations. Do not delete this
1026 style from the list."
1027 :group 'org-export-odt
1028 :version "24.1"
1029 :type '(choice
1030 (const :tag "None" nil)
1031 (repeat :tag "Table Styles"
1032 (list :tag "Table Style Specification"
1033 (string :tag "Table Style Name")
1034 (string :tag "Table Template Name")
1035 (alist :options (use-first-row-styles
1036 use-last-row-styles
1037 use-first-column-styles
1038 use-last-column-styles
1039 use-banding-rows-styles
1040 use-banding-columns-styles)
1041 :key-type symbol
1042 :value-type (const :tag "True" t))))))
1044 ;;;; Timestamps
1046 (defcustom org-odt-use-date-fields nil
1047 "Non-nil, if timestamps should be exported as date fields.
1049 When nil, export timestamps as plain text.
1051 When non-nil, map `org-time-stamp-custom-formats' to a pair of
1052 OpenDocument date-styles with names \"OrgDate1\" and \"OrgDate2\"
1053 respectively. A timestamp with no time component is formatted
1054 with style \"OrgDate1\" while one with explicit hour and minutes
1055 is formatted with style \"OrgDate2\".
1057 This feature is experimental. Most (but not all) of the common
1058 %-specifiers in `format-time-string' are supported.
1059 Specifically, locale-dependent specifiers like \"%c\", \"%x\" are
1060 formatted as canonical Org timestamps. For finer control, avoid
1061 these %-specifiers.
1063 Textual specifiers like \"%b\", \"%h\", \"%B\", \"%a\", \"%A\"
1064 etc., are displayed by the application in the default language
1065 and country specified in `org-odt-styles-file'. Note that the
1066 default styles file uses language \"en\" and country \"GB\". You
1067 can localize the week day and month strings in the exported
1068 document by setting the default language and country either using
1069 the application UI or through a custom styles file.
1071 See `org-odt--build-date-styles' for implementation details."
1072 :group 'org-export-odt
1073 :version "24.4"
1074 :package-version '(Org . "8.0")
1075 :type 'boolean)
1079 ;;; Internal functions
1081 ;;;; Date
1083 (defun org-odt--format-timestamp (timestamp &optional end iso-date-p)
1084 (let* ((format-timestamp
1085 (lambda (timestamp format &optional end utc)
1086 (if timestamp
1087 (org-timestamp-format timestamp format end utc)
1088 (format-time-string format nil utc))))
1089 (has-time-p (or (not timestamp)
1090 (org-timestamp-has-time-p timestamp)))
1091 (iso-date (let ((format (if has-time-p "%Y-%m-%dT%H:%M:%S"
1092 "%Y-%m-%dT%H:%M:%S")))
1093 (funcall format-timestamp timestamp format end))))
1094 (if iso-date-p iso-date
1095 (let* ((style (if has-time-p "OrgDate2" "OrgDate1"))
1096 ;; LibreOffice does not care about end goes as content
1097 ;; within the "<text:date>...</text:date>" field. The
1098 ;; displayed date is automagically corrected to match the
1099 ;; format requested by "style:data-style-name" attribute. So
1100 ;; don't bother about formatting the date contents to be
1101 ;; compatible with "OrgDate1" and "OrgDateTime" styles. A
1102 ;; simple Org-style date should suffice.
1103 (date (let* ((formats
1104 (if org-display-custom-times
1105 (cons (substring
1106 (car org-time-stamp-custom-formats) 1 -1)
1107 (substring
1108 (cdr org-time-stamp-custom-formats) 1 -1))
1109 '("%Y-%m-%d %a" . "%Y-%m-%d %a %H:%M")))
1110 (format (if has-time-p (cdr formats) (car formats))))
1111 (funcall format-timestamp timestamp format end)))
1112 (repeater (let ((repeater-type (org-element-property
1113 :repeater-type timestamp))
1114 (repeater-value (org-element-property
1115 :repeater-value timestamp))
1116 (repeater-unit (org-element-property
1117 :repeater-unit timestamp)))
1118 (concat
1119 (case repeater-type
1120 (catchup "++") (restart ".+") (cumulate "+"))
1121 (when repeater-value
1122 (number-to-string repeater-value))
1123 (case repeater-unit
1124 (hour "h") (day "d") (week "w") (month "m")
1125 (year "y"))))))
1126 (concat
1127 (format "<text:date text:date-value=\"%s\" style:data-style-name=\"%s\" text:fixed=\"true\">%s</text:date>"
1128 iso-date style date)
1129 (and (not (string= repeater "")) " ")
1130 repeater)))))
1132 ;;;; Frame
1134 (defun org-odt--frame (text width height style &optional extra
1135 anchor-type &rest title-and-desc)
1136 (let* ((frame-name (car (org-odt-add-automatic-style "Frame")))
1137 (frame-attrs
1138 (concat
1139 (if width (format " svg:width=\"%0.2fcm\"" width) "")
1140 (if height (format " svg:height=\"%0.2fcm\"" height) "")
1141 extra
1142 (format " text:anchor-type=\"%s\"" (or anchor-type "paragraph"))
1143 (format " draw:name=\"%s\"" frame-name))))
1144 (format
1145 "\n<draw:frame draw:style-name=\"%s\"%s>\n%s\n</draw:frame>"
1146 style frame-attrs
1147 (concat text
1148 (let ((title (car title-and-desc))
1149 (desc (cadr title-and-desc)))
1150 (concat (when title
1151 (format "<svg:title>%s</svg:title>"
1152 (org-odt--encode-plain-text title t)))
1153 (when desc
1154 (format "<svg:desc>%s</svg:desc>"
1155 (org-odt--encode-plain-text desc t)))))))))
1158 ;;;; Library wrappers :: Arc Mode
1160 (defun org-odt--zip-extract (archive members target)
1161 (when (atom members) (setq members (list members)))
1162 (mapc (lambda (member)
1163 (require 'arc-mode)
1164 (let* ((--quote-file-name
1165 ;; This is shamelessly stolen from `archive-zip-extract'.
1166 (lambda (name)
1167 (if (or (not (memq system-type '(windows-nt ms-dos)))
1168 (and (boundp 'w32-quote-process-args)
1169 (null w32-quote-process-args)))
1170 (shell-quote-argument name)
1171 name)))
1172 (target (funcall --quote-file-name target))
1173 (archive (expand-file-name archive))
1174 (archive-zip-extract
1175 (list "unzip" "-qq" "-o" "-d" target))
1176 exit-code command-output)
1177 (setq command-output
1178 (with-temp-buffer
1179 (setq exit-code (archive-zip-extract archive member))
1180 (buffer-string)))
1181 (unless (zerop exit-code)
1182 (message command-output)
1183 (error "Extraction failed"))))
1184 members))
1187 ;;;; Library wrappers :: Ox
1189 (defun org-odt--read-attribute (element property)
1190 (let* ((attrs (org-export-read-attribute :attr_odt element))
1191 (value (plist-get attrs property)))
1192 (and value (ignore-errors (read value)))))
1195 ;;;; Target
1197 (defun org-odt--target (text label)
1198 (cond
1199 ;; Empty label.
1200 ((not (and label (org-string-nw-p label))) text)
1201 ;; Bookmark pointing to a range of text.
1202 ((and text (not (string= text "")))
1203 (concat (format "\n<text:bookmark-start text:name=\"%s\"/>" label) text
1204 (format "\n<text:bookmark-end text:name=\"%s\"/>" label)))
1205 ;; Bookmark at a location.
1206 (t (format "\n<text:bookmark text:name=\"%s\"/>" label))))
1208 (defun org-odt--xref-target (category text label)
1209 (let* ((xref-format (plist-get
1210 (assoc-default category
1211 org-odt-caption-and-xref-settings)
1212 :xref-format)))
1213 (when xref-format
1214 (mapconcat
1215 (lambda (%)
1216 (cond
1217 ((stringp %) %)
1218 ((eq t %)
1219 (format "<text:bookmark-ref text:ref-name=\"%s\">%s</text:bookmark-ref>"
1220 label text))
1221 ((symbolp %)
1222 (format "<text:bookmark-ref text:reference-format=\"%s\" text:ref-name=\"%s\">%s</text:bookmark-ref>"
1223 % label text))))
1224 xref-format ""))))
1226 ;;;; Textbox
1228 (defun org-odt--textbox (text width height style &optional
1229 extra anchor-type)
1230 (org-odt--frame
1231 (format "\n<draw:text-box %s>%s\n</draw:text-box>"
1232 (concat (format " fo:min-height=\"%0.2fcm\"" (or height .2))
1233 (and (not width)
1234 (format " fo:min-width=\"%0.2fcm\"" (or width .2))))
1235 text)
1236 width nil style extra anchor-type))
1240 ;;;; Table of Contents
1242 (defun org-odt-begin-toc (index-title depth)
1243 (concat
1244 (format "
1245 <text:table-of-content text:style-name=\"OrgIndexSection\" text:protected=\"true\" text:name=\"Table of Contents\">
1246 <text:table-of-content-source text:outline-level=\"%d\">
1247 <text:index-title-template text:style-name=\"Contents_20_Heading\">%s</text:index-title-template>
1248 " depth index-title)
1250 (let ((levels (number-sequence 1 10)))
1251 (mapconcat
1252 (lambda (level)
1253 (format
1255 <text:table-of-content-entry-template text:outline-level=\"%d\" text:style-name=\"Contents_20_%d\">
1256 <text:index-entry-link-start text:style-name=\"Internet_20_link\"/>
1257 <text:index-entry-chapter/>
1258 <text:index-entry-text/>
1259 <text:index-entry-link-end/>
1260 </text:table-of-content-entry-template>
1261 " level level)) levels ""))
1263 (format "
1264 </text:table-of-content-source>
1266 <text:index-body>
1267 <text:index-title text:style-name=\"Sect1\" text:name=\"Table of Contents1_Head\">
1268 <text:p text:style-name=\"Contents_20_Heading\">%s</text:p>
1269 </text:index-title>
1270 " index-title)))
1272 (defun org-odt-end-toc ()
1273 (format "
1274 </text:index-body>
1275 </text:table-of-content>
1278 (defun* org-odt-format-toc-headline
1279 (todo todo-type priority text tags
1280 &key level section-number headline-label &allow-other-keys)
1281 (setq text
1282 (concat
1283 ;; Section number.
1284 (when section-number (concat section-number ". "))
1285 ;; Todo.
1286 (when todo
1287 (let ((style (if (member todo org-done-keywords)
1288 "OrgDone" "OrgTodo")))
1289 (format "<text:span text:style-name=\"%s\">%s</text:span> "
1290 style todo)))
1291 (when priority
1292 (let* ((style (format "OrgPriority-%s" priority))
1293 (priority (format "[#%c]" priority)))
1294 (format "<text:span text:style-name=\"%s\">%s</text:span> "
1295 style priority)))
1296 ;; Title.
1297 text
1298 ;; Tags.
1299 (when tags
1300 (concat
1301 (format " <text:span text:style-name=\"%s\">[%s]</text:span>"
1302 "OrgTags"
1303 (mapconcat
1304 (lambda (tag)
1305 (format
1306 "<text:span text:style-name=\"%s\">%s</text:span>"
1307 "OrgTag" tag)) tags " : "))))))
1308 (format "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
1309 headline-label text))
1311 (defun org-odt-toc (depth info)
1312 (assert (wholenump depth))
1313 ;; When a headline is marked as a radio target, as in the example below:
1315 ;; ** <<<Some Heading>>>
1316 ;; Some text.
1318 ;; suppress generation of radio targets. i.e., Radio targets are to
1319 ;; be marked as targets within /document body/ and *not* within
1320 ;; /TOC/, as otherwise there will be duplicated anchors one in TOC
1321 ;; and one in the document body.
1323 ;; FIXME-1: Currently exported headings are memoized. `org-export.el'
1324 ;; doesn't provide a way to disable memoization. So this doesn't
1325 ;; work.
1327 ;; FIXME-2: Are there any other objects that need to be suppressed
1328 ;; within TOC?
1329 (let* ((title (org-export-translate "Table of Contents" :utf-8 info))
1330 (headlines (org-export-collect-headlines
1331 info (and (wholenump depth) depth)))
1332 (backend (org-export-create-backend
1333 :parent (org-export-backend-name
1334 (plist-get info :back-end))
1335 :transcoders (mapcar
1336 (lambda (type) (cons type (lambda (d c i) c)))
1337 (list 'radio-target)))))
1338 (when headlines
1339 (concat
1340 (org-odt-begin-toc title depth)
1341 (mapconcat
1342 (lambda (headline)
1343 (let* ((entry (org-odt-format-headline--wrap
1344 headline backend info 'org-odt-format-toc-headline))
1345 (level (org-export-get-relative-level headline info))
1346 (style (format "Contents_20_%d" level)))
1347 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1348 style entry)))
1349 headlines "\n")
1350 (org-odt-end-toc)))))
1353 ;;;; Document styles
1355 (defun org-odt-add-automatic-style (object-type &optional object-props)
1356 "Create an automatic style of type OBJECT-TYPE with param OBJECT-PROPS.
1357 OBJECT-PROPS is (typically) a plist created by passing
1358 \"#+ATTR_ODT: \" option of the object in question to
1359 `org-odt-parse-block-attributes'.
1361 Use `org-odt-object-counters' to generate an automatic
1362 OBJECT-NAME and STYLE-NAME. If OBJECT-PROPS is non-nil, add a
1363 new entry in `org-odt-automatic-styles'. Return (OBJECT-NAME
1364 . STYLE-NAME)."
1365 (assert (stringp object-type))
1366 (let* ((object (intern object-type))
1367 (seqvar object)
1368 (seqno (1+ (or (plist-get org-odt-object-counters seqvar) 0)))
1369 (object-name (format "%s%d" object-type seqno)) style-name)
1370 (setq org-odt-object-counters
1371 (plist-put org-odt-object-counters seqvar seqno))
1372 (when object-props
1373 (setq style-name (format "Org%s" object-name))
1374 (setq org-odt-automatic-styles
1375 (plist-put org-odt-automatic-styles object
1376 (append (list (list style-name object-props))
1377 (plist-get org-odt-automatic-styles object)))))
1378 (cons object-name style-name)))
1380 ;;;; Checkbox
1382 (defun org-odt--checkbox (item)
1383 "Return check-box string associated to ITEM."
1384 (let ((checkbox (org-element-property :checkbox item)))
1385 (if (not checkbox) ""
1386 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1387 "OrgCode" (case checkbox
1388 (on "[&#x2713;] ") ; CHECK MARK
1389 (off "[ ] ")
1390 (trans "[-] "))))))
1392 ;;; Template
1394 (defun org-odt--build-date-styles (fmt style)
1395 ;; In LibreOffice 3.4.6, there doesn't seem to be a convenient way
1396 ;; to modify the date fields. A date could be modified by
1397 ;; offsetting in days. That's about it. Also, date and time may
1398 ;; have to be emitted as two fields - a date field and a time field
1399 ;; - separately.
1401 ;; One can add Form Controls to date and time fields so that they
1402 ;; can be easily modified. But then, the exported document will
1403 ;; become tightly coupled with LibreOffice and may not function
1404 ;; properly with other OpenDocument applications.
1406 ;; I have a strange feeling that Date styles are a bit flaky at the
1407 ;; moment.
1409 ;; The feature is experimental.
1410 (when (and fmt style)
1411 (let* ((fmt-alist
1412 '(("%A" . "<number:day-of-week number:style=\"long\"/>")
1413 ("%B" . "<number:month number:textual=\"true\" number:style=\"long\"/>")
1414 ("%H" . "<number:hours number:style=\"long\"/>")
1415 ("%M" . "<number:minutes number:style=\"long\"/>")
1416 ("%S" . "<number:seconds number:style=\"long\"/>")
1417 ("%V" . "<number:week-of-year/>")
1418 ("%Y" . "<number:year number:style=\"long\"/>")
1419 ("%a" . "<number:day-of-week number:style=\"short\"/>")
1420 ("%b" . "<number:month number:textual=\"true\" number:style=\"short\"/>")
1421 ("%d" . "<number:day number:style=\"long\"/>")
1422 ("%e" . "<number:day number:style=\"short\"/>")
1423 ("%h" . "<number:month number:textual=\"true\" number:style=\"short\"/>")
1424 ("%k" . "<number:hours number:style=\"short\"/>")
1425 ("%m" . "<number:month number:style=\"long\"/>")
1426 ("%p" . "<number:am-pm/>")
1427 ("%y" . "<number:year number:style=\"short\"/>")))
1428 (case-fold-search nil)
1429 (re (mapconcat 'identity (mapcar 'car fmt-alist) "\\|"))
1430 match rpl (start 0) (filler-beg 0) filler-end filler output)
1431 (mapc
1432 (lambda (pair)
1433 (setq fmt (replace-regexp-in-string (car pair) (cdr pair) fmt t t)))
1434 '(("\\(?:%[[:digit:]]*N\\)" . "") ; strip ns, us and ns
1435 ("%C" . "Y") ; replace century with year
1436 ("%D" . "%m/%d/%y")
1437 ("%G" . "Y") ; year corresponding to iso week
1438 ("%I" . "%H") ; hour on a 12-hour clock
1439 ("%R" . "%H:%M")
1440 ("%T" . "%H:%M:%S")
1441 ("%U\\|%W" . "%V") ; week no. starting on Sun./Mon.
1442 ("%Z" . "") ; time zone name
1443 ("%c" . "%Y-%M-%d %a %H:%M" ) ; locale's date and time format
1444 ("%g" . "%y")
1445 ("%X" . "%x" ) ; locale's pref. time format
1446 ("%j" . "") ; day of the year
1447 ("%l" . "%k") ; like %I blank-padded
1448 ("%s" . "") ; no. of secs since 1970-01-01 00:00:00 +0000
1449 ("%n" . "<text:line-break/>")
1450 ("%r" . "%I:%M:%S %p")
1451 ("%t" . "<text:tab/>")
1452 ("%u\\|%w" . "") ; numeric day of week - Mon (1-7), Sun(0-6)
1453 ("%x" . "%Y-%M-%d %a") ; locale's pref. time format
1454 ("%z" . "") ; time zone in numeric form
1456 (while (string-match re fmt start)
1457 (setq match (match-string 0 fmt))
1458 (setq rpl (assoc-default match fmt-alist))
1459 (setq start (match-end 0))
1460 (setq filler-end (match-beginning 0))
1461 (setq filler (substring fmt (prog1 filler-beg
1462 (setq filler-beg (match-end 0)))
1463 filler-end))
1464 (setq filler (and (not (string= filler ""))
1465 (format "<number:text>%s</number:text>"
1466 (org-odt--encode-plain-text filler))))
1467 (setq output (concat output "\n" filler "\n" rpl)))
1468 (setq filler (substring fmt filler-beg))
1469 (unless (string= filler "")
1470 (setq output (concat output
1471 (format "\n<number:text>%s</number:text>"
1472 (org-odt--encode-plain-text filler)))))
1473 (format "\n<number:date-style style:name=\"%s\" %s>%s\n</number:date-style>"
1474 style
1475 (concat " number:automatic-order=\"true\""
1476 " number:format-source=\"fixed\"")
1477 output ))))
1479 (defun org-odt-template (contents info)
1480 "Return complete document string after ODT conversion.
1481 CONTENTS is the transcoded contents string. RAW-DATA is the
1482 original parsed data. INFO is a plist holding export options."
1483 ;; Write meta file.
1484 (let ((title (org-export-data (plist-get info :title) info))
1485 (author (let ((author (plist-get info :author)))
1486 (if (not author) "" (org-export-data author info))))
1487 (email (plist-get info :email))
1488 (keywords (plist-get info :keywords))
1489 (description (plist-get info :description)))
1490 (write-region
1491 (concat
1492 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
1493 <office:document-meta
1494 xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"
1495 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
1496 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
1497 xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"
1498 xmlns:ooo=\"http://openoffice.org/2004/office\"
1499 office:version=\"1.2\">
1500 <office:meta>\n"
1501 (format "<dc:creator>%s</dc:creator>\n" author)
1502 (format "<meta:initial-creator>%s</meta:initial-creator>\n" author)
1503 ;; Date, if required.
1504 (when (plist-get info :with-date)
1505 ;; Check if DATE is specified as an Org-timestamp. If yes,
1506 ;; include it as meta information. Otherwise, just use
1507 ;; today's date.
1508 (let* ((date (let ((date (plist-get info :date)))
1509 (and (not (cdr date))
1510 (eq (org-element-type (car date)) 'timestamp)
1511 (car date)))))
1512 (let ((iso-date (org-odt--format-timestamp date nil 'iso-date)))
1513 (concat
1514 (format "<dc:date>%s</dc:date>\n" iso-date)
1515 (format "<meta:creation-date>%s</meta:creation-date>\n"
1516 iso-date)))))
1517 (format "<meta:generator>%s</meta:generator>\n"
1518 (let ((creator-info (plist-get info :with-creator)))
1519 (if (or (not creator-info) (eq creator-info 'comment)) ""
1520 (plist-get info :creator))))
1521 (format "<meta:keyword>%s</meta:keyword>\n" keywords)
1522 (format "<dc:subject>%s</dc:subject>\n" description)
1523 (when (org-string-nw-p title)
1524 (format "<dc:title>%s</dc:title>\n" title))
1525 "\n"
1526 " </office:meta>\n" "</office:document-meta>")
1527 nil (concat org-odt-zip-dir "meta.xml"))
1528 ;; Add meta.xml in to manifest.
1529 (org-odt-create-manifest-file-entry "text/xml" "meta.xml"))
1531 ;; Update styles file.
1532 ;; Copy styles.xml. Also dump htmlfontify styles, if there is any.
1533 ;; Write styles file.
1534 (let* ((styles-file (plist-get info :odt-styles-file))
1535 (styles-file (and styles-file (read (org-trim styles-file))))
1536 ;; Non-availability of styles.xml is not a critical
1537 ;; error. For now, throw an error.
1538 (styles-file (or styles-file
1539 org-odt-styles-file
1540 (expand-file-name "OrgOdtStyles.xml"
1541 org-odt-styles-dir)
1542 (error "org-odt: Missing styles file?"))))
1543 (cond
1544 ((listp styles-file)
1545 (let ((archive (nth 0 styles-file))
1546 (members (nth 1 styles-file)))
1547 (org-odt--zip-extract archive members org-odt-zip-dir)
1548 (mapc
1549 (lambda (member)
1550 (when (org-file-image-p member)
1551 (let* ((image-type (file-name-extension member))
1552 (media-type (format "image/%s" image-type)))
1553 (org-odt-create-manifest-file-entry media-type member))))
1554 members)))
1555 ((and (stringp styles-file) (file-exists-p styles-file))
1556 (let ((styles-file-type (file-name-extension styles-file)))
1557 (cond
1558 ((string= styles-file-type "xml")
1559 (copy-file styles-file (concat org-odt-zip-dir "styles.xml") t))
1560 ((member styles-file-type '("odt" "ott"))
1561 (org-odt--zip-extract styles-file "styles.xml" org-odt-zip-dir)))))
1563 (error (format "Invalid specification of styles.xml file: %S"
1564 org-odt-styles-file))))
1566 ;; create a manifest entry for styles.xml
1567 (org-odt-create-manifest-file-entry "text/xml" "styles.xml")
1569 ;; FIXME: Who is opening an empty styles.xml before this point?
1570 (with-current-buffer
1571 (find-file-noselect (concat org-odt-zip-dir "styles.xml") t)
1572 (revert-buffer t t)
1574 ;; Write custom styles for source blocks
1575 ;; Save STYLES used for colorizing of source blocks.
1576 ;; Update styles.xml with styles that were collected as part of
1577 ;; `org-odt-hfy-face-to-css' callbacks.
1578 (let ((styles (mapconcat (lambda (style) (format " %s\n" (cddr style)))
1579 hfy-user-sheet-assoc "")))
1580 (when styles
1581 (goto-char (point-min))
1582 (when (re-search-forward "</office:styles>" nil t)
1583 (goto-char (match-beginning 0))
1584 (insert "\n<!-- Org Htmlfontify Styles -->\n" styles "\n"))))
1586 ;; Update styles.xml - take care of outline numbering
1588 ;; Don't make automatic backup of styles.xml file. This setting
1589 ;; prevents the backed-up styles.xml file from being zipped in to
1590 ;; odt file. This is more of a hackish fix. Better alternative
1591 ;; would be to fix the zip command so that the output odt file
1592 ;; includes only the needed files and excludes any auto-generated
1593 ;; extra files like backups and auto-saves etc etc. Note that
1594 ;; currently the zip command zips up the entire temp directory so
1595 ;; that any auto-generated files created under the hood ends up in
1596 ;; the resulting odt file.
1597 (set (make-local-variable 'backup-inhibited) t)
1599 ;; Outline numbering is retained only upto LEVEL.
1600 ;; To disable outline numbering pass a LEVEL of 0.
1602 (goto-char (point-min))
1603 (let ((regex
1604 "<text:outline-level-style\\([^>]*\\)text:level=\"\\([^\"]*\\)\"\\([^>]*\\)>")
1605 (replacement
1606 "<text:outline-level-style\\1text:level=\"\\2\" style:num-format=\"\">"))
1607 (while (re-search-forward regex nil t)
1608 (unless (let ((sec-num (plist-get info :section-numbers))
1609 (level (string-to-number (match-string 2))))
1610 (if (wholenump sec-num) (<= level sec-num) sec-num))
1611 (replace-match replacement t nil))))
1612 (save-buffer 0)))
1613 ;; Update content.xml.
1615 (let* ( ;; `org-display-custom-times' should be accessed right
1616 ;; within the context of the Org buffer. So obtain its
1617 ;; value before moving on to temp-buffer context down below.
1618 (custom-time-fmts
1619 (if org-display-custom-times
1620 (cons (substring (car org-time-stamp-custom-formats) 1 -1)
1621 (substring (cdr org-time-stamp-custom-formats) 1 -1))
1622 '("%Y-%M-%d %a" . "%Y-%M-%d %a %H:%M"))))
1623 (with-temp-buffer
1624 (insert-file-contents
1625 (or org-odt-content-template-file
1626 (expand-file-name "OrgOdtContentTemplate.xml"
1627 org-odt-styles-dir)))
1628 ;; Write automatic styles.
1629 ;; - Position the cursor.
1630 (goto-char (point-min))
1631 (re-search-forward " </office:automatic-styles>" nil t)
1632 (goto-char (match-beginning 0))
1633 ;; - Dump automatic table styles.
1634 (loop for (style-name props) in
1635 (plist-get org-odt-automatic-styles 'Table) do
1636 (when (setq props (or (let ((value (plist-get props :rel-width)))
1637 (and value (ignore-errors (read value)))) 96))
1638 (insert (format org-odt-table-style-format style-name props))))
1639 ;; - Dump date-styles.
1640 (when org-odt-use-date-fields
1641 (insert (org-odt--build-date-styles (car custom-time-fmts)
1642 "OrgDate1")
1643 (org-odt--build-date-styles (cdr custom-time-fmts)
1644 "OrgDate2")))
1645 ;; Update display level.
1646 ;; - Remove existing sequence decls. Also position the cursor.
1647 (goto-char (point-min))
1648 (when (re-search-forward "<text:sequence-decls" nil t)
1649 (delete-region (match-beginning 0)
1650 (re-search-forward "</text:sequence-decls>" nil nil)))
1651 ;; Update sequence decls according to user preference.
1652 (insert
1653 (format
1654 "\n<text:sequence-decls>\n%s\n</text:sequence-decls>"
1655 (mapconcat
1656 (lambda (x)
1657 (format
1658 "<text:sequence-decl text:display-outline-level=\"%d\" text:name=\"%s\"/>"
1659 org-odt-display-outline-level (nth 1 x)))
1660 org-odt-category-map-alist "\n")))
1661 ;; Position the cursor to document body.
1662 (goto-char (point-min))
1663 (re-search-forward "</office:text>" nil nil)
1664 (goto-char (match-beginning 0))
1666 ;; Preamble - Title, Author, Date etc.
1667 (insert
1668 (let* ((title (org-export-data (plist-get info :title) info))
1669 (author (and (plist-get info :with-author)
1670 (let ((auth (plist-get info :author)))
1671 (and auth (org-export-data auth info)))))
1672 (email (plist-get info :email))
1673 ;; Switch on or off above vars based on user settings
1674 (author (and (plist-get info :with-author) (or author email)))
1675 (email (and (plist-get info :with-email) email)))
1676 (concat
1677 ;; Title.
1678 (when (org-string-nw-p title)
1679 (concat
1680 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1681 "OrgTitle" (format "\n<text:title>%s</text:title>" title))
1682 ;; Separator.
1683 "\n<text:p text:style-name=\"OrgTitle\"/>"))
1684 (cond
1685 ((and author (not email))
1686 ;; Author only.
1687 (concat
1688 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1689 "OrgSubtitle"
1690 (format "<text:initial-creator>%s</text:initial-creator>" author))
1691 ;; Separator.
1692 "\n<text:p text:style-name=\"OrgSubtitle\"/>"))
1693 ((and author email)
1694 ;; Author and E-mail.
1695 (concat
1696 (format
1697 "\n<text:p text:style-name=\"%s\">%s</text:p>"
1698 "OrgSubtitle"
1699 (format
1700 "<text:a xlink:type=\"simple\" xlink:href=\"%s\">%s</text:a>"
1701 (concat "mailto:" email)
1702 (format "<text:initial-creator>%s</text:initial-creator>" author)))
1703 ;; Separator.
1704 "\n<text:p text:style-name=\"OrgSubtitle\"/>")))
1705 ;; Date, if required.
1706 (when (plist-get info :with-date)
1707 (let* ((date (plist-get info :date))
1708 ;; Check if DATE is specified as a timestamp.
1709 (timestamp (and (not (cdr date))
1710 (eq (org-element-type (car date)) 'timestamp)
1711 (car date))))
1712 (concat
1713 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1714 "OrgSubtitle"
1715 (if (and org-odt-use-date-fields timestamp)
1716 (org-odt--format-timestamp (car date))
1717 (org-export-data (plist-get info :date) info)))
1718 ;; Separator
1719 "<text:p text:style-name=\"OrgSubtitle\"/>"))))))
1720 ;; Table of Contents
1721 (let* ((with-toc (plist-get info :with-toc))
1722 (depth (and with-toc (if (wholenump with-toc)
1723 with-toc
1724 (plist-get info :headline-levels)))))
1725 (when depth (insert (or (org-odt-toc depth info) ""))))
1726 ;; Contents.
1727 (insert contents)
1728 ;; Return contents.
1729 (buffer-substring-no-properties (point-min) (point-max)))))
1733 ;;; Transcode Functions
1735 ;;;; Bold
1737 (defun org-odt-bold (bold contents info)
1738 "Transcode BOLD from Org to ODT.
1739 CONTENTS is the text with bold markup. INFO is a plist holding
1740 contextual information."
1741 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1742 ;; Internally, `org-odt--translate-description-lists/html'
1743 ;; or `org-odt--translate-description-lists/latex' requests
1744 ;; a custom style for bold.
1745 (or (org-element-property :style bold) "Bold")
1746 contents))
1749 ;;;; Center Block
1751 (defun org-odt-center-block (center-block contents info)
1752 "Transcode a CENTER-BLOCK element from Org to ODT.
1753 CONTENTS holds the contents of the center block. INFO is a plist
1754 holding contextual information."
1755 contents)
1758 ;;;; Clock
1760 (defun org-odt-clock (clock contents info)
1761 "Transcode a CLOCK element from Org to ODT.
1762 CONTENTS is nil. INFO is a plist used as a communication
1763 channel."
1764 (let ((timestamp (org-element-property :value clock))
1765 (duration (org-element-property :duration clock)))
1766 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1767 (if (eq (org-element-type (org-export-get-next-element clock info))
1768 'clock) "OrgClock" "OrgClockLastLine")
1769 (concat
1770 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1771 "OrgClockKeyword" org-clock-string)
1772 (org-odt-timestamp timestamp contents info)
1773 (and duration (format " (%s)" duration))))))
1776 ;;;; Code
1778 (defun org-odt-code (code contents info)
1779 "Transcode a CODE object from Org to ODT.
1780 CONTENTS is nil. INFO is a plist used as a communication
1781 channel."
1782 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1783 "OrgCode" (org-odt--encode-plain-text
1784 (org-element-property :value code))))
1787 ;;;; Comment
1789 ;; Comments are ignored.
1792 ;;;; Comment Block
1794 ;; Comment Blocks are ignored.
1797 ;;;; Drawer
1799 (defun org-odt-drawer (drawer contents info)
1800 "Transcode a DRAWER element from Org to ODT.
1801 CONTENTS holds the contents of the block. INFO is a plist
1802 holding contextual information."
1803 (let* ((name (org-element-property :drawer-name drawer))
1804 (output (funcall org-odt-format-drawer-function
1805 name contents)))
1806 output))
1809 ;;;; Dynamic Block
1811 (defun org-odt-dynamic-block (dynamic-block contents info)
1812 "Transcode a DYNAMIC-BLOCK element from Org to ODT.
1813 CONTENTS holds the contents of the block. INFO is a plist
1814 holding contextual information. See `org-export-data'."
1815 contents)
1818 ;;;; Entity
1820 (defun org-odt-entity (entity contents info)
1821 "Transcode an ENTITY object from Org to ODT.
1822 CONTENTS are the definition itself. INFO is a plist holding
1823 contextual information."
1824 (org-element-property :utf-8 entity))
1827 ;;;; Example Block
1829 (defun org-odt-example-block (example-block contents info)
1830 "Transcode a EXAMPLE-BLOCK element from Org to ODT.
1831 CONTENTS is nil. INFO is a plist holding contextual information."
1832 (org-odt-format-code example-block info))
1835 ;;;; Export Snippet
1837 (defun org-odt-export-snippet (export-snippet contents info)
1838 "Transcode a EXPORT-SNIPPET object from Org to ODT.
1839 CONTENTS is nil. INFO is a plist holding contextual information."
1840 (when (eq (org-export-snippet-backend export-snippet) 'odt)
1841 (org-element-property :value export-snippet)))
1844 ;;;; Export Block
1846 (defun org-odt-export-block (export-block contents info)
1847 "Transcode a EXPORT-BLOCK element from Org to ODT.
1848 CONTENTS is nil. INFO is a plist holding contextual information."
1849 (when (string= (org-element-property :type export-block) "ODT")
1850 (org-remove-indentation (org-element-property :value export-block))))
1853 ;;;; Fixed Width
1855 (defun org-odt-fixed-width (fixed-width contents info)
1856 "Transcode a FIXED-WIDTH element from Org to ODT.
1857 CONTENTS is nil. INFO is a plist holding contextual information."
1858 (org-odt-do-format-code (org-element-property :value fixed-width)))
1861 ;;;; Footnote Definition
1863 ;; Footnote Definitions are ignored.
1866 ;;;; Footnote Reference
1868 (defun org-odt-footnote-reference (footnote-reference contents info)
1869 "Transcode a FOOTNOTE-REFERENCE element from Org to ODT.
1870 CONTENTS is nil. INFO is a plist holding contextual information."
1871 (let ((--format-footnote-definition
1872 (function
1873 (lambda (n def)
1874 (setq n (format "%d" n))
1875 (let ((id (concat "fn" n))
1876 (note-class "footnote")
1877 (par-style "Footnote"))
1878 (format
1879 "<text:note text:id=\"%s\" text:note-class=\"%s\">%s</text:note>"
1880 id note-class
1881 (concat
1882 (format "<text:note-citation>%s</text:note-citation>" n)
1883 (format "<text:note-body>%s</text:note-body>" def)))))))
1884 (--format-footnote-reference
1885 (function
1886 (lambda (n)
1887 (setq n (format "%d" n))
1888 (let ((note-class "footnote")
1889 (ref-format "text")
1890 (ref-name (concat "fn" n)))
1891 (format
1892 "<text:span text:style-name=\"%s\">%s</text:span>"
1893 "OrgSuperscript"
1894 (format "<text:note-ref text:note-class=\"%s\" text:reference-format=\"%s\" text:ref-name=\"%s\">%s</text:note-ref>"
1895 note-class ref-format ref-name n)))))))
1896 (concat
1897 ;; Insert separator between two footnotes in a row.
1898 (let ((prev (org-export-get-previous-element footnote-reference info)))
1899 (and (eq (org-element-type prev) 'footnote-reference)
1900 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1901 "OrgSuperscript" ",")))
1902 ;; Transcode footnote reference.
1903 (let ((n (org-export-get-footnote-number footnote-reference info)))
1904 (cond
1905 ((not (org-export-footnote-first-reference-p footnote-reference info))
1906 (funcall --format-footnote-reference n))
1907 ;; Inline definitions are secondary strings.
1908 ;; Non-inline footnotes definitions are full Org data.
1910 (let* ((raw (org-export-get-footnote-definition
1911 footnote-reference info))
1912 (def
1913 (let ((def (org-trim (org-export-data raw info))))
1914 (if (eq (org-element-type raw) 'org-data) def
1915 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1916 "Footnote" def)))))
1917 (funcall --format-footnote-definition n def))))))))
1920 ;;;; Headline
1922 (defun* org-odt-format-headline
1923 (todo todo-type priority text tags
1924 &key level section-number headline-label &allow-other-keys)
1925 (concat
1926 ;; Todo.
1927 (when todo
1928 (let ((style (if (member todo org-done-keywords) "OrgDone" "OrgTodo")))
1929 (format "<text:span text:style-name=\"%s\">%s</text:span> "
1930 style todo)))
1931 (when priority
1932 (let* ((style (format "OrgPriority-%s" priority))
1933 (priority (format "[#%c]" priority)))
1934 (format "<text:span text:style-name=\"%s\">%s</text:span> "
1935 style priority)))
1936 ;; Title.
1937 text
1938 ;; Tags.
1939 (when tags
1940 (concat
1941 "<text:tab/>"
1942 (format "<text:span text:style-name=\"%s\">[%s]</text:span>"
1943 "OrgTags" (mapconcat
1944 (lambda (tag)
1945 (format
1946 "<text:span text:style-name=\"%s\">%s</text:span>"
1947 "OrgTag" tag)) tags " : "))))))
1949 (defun org-odt-format-headline--wrap (headline backend info
1950 &optional format-function
1951 &rest extra-keys)
1952 "Transcode a HEADLINE element using BACKEND.
1953 INFO is a plist holding contextual information."
1954 (setq backend (or backend (plist-get info :back-end)))
1955 (let* ((level (+ (org-export-get-relative-level headline info)))
1956 (headline-number (org-export-get-headline-number headline info))
1957 (section-number (and (org-export-numbered-headline-p headline info)
1958 (mapconcat 'number-to-string
1959 headline-number ".")))
1960 (todo (and (plist-get info :with-todo-keywords)
1961 (let ((todo (org-element-property :todo-keyword headline)))
1962 (and todo
1963 (org-export-data-with-backend todo backend info)))))
1964 (todo-type (and todo (org-element-property :todo-type headline)))
1965 (priority (and (plist-get info :with-priority)
1966 (org-element-property :priority headline)))
1967 (text (org-export-data-with-backend
1968 (org-element-property :title headline) backend info))
1969 (tags (and (plist-get info :with-tags)
1970 (org-export-get-tags headline info)))
1971 (headline-label (concat "sec-" (mapconcat 'number-to-string
1972 headline-number "-")))
1973 (format-function (cond
1974 ((functionp format-function) format-function)
1975 ((not (eq org-odt-format-headline-function 'ignore))
1976 (function*
1977 (lambda (todo todo-type priority text tags
1978 &allow-other-keys)
1979 (funcall org-odt-format-headline-function
1980 todo todo-type priority text tags))))
1981 (t 'org-odt-format-headline))))
1982 (apply format-function
1983 todo todo-type priority text tags
1984 :headline-label headline-label :level level
1985 :section-number section-number extra-keys)))
1987 (defun org-odt-headline (headline contents info)
1988 "Transcode a HEADLINE element from Org to ODT.
1989 CONTENTS holds the contents of the headline. INFO is a plist
1990 holding contextual information."
1991 ;; Case 1: This is a footnote section: ignore it.
1992 (unless (org-element-property :footnote-section-p headline)
1993 (let* ((text (org-export-data (org-element-property :title headline) info))
1994 ;; Create the headline text.
1995 (full-text (org-odt-format-headline--wrap headline nil info))
1996 ;; Get level relative to current parsed data.
1997 (level (org-export-get-relative-level headline info))
1998 ;; Get canonical label for the headline.
1999 (id (concat "sec-" (mapconcat 'number-to-string
2000 (org-export-get-headline-number
2001 headline info) "-")))
2002 ;; Get user-specified labels for the headline.
2003 (extra-ids (list (org-element-property :CUSTOM_ID headline)
2004 (org-element-property :ID headline)))
2005 ;; Extra targets.
2006 (extra-targets
2007 (mapconcat (lambda (x)
2008 (when x
2009 (let ((x (if (org-uuidgen-p x) (concat "ID-" x) x)))
2010 (org-odt--target
2011 "" (org-export-solidify-link-text x)))))
2012 extra-ids ""))
2013 ;; Title.
2014 (anchored-title (org-odt--target full-text id)))
2015 (cond
2016 ;; Case 2. This is a deep sub-tree: export it as a list item.
2017 ;; Also export as items headlines for which no section
2018 ;; format has been found.
2019 ((org-export-low-level-p headline info)
2020 ;; Build the real contents of the sub-tree.
2021 (concat
2022 (and (org-export-first-sibling-p headline info)
2023 (format "\n<text:list text:style-name=\"%s\" %s>"
2024 ;; Choose style based on list type.
2025 (if (org-export-numbered-headline-p headline info)
2026 "OrgNumberedList" "OrgBulletedList")
2027 ;; If top-level list, re-start numbering. Otherwise,
2028 ;; continue numbering.
2029 (format "text:continue-numbering=\"%s\""
2030 (let* ((parent (org-export-get-parent-headline
2031 headline)))
2032 (if (and parent
2033 (org-export-low-level-p parent info))
2034 "true" "false")))))
2035 (let ((headline-has-table-p
2036 (let ((section (assq 'section (org-element-contents headline))))
2037 (assq 'table (and section (org-element-contents section))))))
2038 (format "\n<text:list-item>\n%s\n%s"
2039 (concat
2040 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
2041 "Text_20_body"
2042 (concat extra-targets anchored-title))
2043 contents)
2044 (if headline-has-table-p
2045 "</text:list-header>"
2046 "</text:list-item>")))
2047 (and (org-export-last-sibling-p headline info)
2048 "</text:list>")))
2049 ;; Case 3. Standard headline. Export it as a section.
2051 (concat
2052 (format
2053 "\n<text:h text:style-name=\"%s\" text:outline-level=\"%s\">%s</text:h>"
2054 (format "Heading_20_%s" level)
2055 level
2056 (concat extra-targets anchored-title))
2057 contents))))))
2060 ;;;; Horizontal Rule
2062 (defun org-odt-horizontal-rule (horizontal-rule contents info)
2063 "Transcode an HORIZONTAL-RULE object from Org to ODT.
2064 CONTENTS is nil. INFO is a plist holding contextual information."
2065 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
2066 "Horizontal_20_Line" ""))
2069 ;;;; Inline Babel Call
2071 ;; Inline Babel Calls are ignored.
2074 ;;;; Inline Src Block
2076 (defun org-odt--find-verb-separator (s)
2077 "Return a character not used in string S.
2078 This is used to choose a separator for constructs like \\verb."
2079 (let ((ll "~,./?;':\"|!@#%^&-_=+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>()[]{}"))
2080 (loop for c across ll
2081 when (not (string-match (regexp-quote (char-to-string c)) s))
2082 return (char-to-string c))))
2084 (defun org-odt-inline-src-block (inline-src-block contents info)
2085 "Transcode an INLINE-SRC-BLOCK element from Org to ODT.
2086 CONTENTS holds the contents of the item. INFO is a plist holding
2087 contextual information."
2088 (let* ((org-lang (org-element-property :language inline-src-block))
2089 (code (org-element-property :value inline-src-block))
2090 (separator (org-odt--find-verb-separator code)))
2091 (error "FIXME")))
2094 ;;;; Inlinetask
2096 (defun org-odt-inlinetask (inlinetask contents info)
2097 "Transcode an INLINETASK element from Org to ODT.
2098 CONTENTS holds the contents of the block. INFO is a plist
2099 holding contextual information."
2100 (cond
2101 ;; If `org-odt-format-inlinetask-function' is not 'ignore, call it
2102 ;; with appropriate arguments.
2103 ((not (eq org-odt-format-inlinetask-function 'ignore))
2104 (let ((format-function
2105 (function*
2106 (lambda (todo todo-type priority text tags
2107 &key contents &allow-other-keys)
2108 (funcall org-odt-format-inlinetask-function
2109 todo todo-type priority text tags contents)))))
2110 (org-odt-format-headline--wrap
2111 inlinetask nil info format-function :contents contents)))
2112 ;; Otherwise, use a default template.
2114 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
2115 "Text_20_body"
2116 (org-odt--textbox
2117 (concat
2118 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
2119 "OrgInlineTaskHeading"
2120 (org-odt-format-headline--wrap inlinetask nil info))
2121 contents)
2122 nil nil "OrgInlineTaskFrame" " style:rel-width=\"100%\"")))))
2124 ;;;; Italic
2126 (defun org-odt-italic (italic contents info)
2127 "Transcode ITALIC from Org to ODT.
2128 CONTENTS is the text with italic markup. INFO is a plist holding
2129 contextual information."
2130 (format "<text:span text:style-name=\"%s\">%s</text:span>"
2131 "Emphasis" contents))
2134 ;;;; Item
2136 (defun org-odt-item (item contents info)
2137 "Transcode an ITEM element from Org to ODT.
2138 CONTENTS holds the contents of the item. INFO is a plist holding
2139 contextual information."
2140 (let* ((plain-list (org-export-get-parent item))
2141 (type (org-element-property :type plain-list))
2142 (counter (org-element-property :counter item))
2143 (tag (let ((tag (org-element-property :tag item)))
2144 (and tag
2145 (concat (org-odt--checkbox item)
2146 (org-export-data tag info))))))
2147 (case type
2148 ((ordered unordered descriptive-1 descriptive-2)
2149 (format "\n<text:list-item>\n%s\n%s"
2150 contents
2151 (let* ((--element-has-a-table-p
2152 (function
2153 (lambda (element info)
2154 (loop for el in (org-element-contents element)
2155 thereis (eq (org-element-type el) 'table))))))
2156 (cond
2157 ((funcall --element-has-a-table-p item info)
2158 "</text:list-header>")
2159 (t "</text:list-item>")))))
2160 (t (error "Unknown list type: %S" type)))))
2162 ;;;; Keyword
2164 (defun org-odt-keyword (keyword contents info)
2165 "Transcode a KEYWORD element from Org to ODT.
2166 CONTENTS is nil. INFO is a plist holding contextual information."
2167 (let ((key (org-element-property :key keyword))
2168 (value (org-element-property :value keyword)))
2169 (cond
2170 ((string= key "ODT") value)
2171 ((string= key "INDEX")
2172 ;; FIXME
2173 (ignore))
2174 ((string= key "TOC")
2175 (let ((value (downcase value)))
2176 (cond
2177 ((string-match "\\<headlines\\>" value)
2178 (let ((depth (or (and (string-match "[0-9]+" value)
2179 (string-to-number (match-string 0 value)))
2180 (plist-get info :with-toc))))
2181 (when (wholenump depth) (org-odt-toc depth info))))
2182 ((member value '("tables" "figures" "listings"))
2183 ;; FIXME
2184 (ignore)))))
2185 ((string= key "PAGEBREAK")
2187 ;; Pagebreaks created this way are a mere expedience. These
2188 ;; create extraneous "empty" paragraphs which take up "extra
2189 ;; space". A typographer will chide you for resorting to such
2190 ;; underhanded means to create pagebreaks.
2192 ;; As an expedience it has it's uses. See
2193 ;; `org-odt-special-block' for a realistic example of how
2194 ;; pagebreak can be to service.
2196 ;; The right way to create pagebreaks is to create new styles -
2197 ;; custom or automatic - that set the "before/after" pagebreak
2198 ;; of an element (a paragraph, table etc).
2200 ;; For example, consider pagebreaks created as below.
2202 ;; Text in first page.
2204 ;; #+ATTR_ODT: :style "OrgPageBreakDefault"
2205 ;; #+PAGEBREAK:
2207 ;; This text goes in next page.
2209 ;; Now look at the page that is introduced with forced page
2210 ;; break. You will realize that the first line of text in that
2211 ;; page is a bit displaced from other pages created by
2212 ;; LibreOffice. A keen eye will definitely catch this
2213 ;; aberration.
2214 (let ((style (org-odt--read-attribute keyword :style)))
2215 (unless (and style (stringp style) (org-string-nw-p style))
2216 (setq style "OrgPageBreakDefault"))
2217 (format "\n<text:p text:style-name=\"%s\"/>" style))))))
2220 ;;;; Latex Environment
2223 ;; (eval-after-load 'ox-odt '(ad-deactivate 'org-format-latex-as-mathml))
2224 ;; (defadvice org-format-latex-as-mathml ; FIXME
2225 ;; (after org-odt-protect-latex-fragment activate)
2226 ;; "Encode LaTeX fragment as XML.
2227 ;; Do this when translation to MathML fails."
2228 ;; (unless (> (length ad-return-value) 0)
2229 ;; (setq ad-return-value (org-odt--encode-plain-text (ad-get-arg 0)))))
2231 (defun org-odt-latex-environment (latex-environment contents info)
2232 "Transcode a LATEX-ENVIRONMENT element from Org to ODT.
2233 CONTENTS is nil. INFO is a plist holding contextual information."
2234 (let* ((latex-frag (org-remove-indentation
2235 (org-element-property :value latex-environment))))
2236 (org-odt-do-format-code latex-frag)))
2239 ;;;; Latex Fragment
2241 ;; (when latex-frag ; FIXME
2242 ;; (setq href (org-propertize href :title "LaTeX Fragment"
2243 ;; :description latex-frag)))
2244 ;; handle verbatim
2245 ;; provide descriptions
2247 (defun org-odt-latex-fragment (latex-fragment contents info)
2248 "Transcode a LATEX-FRAGMENT object from Org to ODT.
2249 CONTENTS is nil. INFO is a plist holding contextual information."
2250 (let* ((latex-frag (org-element-property :value latex-fragment))
2251 (processing-type (plist-get info :with-latex)))
2252 (format "<text:span text:style-name=\"%s\">%s</text:span>"
2253 "OrgCode" (org-odt--encode-plain-text latex-frag t))))
2256 ;;;; Line Break
2258 (defun org-odt-line-break (line-break contents info)
2259 "Transcode a LINE-BREAK object from Org to ODT.
2260 CONTENTS is nil. INFO is a plist holding contextual information."
2261 "<text:line-break/>")
2264 ;;;; Link
2266 ;;;; Links :: Label references
2268 (defun org-odt--enumerate (element info &optional predicate n)
2269 (when predicate (assert (funcall predicate element info)))
2270 (let* ((--numbered-parent-headline-at-<=-n
2271 (function
2272 (lambda (element n info)
2273 (loop for x in (org-element-lineage element)
2274 thereis (and (eq (org-element-type x) 'headline)
2275 (<= (org-export-get-relative-level x info) n)
2276 (org-export-numbered-headline-p x info)
2277 x)))))
2278 (--enumerate
2279 (function
2280 (lambda (element scope info &optional predicate)
2281 (let ((counter 0))
2282 (org-element-map (or scope (plist-get info :parse-tree))
2283 (org-element-type element)
2284 (lambda (el)
2285 (and (or (not predicate) (funcall predicate el info))
2286 (incf counter)
2287 (eq element el)
2288 counter))
2289 info 'first-match)))))
2290 (scope (funcall --numbered-parent-headline-at-<=-n
2291 element (or n org-odt-display-outline-level) info))
2292 (ordinal (funcall --enumerate element scope info predicate))
2293 (tag
2294 (concat
2295 ;; Section number.
2296 (and scope
2297 (mapconcat 'number-to-string
2298 (org-export-get-headline-number scope info) "."))
2299 ;; Separator.
2300 (and scope ".")
2301 ;; Ordinal.
2302 (number-to-string ordinal))))
2303 tag))
2305 (defun org-odt-format-label (element info op &optional format-prop)
2306 "Return a label for ELEMENT.
2308 ELEMENT is a `link', `table', `src-block' or `paragraph' type
2309 element. INFO is a plist used as a communication channel. OP is
2310 either `definition' or `reference', depending on the purpose of
2311 the generated string.
2313 Return value is a string if OP is set to `reference' or a cons
2314 cell like CAPTION . SHORT-CAPTION) where CAPTION and
2315 SHORT-CAPTION are strings."
2316 (assert (memq (org-element-type element) '(link table src-block paragraph)))
2317 (let* ((caption-from
2318 (case (org-element-type element)
2319 (link (org-export-get-parent-element element))
2320 (t element)))
2321 ;; Get label and caption.
2322 (label (org-element-property :name caption-from))
2323 (caption (org-export-get-caption caption-from))
2324 (short-caption (org-export-get-caption caption-from t))
2325 ;; Transcode captions.
2326 (caption (and caption (org-export-data caption info)))
2327 ;; Currently short caption are sneaked in as object names.
2329 ;; The advantages are:
2331 ;; - Table Of Contents: Currently, there is no support for
2332 ;; building TOC for figures, listings and tables. See
2333 ;; `org-odt-keyword'. User instead has to rely on
2334 ;; external application for building such indices. Within
2335 ;; LibreOffice, building an "Illustration Index" or "Index
2336 ;; of Tables" will create a table with long captions (only)
2337 ;; and building a table with "Object names" will create a
2338 ;; table with short captions.
2340 ;; - Easy navigation: In LibreOffice, object names are
2341 ;; offered via the navigation bar. This way one can
2342 ;; quickly locate and jump to object of his choice in the
2343 ;; exported document.
2345 ;; The main disadvantage is that there cannot be any markups
2346 ;; within object names i.e., one cannot embolden, italicize
2347 ;; or underline text within short caption. So suppress
2348 ;; generation of <text:span >...</text:span> and other
2349 ;; markups by overriding the default translators. We
2350 ;; probably shouldn't be suppressing translators for all
2351 ;; elements in `org-element-all-objects', but for now this
2352 ;; will do.
2353 (short-caption
2354 ;; Sneaking in short-caption as name attribute is
2355 ;; problematic with LibreOffice > 4.0.4.2. So ignore
2356 ;; short-captions. See following thread:
2357 ;; http://lists.gnu.org/archive/html/emacs-orgmode/2013-12/msg00100.html
2358 (ignore
2359 (let ((short-caption (or short-caption caption))
2360 (backend (org-export-create-backend
2361 :parent (org-export-backend-name
2362 (plist-get info :back-end))
2363 :transcoders
2364 (mapcar (lambda (type) (cons type (lambda (o c i) c)))
2365 org-element-all-objects))))
2366 (when short-caption
2367 (org-export-data-with-backend short-caption backend info))))))
2368 (when (or label caption)
2369 (let* ((default-category
2370 (case (org-element-type element)
2371 (table :TABLE:)
2372 (src-block :LISTING:)
2373 ((link paragraph)
2374 (cond
2375 ((org-odt--enumerable-latex-image-p element info)
2376 :DVIPNG-IMAGE:)
2377 ((org-odt--enumerable-image-p element info)
2378 :FIGURE:)
2379 ((org-odt--enumerable-formula-p element info)
2380 :MATH-FORMULA:)
2381 (t (error "Don't know how to format label for link: %S"
2382 element))))
2383 (t (error "Don't know how to format label for element type: %s"
2384 (org-element-type element)))))
2385 seqno)
2386 (assert default-category)
2387 (destructuring-bind (counter category predicate)
2388 (assoc-default default-category org-odt-category-map-alist)
2389 ;; Compute sequence number of the element.
2390 (setq seqno (org-odt--enumerate element info predicate))
2391 ;; Localize category string.
2392 (setq category (org-export-translate category :utf-8 info))
2393 (case op
2394 ;; Case 1: Handle Label definition.
2395 (definition
2396 ;; Assign an internal label, if user has not provided one
2397 (setq label (org-export-solidify-link-text
2398 (or label (format "%s-%s" default-category seqno))))
2399 (cons
2400 (concat
2401 ;; Sneak in a bookmark. The bookmark is used when the
2402 ;; labeled element is referenced with a link that
2403 ;; provides its own description.
2404 (org-odt--target "" label)
2405 ;; Label definition: Typically formatted as below:
2406 ;; CATEGORY SEQ-NO: LONG CAPTION
2407 ;; with translation for correct punctuation.
2408 (let* ((caption-format
2409 (plist-get
2410 (assoc-default default-category
2411 org-odt-caption-and-xref-settings)
2412 (or format-prop :caption-format))))
2413 (mapconcat (lambda (%)
2414 (case %
2415 (category
2416 (org-export-translate category :utf-8 info))
2417 (counter
2418 (format
2419 "<text:sequence text:ref-name=\"%s\" text:name=\"%s\" text:formula=\"ooow:%s+1\" style:num-format=\"1\">%s</text:sequence>"
2420 label counter counter seqno))
2421 (caption (or caption ""))
2422 (otherwise %)))
2423 caption-format "")))
2424 short-caption))
2425 ;; Case 2: Handle Label reference.
2426 (reference
2427 (assert label)
2428 (setq label (org-export-solidify-link-text label))
2429 (let* ((xref-format
2430 (plist-get
2431 (assoc-default default-category
2432 org-odt-caption-and-xref-settings)
2433 (or format-prop :xref-format)))
2434 (standard-value-p
2435 (let ((standard-value
2436 (eval (car (get 'org-odt-caption-and-xref-settings
2437 'standard-value)))))
2438 (equal (assoc-default default-category
2439 org-odt-caption-and-xref-settings)
2440 (assoc-default default-category standard-value))))
2441 (value (if standard-value-p seqno "[PLS. UPDATE FIELDS]")))
2442 (mapconcat (lambda (%)
2443 (cond
2444 ((stringp %) %)
2445 ((symbolp %)
2446 (format "<text:sequence-ref text:reference-format=\"%s\" text:ref-name=\"%s\">%s</text:sequence-ref>"
2447 % label value))))
2448 xref-format "")))
2449 (t (error "Unknown %S on label" op))))))))
2452 ;;;; Links :: Inline Images
2454 (defun org-odt--copy-image-file (path)
2455 "Returns the internal name of the file"
2456 (let* ((image-type (file-name-extension path))
2457 (media-type (format "image/%s" image-type))
2458 (target-dir "Images/")
2459 (target-file
2460 (format "%s%04d.%s" target-dir
2461 (incf org-odt-embedded-images-count) image-type)))
2462 (message "Embedding %s as %s..."
2463 (substring-no-properties path) target-file)
2465 (when (= 1 org-odt-embedded-images-count)
2466 (make-directory (concat org-odt-zip-dir target-dir))
2467 (org-odt-create-manifest-file-entry "" target-dir))
2469 (copy-file path (concat org-odt-zip-dir target-file) 'overwrite)
2470 (org-odt-create-manifest-file-entry media-type target-file)
2471 target-file))
2473 (defun org-odt--image-size (file &optional user-width
2474 user-height scale dpi embed-as)
2475 (let* ((--pixels-to-cms
2476 (function (lambda (pixels dpi)
2477 (let ((cms-per-inch 2.54)
2478 (inches (/ pixels dpi)))
2479 (* cms-per-inch inches)))))
2480 (--size-in-cms
2481 (function
2482 (lambda (size-in-pixels dpi)
2483 (and size-in-pixels
2484 (cons (funcall --pixels-to-cms (car size-in-pixels) dpi)
2485 (funcall --pixels-to-cms (cdr size-in-pixels) dpi))))))
2486 (dpi (or dpi org-odt-pixels-per-inch))
2487 (anchor-type (or embed-as "paragraph"))
2488 (user-width (and (not scale) user-width))
2489 (user-height (and (not scale) user-height))
2490 (size
2491 (and
2492 (not (and user-height user-width))
2494 ;; Use Imagemagick.
2495 (and (executable-find "identify")
2496 (let ((size-in-pixels
2497 (let ((dim (shell-command-to-string
2498 (format "identify -format \"%%w:%%h\" \"%s\""
2499 file))))
2500 (when (string-match "\\([0-9]+\\):\\([0-9]+\\)" dim)
2501 (cons (string-to-number (match-string 1 dim))
2502 (string-to-number (match-string 2 dim)))))))
2503 (funcall --size-in-cms size-in-pixels dpi)))
2504 ;; Use Emacs.
2505 (let ((size-in-pixels
2506 (ignore-errors ; Emacs could be in batch mode
2507 (clear-image-cache)
2508 (image-size (create-image file) 'pixels))))
2509 (funcall --size-in-cms size-in-pixels dpi))
2510 ;; Use hard-coded values.
2511 (cdr (assoc-string anchor-type
2512 org-odt-default-image-sizes-alist))
2513 ;; Error out.
2514 (error "Cannot determine image size, aborting"))))
2515 (width (car size)) (height (cdr size)))
2516 (cond
2517 (scale
2518 (setq width (* width scale) height (* height scale)))
2519 ((and user-height user-width)
2520 (setq width user-width height user-height))
2521 (user-height
2522 (setq width (* user-height (/ width height)) height user-height))
2523 (user-width
2524 (setq height (* user-width (/ height width)) width user-width))
2525 (t (ignore)))
2526 ;; ensure that an embedded image fits comfortably within a page
2527 (let ((max-width (car org-odt-max-image-size))
2528 (max-height (cdr org-odt-max-image-size)))
2529 (when (or (> width max-width) (> height max-height))
2530 (let* ((scale1 (/ max-width width))
2531 (scale2 (/ max-height height))
2532 (scale (min scale1 scale2)))
2533 (setq width (* scale width) height (* scale height)))))
2534 (cons width height)))
2536 (defun org-odt-link--inline-image (element info)
2537 "Return ODT code for an inline image.
2538 LINK is the link pointing to the inline image. INFO is a plist
2539 used as a communication channel."
2540 (assert (eq (org-element-type element) 'link))
2541 (let* ((src (let* ((type (org-element-property :type element))
2542 (raw-path (org-element-property :path element)))
2543 (cond ((member type '("http" "https"))
2544 (concat type ":" raw-path))
2545 ((file-name-absolute-p raw-path)
2546 (expand-file-name raw-path))
2547 (t raw-path))))
2548 (src-expanded (if (file-name-absolute-p src) src
2549 (expand-file-name src (file-name-directory
2550 (plist-get info :input-file)))))
2551 (href (format
2552 "\n<draw:image xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>"
2553 (org-odt--copy-image-file src-expanded)))
2554 ;; Extract attributes from #+ATTR_ODT line.
2555 (attr-from (case (org-element-type element)
2556 (link (org-export-get-parent-element element))
2557 (t element)))
2558 ;; Handle `:anchor', `:style' and `:attributes' properties.
2559 (user-frame-anchor
2560 (car (assoc-string (org-odt--read-attribute attr-from :anchor)
2561 '(("as-char") ("paragraph") ("page")) t)))
2562 (user-frame-style
2563 (and user-frame-anchor (org-odt--read-attribute attr-from :style)))
2564 (user-frame-attrs
2565 (and user-frame-anchor (org-odt--read-attribute attr-from :attributes)))
2566 (user-frame-params
2567 (list user-frame-style user-frame-attrs user-frame-anchor))
2568 ;; (embed-as (or embed-as user-frame-anchor "paragraph"))
2570 ;; Handle `:width', `:height' and `:scale' properties. Read
2571 ;; them as numbers since we need them for computations.
2572 (size (org-odt--image-size
2573 src-expanded
2574 (org-odt--read-attribute attr-from :width)
2575 (org-odt--read-attribute attr-from :height)
2576 (org-odt--read-attribute attr-from :scale)
2577 nil ; embed-as
2578 "paragraph" ; FIXME
2580 (width (car size)) (height (cdr size))
2581 (standalone-link-p (org-odt--standalone-link-p element info))
2582 (embed-as (if standalone-link-p "paragraph" "as-char"))
2583 (captions (org-odt-format-label element info 'definition))
2584 (caption (car captions)) (short-caption (cdr captions))
2585 (entity (concat (and caption "Captioned") embed-as "Image"))
2586 ;; Check if this link was created by LaTeX-to-PNG converter.
2587 (replaces (org-element-property
2588 :replaces (if (not standalone-link-p) element
2589 (org-export-get-parent-element element))))
2590 ;; If yes, note down the type of the element - LaTeX Fragment
2591 ;; or LaTeX environment. It will go in to frame title.
2592 (title (and replaces (capitalize
2593 (symbol-name (org-element-type replaces)))))
2595 ;; If yes, note down its contents. It will go in to frame
2596 ;; description. This quite useful for debugging.
2597 (desc (and replaces (org-element-property :value replaces))))
2598 (org-odt--render-image/formula entity href width height
2599 captions user-frame-params title desc)))
2602 ;;;; Links :: Math formula
2604 (defun org-odt-link--inline-formula (element info)
2605 (let* ((src (let* ((type (org-element-property :type element))
2606 (raw-path (org-element-property :path element)))
2607 (cond
2608 ((file-name-absolute-p raw-path)
2609 (expand-file-name raw-path))
2610 (t raw-path))))
2611 (src-expanded (if (file-name-absolute-p src) src
2612 (expand-file-name src (file-name-directory
2613 (plist-get info :input-file)))))
2614 (href
2615 (format
2616 "\n<draw:object %s xlink:href=\"%s\" xlink:type=\"simple\"/>"
2617 " xlink:show=\"embed\" xlink:actuate=\"onLoad\""
2618 (file-name-directory (org-odt--copy-formula-file src-expanded))))
2619 (standalone-link-p (org-odt--standalone-link-p element info))
2620 (embed-as (if standalone-link-p 'paragraph 'character))
2621 (captions (org-odt-format-label element info 'definition))
2622 (caption (car captions)) (short-caption (cdr captions))
2623 ;; Check if this link was created by LaTeX-to-MathML
2624 ;; converter.
2625 (replaces (org-element-property
2626 :replaces (if (not standalone-link-p) element
2627 (org-export-get-parent-element element))))
2628 ;; If yes, note down the type of the element - LaTeX Fragment
2629 ;; or LaTeX environment. It will go in to frame title.
2630 (title (and replaces (capitalize
2631 (symbol-name (org-element-type replaces)))))
2633 ;; If yes, note down its contents. It will go in to frame
2634 ;; description. This quite useful for debugging.
2635 (desc (and replaces (org-element-property :value replaces)))
2636 width height)
2637 (cond
2638 ((eq embed-as 'character)
2639 (org-odt--render-image/formula "InlineFormula" href width height
2640 nil nil title desc))
2642 (let* ((equation (org-odt--render-image/formula
2643 "CaptionedDisplayFormula" href width height
2644 captions nil title desc))
2645 (label
2646 (car (org-odt-format-label element info 'definition :label-format))))
2647 (concat equation "<text:tab/>" label))))))
2649 (defun org-odt--copy-formula-file (src-file)
2650 "Returns the internal name of the file"
2651 (let* ((target-dir (format "Formula-%04d/"
2652 (incf org-odt-embedded-formulas-count)))
2653 (target-file (concat target-dir "content.xml")))
2654 ;; Create a directory for holding formula file. Also enter it in
2655 ;; to manifest.
2656 (make-directory (concat org-odt-zip-dir target-dir))
2657 (org-odt-create-manifest-file-entry
2658 "application/vnd.oasis.opendocument.formula" target-dir "1.2")
2659 ;; Copy over the formula file from user directory to zip
2660 ;; directory.
2661 (message "Embedding %s as %s..." src-file target-file)
2662 (let ((case-fold-search nil))
2663 (cond
2664 ;; Case 1: Mathml.
2665 ((string-match "\\.\\(mathml\\|mml\\)\\'" src-file)
2666 (copy-file src-file (concat org-odt-zip-dir target-file) 'overwrite))
2667 ;; Case 2: OpenDocument formula.
2668 ((string-match "\\.odf\\'" src-file)
2669 (org-odt--zip-extract src-file "content.xml"
2670 (concat org-odt-zip-dir target-dir)))
2671 (t (error "%s is not a formula file" src-file))))
2672 ;; Enter the formula file in to manifest.
2673 (org-odt-create-manifest-file-entry "text/xml" target-file)
2674 target-file))
2676 ;;;; Targets
2678 (defun org-odt--render-image/formula (cfg-key href width height &optional
2679 captions user-frame-params
2680 &rest title-and-desc)
2681 (let* ((frame-cfg-alist
2682 ;; Each element of this alist is of the form (CFG-HANDLE
2683 ;; INNER-FRAME-PARAMS OUTER-FRAME-PARAMS).
2685 ;; CFG-HANDLE is the key to the alist.
2687 ;; INNER-FRAME-PARAMS and OUTER-FRAME-PARAMS specify the
2688 ;; frame params for INNER-FRAME and OUTER-FRAME
2689 ;; respectively. See below.
2691 ;; Configurations that are meant to be applied to
2692 ;; non-captioned image/formula specifies no
2693 ;; OUTER-FRAME-PARAMS.
2695 ;; TERMINOLOGY
2696 ;; ===========
2697 ;; INNER-FRAME :: Frame that directly surrounds an
2698 ;; image/formula.
2700 ;; OUTER-FRAME :: Frame that encloses the INNER-FRAME. This
2701 ;; frame also contains the caption, if any.
2703 ;; FRAME-PARAMS :: List of the form (FRAME-STYLE-NAME
2704 ;; FRAME-ATTRIBUTES FRAME-ANCHOR). Note
2705 ;; that these are the last three arguments
2706 ;; to `org-odt--frame'.
2708 ;; Note that an un-captioned image/formula requires just an
2709 ;; INNER-FRAME, while a captioned image/formula requires
2710 ;; both an INNER and an OUTER-FRAME.
2711 '(("As-CharImage" ("OrgInlineImage" nil "as-char"))
2712 ("ParagraphImage" ("OrgDisplayImage" nil "paragraph"))
2713 ("PageImage" ("OrgPageImage" nil "page"))
2714 ("CaptionedAs-CharImage"
2715 ("OrgCaptionedImage"
2716 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
2717 ("OrgInlineImage" nil "as-char"))
2718 ("CaptionedParagraphImage"
2719 ("OrgCaptionedImage"
2720 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
2721 ("OrgImageCaptionFrame" nil "paragraph"))
2722 ("CaptionedPageImage"
2723 ("OrgCaptionedImage"
2724 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
2725 ("OrgPageImageCaptionFrame" nil "page"))
2726 ("InlineFormula" ("OrgInlineFormula" nil "as-char"))
2727 ("DisplayFormula" ("OrgDisplayFormula" nil "as-char"))
2728 ("CaptionedDisplayFormula"
2729 ("OrgCaptionedFormula" nil "paragraph")
2730 ("OrgFormulaCaptionFrame" nil "paragraph"))))
2731 (caption (car captions)) (short-caption (cdr captions))
2732 ;; Retrieve inner and outer frame params, from configuration.
2733 (frame-cfg (assoc-string cfg-key frame-cfg-alist t))
2734 (inner (nth 1 frame-cfg))
2735 (outer (nth 2 frame-cfg))
2736 ;; User-specified frame params (from #+ATTR_ODT spec)
2737 (user user-frame-params)
2738 (--merge-frame-params (function
2739 (lambda (default user)
2740 "Merge default and user frame params."
2741 (if (not user) default
2742 (assert (= (length default) 3))
2743 (assert (= (length user) 3))
2744 (loop for u in user
2745 for d in default
2746 collect (or u d)))))))
2747 (cond
2748 ;; Case 1: Image/Formula has no caption.
2749 ;; There is only one frame, one that surrounds the image
2750 ;; or formula.
2751 ((not caption)
2752 ;; Merge user frame params with that from configuration.
2753 (setq inner (funcall --merge-frame-params inner user))
2754 (apply 'org-odt--frame href width height
2755 (append inner title-and-desc)))
2756 ;; Case 2: Image/Formula is captioned or labeled.
2757 ;; There are two frames: The inner one surrounds the
2758 ;; image or formula. The outer one contains the
2759 ;; caption/sequence number.
2761 ;; Merge user frame params with outer frame params.
2762 (setq outer (funcall --merge-frame-params outer user))
2763 ;; Short caption, if specified, goes as part of inner frame.
2764 (setq inner (let ((frame-params (copy-sequence inner)))
2765 (setcar (cdr frame-params)
2766 (concat
2767 (cadr frame-params)
2768 (when short-caption
2769 (format " draw:name=\"%s\" " short-caption))))
2770 frame-params))
2771 (apply 'org-odt--textbox
2772 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
2773 "Illustration"
2774 (concat
2775 (apply 'org-odt--frame href width height
2776 (append inner title-and-desc))
2777 caption))
2778 width height outer)))))
2780 (defun org-odt--enumerable-p (element info)
2781 ;; Element should have a caption or label.
2782 (or (org-element-property :caption element)
2783 (org-element-property :name element)))
2785 (defun org-odt--enumerable-image-p (element info)
2786 (org-odt--standalone-link-p
2787 element info
2788 ;; Paragraph should have a caption or label. It SHOULD NOT be a
2789 ;; replacement element. (i.e., It SHOULD NOT be a result of LaTeX
2790 ;; processing.)
2791 (lambda (p)
2792 (and (not (org-element-property :replaces p))
2793 (or (org-element-property :caption p)
2794 (org-element-property :name p))))
2795 ;; Link should point to an image file.
2796 (lambda (l)
2797 (assert (eq (org-element-type l) 'link))
2798 (org-export-inline-image-p l org-odt-inline-image-rules))))
2800 (defun org-odt--enumerable-latex-image-p (element info)
2801 (org-odt--standalone-link-p
2802 element info
2803 ;; Paragraph should have a caption or label. It SHOULD also be a
2804 ;; replacement element. (i.e., It SHOULD be a result of LaTeX
2805 ;; processing.)
2806 (lambda (p)
2807 (and (org-element-property :replaces p)
2808 (or (org-element-property :caption p)
2809 (org-element-property :name p))))
2810 ;; Link should point to an image file.
2811 (lambda (l)
2812 (assert (eq (org-element-type l) 'link))
2813 (org-export-inline-image-p l org-odt-inline-image-rules))))
2815 (defun org-odt--enumerable-formula-p (element info)
2816 (org-odt--standalone-link-p
2817 element info
2818 ;; Paragraph should have a caption or label.
2819 (lambda (p)
2820 (or (org-element-property :caption p)
2821 (org-element-property :name p)))
2822 ;; Link should point to a MathML or ODF file.
2823 (lambda (l)
2824 (assert (eq (org-element-type l) 'link))
2825 (org-export-inline-image-p l org-odt-inline-formula-rules))))
2827 (defun org-odt--standalone-link-p (element info &optional
2828 paragraph-predicate
2829 link-predicate)
2830 "Test if ELEMENT is a standalone link for the purpose ODT export.
2831 INFO is a plist holding contextual information.
2833 Return non-nil, if ELEMENT is of type paragraph satisfying
2834 PARAGRAPH-PREDICATE and its sole content, save for whitespaces,
2835 is a link that satisfies LINK-PREDICATE.
2837 Return non-nil, if ELEMENT is of type link satisfying
2838 LINK-PREDICATE and its containing paragraph satisfies
2839 PARAGRAPH-PREDICATE in addition to having no other content save for
2840 leading and trailing whitespaces.
2842 Return nil, otherwise."
2843 (let ((p (case (org-element-type element)
2844 (paragraph element)
2845 (link (and (or (not link-predicate)
2846 (funcall link-predicate element))
2847 (org-export-get-parent element)))
2848 (t nil))))
2849 (when (and p (eq (org-element-type p) 'paragraph))
2850 (when (or (not paragraph-predicate)
2851 (funcall paragraph-predicate p))
2852 (let ((contents (org-element-contents p)))
2853 (loop for x in contents
2854 with inline-image-count = 0
2855 always (case (org-element-type x)
2856 (plain-text
2857 (not (org-string-nw-p x)))
2858 (link
2859 (and (or (not link-predicate)
2860 (funcall link-predicate x))
2861 (= (incf inline-image-count) 1)))
2862 (t nil))))))))
2864 (defun org-odt-link--infer-description (destination info)
2865 ;; DESTINATION is a HEADLINE, a "<<target>>" or an element (like
2866 ;; paragraph, verse-block etc) to which a "#+NAME: label" can be
2867 ;; attached. Note that labels that are attached to captioned
2868 ;; entities - inline images, math formulae and tables - get resolved
2869 ;; as part of `org-odt-format-label' and `org-odt--enumerate'.
2871 ;; Create a cross-reference to DESTINATION but make best-efforts to
2872 ;; create a *meaningful* description. Check item numbers, section
2873 ;; number and section title in that order.
2875 ;; NOTE: Counterpart of `org-export-get-ordinal'.
2876 ;; FIXME: Handle footnote-definition footnote-reference?
2877 (let* ((genealogy (org-element-lineage destination))
2878 (data (reverse genealogy))
2879 (label (case (org-element-type destination)
2880 (headline
2881 (format "sec-%s" (mapconcat 'number-to-string
2882 (org-export-get-headline-number
2883 destination info) "-")))
2884 (target
2885 (org-element-property :value destination))
2886 (t (org-element-property :name destination)))))
2888 ;; Case 1: Does the user want the cross-references to be typeset
2889 ;; in a custom manner (say for example, generate page numbers
2890 ;; etc.)? If yes, emit the required XML tags but with "???" as
2891 ;; the field value. This (incorrect) field value can be
2892 ;; corrected by using an external Office application. For
2893 ;; example, in case of LibreOffice, the field values can be
2894 ;; synchronized by running Tools->Update->Fields/Update All on
2895 ;; the exported document.
2896 (org-odt--xref-target :TARGET: "[PLS. UPDATE FIELDS]"
2897 (org-export-solidify-link-text label))
2898 ;; Case 2: Is target an item of a numbered list? If yes, use the
2899 ;; item's number as description. The target need not necessarily
2900 ;; be part of a proper numbered list, it can also be part of a
2901 ;; low-level headline that is deemed as a list for purposes of
2902 ;; export.
2903 (let* ( ;; Locate top-level list.
2904 (top-level-list
2905 (loop for x on data
2906 when (eq (org-element-type (car x)) 'plain-list)
2907 return x))
2908 ;; Get list item nos.
2909 (item-numbers
2910 (loop for (plain-list item . rest) on top-level-list by #'cddr
2911 until (not (eq (org-element-type plain-list) 'plain-list))
2912 collect (when (eq (org-element-property :type
2913 plain-list)
2914 'ordered)
2915 (1+ (length (org-export-get-previous-element
2916 item info t))))))
2917 ;; Locate top-most listified headline.
2918 (listified-headlines
2919 (loop for x on data
2920 when (and (eq (org-element-type (car x)) 'headline)
2921 (org-export-low-level-p (car x) info))
2922 return x))
2923 ;; Get listified headline numbers.
2924 (listified-headline-nos
2925 (loop for el in listified-headlines
2926 when (eq (org-element-type el) 'headline)
2927 collect (when (org-export-numbered-headline-p el info)
2928 (1+ (length (org-export-get-previous-element
2929 el info t)))))))
2930 ;; Combine item numbers from both the listified headlines and
2931 ;; regular list items.
2933 ;; Case 2.1: Check if all the parents of list item are
2934 ;; numbered. If yes, link to the item proper.
2935 (let ((item-numbers (append listified-headline-nos item-numbers)))
2936 (when (and item-numbers (not (memq nil item-numbers)))
2937 (format "<text:bookmark-ref text:reference-format=\"number-all-superior\" text:ref-name=\"%s\">%s</text:bookmark-ref>"
2938 (org-export-solidify-link-text label)
2939 (mapconcat (lambda (n) (if (not n) " "
2940 (concat (number-to-string n) ".")))
2941 item-numbers "")))))
2942 ;; Case 3: Is the target part of a regular and numbered headline
2943 ;; in the hierarchy? If yes, use the chapter/section number as
2944 ;; description.
2945 (let ((headline (loop for el in (cons destination genealogy)
2946 when (and (eq (org-element-type el) 'headline)
2947 (not (org-export-low-level-p el info))
2948 (org-export-numbered-headline-p el info))
2949 return el)))
2950 ;; We found one.
2951 (when headline
2952 (format "<text:bookmark-ref text:reference-format=\"chapter\" text:ref-name=\"%s\">%s</text:bookmark-ref>"
2953 (org-export-solidify-link-text label)
2954 (mapconcat 'number-to-string (org-export-get-headline-number
2955 headline info) "."))))
2956 ;; Case 4: Is the target part of any headline. If yes, use the
2957 ;; chapter/section's title description.
2958 (let ((headline (loop for el in (cons destination genealogy)
2959 when (and (eq (org-element-type el) 'headline)
2960 (not (org-export-low-level-p el info)))
2961 return el)))
2962 ;; We found one.
2963 (when headline
2964 (format "<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"%s\">%s</text:bookmark-ref>"
2965 (org-export-solidify-link-text label)
2966 (let ((title (org-element-property :title headline)))
2967 (org-export-data title info)))))
2968 ;; Case 5: The target is part of a document that is outside of
2969 ;; any headline. Use "???" as description. (We can use the
2970 ;; label text itself as the description. But, philosophically
2971 ;; speaking, this is in-appropriate. Targets are just labels and
2972 ;; must not generate any content text. So, it makes sense to
2973 ;; insist that the user provide an explicit description.)
2974 (format "<text:bookmark-ref text:reference-format=\"number-all-superior\" text:ref-name=\"%s\">%s</text:bookmark-ref>"
2975 (org-export-solidify-link-text label) "[PLS. UPDATE FIELDS]"))))
2977 (defun org-odt-link (link desc info)
2978 "Transcode a LINK object from Org to ODT.
2980 DESC is the description part of the link, or the empty string.
2981 INFO is a plist holding contextual information. See
2982 `org-export-data'."
2983 (let* ((type (org-element-property :type link))
2984 (raw-path (org-element-property :path link))
2985 ;; Ensure DESC really exists, or set it to nil.
2986 (desc (and (not (string= desc "")) desc))
2987 (imagep (org-export-inline-image-p
2988 link org-odt-inline-image-rules))
2989 (path (cond
2990 ((member type '("http" "https" "ftp" "mailto"))
2991 (concat type ":" raw-path))
2992 ((and (string= type "file") (file-name-absolute-p raw-path))
2993 (concat "file:" raw-path))
2994 (t raw-path)))
2995 ;; Convert & to &amp; for correct XML representation
2996 (path (replace-regexp-in-string "&" "&amp;" path))
2997 protocol)
2998 (cond
2999 ;; Image file.
3000 ((and (not desc) (org-export-inline-image-p
3001 link org-odt-inline-image-rules))
3002 (org-odt-link--inline-image link info))
3003 ;; Formula file.
3004 ((and (not desc) (org-export-inline-image-p
3005 link org-odt-inline-formula-rules))
3006 (org-odt-link--inline-formula link info))
3007 ;; Radio target: Transcode target's contents and use them as
3008 ;; link's description.
3009 ((string= type "radio")
3010 (let ((destination (org-export-resolve-radio-link link info)))
3011 (when destination
3012 (let ((desc (org-export-data (org-element-contents destination) info))
3013 (href (org-export-solidify-link-text
3014 (org-element-property :value destination))))
3016 ;; Case 1: Honour user's customization.
3017 (org-odt--xref-target :TARGET: "[PLS. UPDATE FIELDS]" href)
3018 ;; Case 2: Use the text of the radio target.
3019 (format
3020 "<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"%s\">%s</text:bookmark-ref>"
3021 href desc))))))
3022 ;; Links pointing to a headline: Find destination and build
3023 ;; appropriate referencing command.
3024 ((member type '("custom-id" "fuzzy" "id"))
3025 (let ((destination (if (string= type "fuzzy")
3026 (org-export-resolve-fuzzy-link link info)
3027 (org-export-resolve-id-link link info))))
3028 (case (org-element-type destination)
3029 ;; Case 1: Fuzzy link points nowhere.
3030 ('nil
3031 (user-error
3032 "Link \"%s\" at char position %d-%d points nowhere."
3033 (org-element-property :raw-link link)
3034 (org-element-property :begin link)
3035 (org-element-property :end link)))
3036 ;; Case 2: Fuzzy link points to a headline.
3037 (headline
3038 ;; If there's a description, create a hyperlink.
3039 ;; Otherwise, try to provide a meaningful description.
3040 (if (not desc) (org-odt-link--infer-description destination info)
3041 (let* ((headline-no
3042 (org-export-get-headline-number destination info))
3043 (label
3044 (format "sec-%s"
3045 (mapconcat 'number-to-string headline-no "-"))))
3046 (format
3047 "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
3048 label desc))))
3049 ;; Case 3: Fuzzy link points to a target.
3050 (target
3051 ;; If there's a description, create a hyperlink.
3052 ;; Otherwise, try to provide a meaningful description.
3053 (if (not desc) (org-odt-link--infer-description destination info)
3054 (let ((label (org-element-property :value destination)))
3055 (format "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
3056 (org-export-solidify-link-text label)
3057 desc))))
3058 ;; Case 4: Fuzzy link points to some element (e.g., an
3059 ;; inline image, a math formula or a table).
3060 (otherwise
3061 (let ((label-reference
3062 (ignore-errors (org-odt-format-label
3063 destination info 'reference))))
3064 (cond ((not label-reference)
3065 (org-odt-link--infer-description destination info))
3066 ;; LINK has no description. Create
3067 ;; a cross-reference showing entity's sequence
3068 ;; number.
3069 ((not desc) label-reference)
3070 ;; LINK has description. Insert a hyperlink with
3071 ;; user-provided description.
3073 (let ((label (org-element-property :name destination)))
3074 (format "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
3075 (org-export-solidify-link-text label)
3076 desc)))))))))
3077 ;; Coderef: replace link with the reference name or the
3078 ;; equivalent line number.
3079 ((string= type "coderef")
3080 (let* ((line-no (format "%d" (org-export-resolve-coderef path info)))
3081 (href (concat "coderef-" path)))
3082 (format
3083 (org-export-get-coderef-format path desc)
3084 (format
3085 "<text:bookmark-ref text:reference-format=\"number\" text:ref-name=\"%s\">%s</text:bookmark-ref>"
3086 href line-no))))
3087 ;; Link type is handled by a special function.
3088 ((functionp (setq protocol (nth 2 (assoc type org-link-protocols))))
3089 (funcall protocol (org-link-unescape path) desc 'odt))
3090 ;; External link with a description part.
3091 ((and path desc)
3092 (let ((link-contents (org-element-contents link)))
3093 ;; Check if description is a link to an inline image.
3094 (if (and (not (cdr link-contents))
3095 (let ((desc-element (car link-contents)))
3096 (and (eq (org-element-type desc-element) 'link)
3097 (org-export-inline-image-p
3098 desc-element org-odt-inline-image-rules))))
3099 ;; Format link as a clickable image.
3100 (format "\n<draw:a xlink:type=\"simple\" xlink:href=\"%s\">\n%s\n</draw:a>"
3101 path desc)
3102 ;; Otherwise, format it as a regular link.
3103 (format "<text:a xlink:type=\"simple\" xlink:href=\"%s\">%s</text:a>"
3104 path desc))))
3105 ;; External link without a description part.
3106 (path
3107 (format "<text:a xlink:type=\"simple\" xlink:href=\"%s\">%s</text:a>"
3108 path path))
3109 ;; No path, only description. Try to do something useful.
3110 (t (format "<text:span text:style-name=\"%s\">%s</text:span>"
3111 "Emphasis" desc)))))
3114 ;;;; Node Property
3116 (defun org-odt-node-property (node-property contents info)
3117 "Transcode a NODE-PROPERTY element from Org to ODT.
3118 CONTENTS is nil. INFO is a plist holding contextual
3119 information."
3120 (org-odt--encode-plain-text
3121 (format "%s:%s"
3122 (org-element-property :key node-property)
3123 (let ((value (org-element-property :value node-property)))
3124 (if value (concat " " value) "")))))
3126 ;;;; Paragraph
3128 ;; You can customize paragraphs - standalone one and those occurring
3129 ;; within lists - using `:style' and `:p-style' attributes. Try out
3130 ;; the following example and see for yourself what you can achieve.
3132 ;; #+ATTR_ODT: :style "OrgBulletedList" :p-style "Text_20_body_20_bold"
3133 ;; 1. N1
3134 ;; 1. N11
3135 ;; 2. N12
3136 ;; 2. N2
3137 ;; #+ATTR_ODT: :style "OrgNumberedList" :p-style "Preformatted_20_Text"
3138 ;; * B21
3140 ;; * B22
3141 ;; - B221
3143 ;; First paragraph.
3145 ;; #+ATTR_ODT: :style "OrgBibliographyList" :p-style "Text_20_body"
3146 ;; 1. one
3147 ;; 2. two
3148 ;; 3. three
3150 ;; #+ATTR_ODT: :style "Text_20_body_20_indent"
3151 ;; Second paragraph.
3153 ;; - B222
3154 ;; * B23
3155 ;; 3. N3
3157 (defun org-odt-paragraph (paragraph contents info)
3158 "Transcode a PARAGRAPH element from Org to ODT.
3159 CONTENTS is the contents of the paragraph, as a string. INFO is
3160 the plist used as a communication channel."
3161 (let* ((parent (org-export-get-parent paragraph))
3162 (parent-type (org-element-type parent))
3163 (genealogy (cons paragraph (org-element-lineage paragraph)))
3164 (data (reverse genealogy))
3165 (style
3166 ;; Traverse the parse-tree from root element to this
3167 ;; paragraph. Use the following rule at each element to
3168 ;; calculate the paragraph style applicable at that element.
3170 ;; Case 1: If an element specifies an EXPLICIT STYLE of it's
3171 ;; own via the #+ATTR_ODT line, use it. PARAGRAPH and
3172 ;; SPECIAL-BLOCK use the `:style' attribute for this
3173 ;; purpose, while PLAIN-LIST uses `:p-style' attribute.
3175 ;; Case 2: If an element does not have an explicit style but
3176 ;; has an IMPLICIT, PRE-CONFIGURE STYLE of it's own, use it.
3177 ;; For example, paragraphs within a FOOTNOTE-DEFINITON,
3178 ;; CENTER-BLOCK or QUOTE-BLOCK get pre-configured styles
3179 ;; like "Footnote", "OrgCenter" or "Quotations" resply.
3181 ;; Case 3: If an element specifies neither an IMPLICIT style
3182 ;; or an EXPLICIT style, use the style from it's parent.
3183 ;; For example, a paragraph within a PLAIN-LIST (that
3184 ;; doesn't specify a `:p-style' of it's own) inherit it's
3185 ;; style from the it's parent.
3187 ;; Case 4: If an element has no parent (i.e., root node),
3188 ;; use the fallback style "Text_20_body".
3189 (loop for el in data
3190 ;; Fallback style.
3191 with style = "Text_20_body"
3192 with footnote-definition-p = nil do
3193 (setq style
3195 ;; Case 1: Does this node IMPLICITLY or
3196 ;; EXPLICITLY specify a style? Use it.
3197 (case (org-element-type el)
3198 (center-block
3199 (or (org-odt--read-attribute el :style)
3200 (if footnote-definition-p "OrgFootnoteCenter"
3201 "OrgCenter")))
3202 (footnote-definition
3203 (setq footnote-definition-p t)
3204 (or (org-odt--read-attribute el :style) "Footnote"))
3205 (paragraph
3207 ;; Case 1: Some paragraphs are "created"
3208 ;; not by the user but by the
3209 ;; pre-processing stage. They use the
3210 ;; `:style' property of the element rather
3211 ;; than the style property from the
3212 ;; attribute line. See
3213 ;; `org-odt--translate-description-lists/latex',
3214 ;; `org-odt--translate-description-lists/html'
3215 ;; `org-odt--translate-latex-fragments'.
3216 (org-element-property :style el)
3217 (org-odt--read-attribute el :style)))
3218 (plain-list
3219 ;; NOTE: ITEMs cannot have #+ATTR_ODT
3220 ;; attached to them. See
3222 ;; http://lists.gnu.org/archive/html/emacs-orgmode/2013-08/msg00586.html
3223 (org-odt--read-attribute el :p-style))
3224 (quote-block
3225 (if footnote-definition-p "OrgFootnoteQuotations"
3226 "Quotations"))
3227 (special-block
3228 (let ((type (downcase (org-element-property :type el))))
3229 (cond
3230 ;; Case 1: Handle SPECIAL-BLOCKs that are
3231 ;; well-known (and treated specially) by
3232 ;; the ODT exporter.
3233 ((string= type "textbox")
3234 (org-odt--read-attribute el :p-style))
3235 ;; Case 2: Handle user-specified
3236 ;; SPECIAL-BLOCKs not known to the
3237 ;; exporter.
3238 (t (org-odt--read-attribute el :style))))))
3239 ;; Case 2: Element doesn't specify a style of
3240 ;; it's own. Use the parent style.
3241 style))
3242 finally return style)))
3243 ;; If this paragraph is a leading paragraph in an item and the
3244 ;; item has a checkbox, splice the checkbox and paragraph contents
3245 ;; together.
3246 (when (and (eq (org-element-type parent) 'item)
3247 (eq paragraph (car (org-element-contents parent))))
3248 (setq contents (concat (org-odt--checkbox parent) contents)))
3249 (format "\n<text:p text:style-name=\"%s\">%s</text:p>" style contents)))
3252 ;;;; Plain List
3254 (defun org-odt-plain-list (plain-list contents info)
3255 "Transcode a PLAIN-LIST element from Org to ODT.
3256 CONTENTS is the contents of the list. INFO is a plist holding
3257 contextual information."
3258 (format "\n<text:list text:style-name=\"%s\" %s>\n%s</text:list>"
3259 ;; Choose style based on list type.
3260 (case (org-element-property :type plain-list)
3261 (ordered (or (org-odt--read-attribute plain-list :style)
3262 "OrgNumberedList"))
3263 (unordered (or (org-odt--read-attribute plain-list :style)
3264 "OrgBulletedList"))
3265 ;; FIXME: Define and handle `:style' attributes for
3266 ;; description lists.
3267 (descriptive-1 "OrgDescriptionList")
3268 (descriptive-2 "OrgDescriptionList"))
3269 ;; If top-level list, re-start numbering. Otherwise,
3270 ;; continue numbering.
3271 (format "text:continue-numbering=\"%s\""
3272 (let* ((parent (org-export-get-parent plain-list)))
3273 (if (and parent (eq (org-element-type parent) 'item))
3274 "true" "false")))
3275 contents))
3277 ;;;; Plain Text
3279 (defun org-odt--encode-tabs-and-spaces (line)
3280 (replace-regexp-in-string
3281 "\\([\t]\\|\\([ ]+\\)\\)"
3282 (lambda (s)
3283 (cond
3284 ((string= s "\t") "<text:tab/>")
3285 (t (let ((n (length s)))
3286 (cond
3287 ((= n 1) " ")
3288 ((> n 1) (concat " " (format "<text:s text:c=\"%d\"/>" (1- n))))
3289 (t ""))))))
3290 line))
3292 (defun org-odt--encode-plain-text (text &optional no-whitespace-filling)
3293 (mapc
3294 (lambda (pair)
3295 (setq text (replace-regexp-in-string (car pair) (cdr pair) text t t)))
3296 '(("&" . "&amp;") ("<" . "&lt;") (">" . "&gt;")))
3297 (if no-whitespace-filling text
3298 (org-odt--encode-tabs-and-spaces text)))
3300 (defun org-odt-plain-text (text info)
3301 "Transcode a TEXT string from Org to ODT.
3302 TEXT is the string to transcode. INFO is a plist holding
3303 contextual information."
3304 (let ((output text))
3305 ;; Protect &, < and >.
3306 (setq output (org-odt--encode-plain-text output t))
3307 ;; Handle smart quotes. Be sure to provide original string since
3308 ;; OUTPUT may have been modified.
3309 (when (plist-get info :with-smart-quotes)
3310 (setq output (org-export-activate-smart-quotes output :utf-8 info text)))
3311 ;; Convert special strings.
3312 (when (plist-get info :with-special-strings)
3313 (mapc
3314 (lambda (pair)
3315 (setq output
3316 (replace-regexp-in-string (car pair) (cdr pair) output t nil)))
3317 org-odt-special-string-regexps))
3318 ;; Handle break preservation if required.
3319 (when (plist-get info :preserve-breaks)
3320 (setq output (replace-regexp-in-string
3321 "\\(\\\\\\\\\\)?[ \t]*\n" "<text:line-break/>" output t)))
3322 ;; Return value.
3323 output))
3326 ;;;; Planning
3328 (defun org-odt-planning (planning contents info)
3329 "Transcode a PLANNING element from Org to ODT.
3330 CONTENTS is nil. INFO is a plist used as a communication
3331 channel."
3332 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3333 "OrgPlanning"
3334 (concat
3335 (let ((closed (org-element-property :closed planning)))
3336 (when closed
3337 (concat
3338 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3339 "OrgClosedKeyword" org-closed-string)
3340 (org-odt-timestamp closed contents info))))
3341 (let ((deadline (org-element-property :deadline planning)))
3342 (when deadline
3343 (concat
3344 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3345 "OrgDeadlineKeyword" org-deadline-string)
3346 (org-odt-timestamp deadline contents info))))
3347 (let ((scheduled (org-element-property :scheduled planning)))
3348 (when scheduled
3349 (concat
3350 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3351 "OrgScheduledKeyword" org-deadline-string)
3352 (org-odt-timestamp scheduled contents info)))))))
3355 ;;;; Property Drawer
3357 (defun org-odt-property-drawer (property-drawer contents info)
3358 "Transcode a PROPERTY-DRAWER element from Org to ODT.
3359 CONTENTS holds the contents of the drawer. INFO is a plist
3360 holding contextual information."
3361 (and (org-string-nw-p contents)
3362 (format "<text:p text:style-name=\"OrgFixedWidthBlock\">%s</text:p>"
3363 contents)))
3366 ;;;; Quote Block
3368 (defun org-odt-quote-block (quote-block contents info)
3369 "Transcode a QUOTE-BLOCK element from Org to ODT.
3370 CONTENTS holds the contents of the block. INFO is a plist
3371 holding contextual information."
3372 contents)
3375 ;;;; Section
3377 (defun org-odt-format-section (text style &optional name)
3378 (let ((default-name (car (org-odt-add-automatic-style "Section"))))
3379 (format "\n<text:section text:style-name=\"%s\" %s>\n%s\n</text:section>"
3380 style
3381 (format "text:name=\"%s\"" (or name default-name))
3382 text)))
3385 (defun org-odt-section (section contents info) ; FIXME
3386 "Transcode a SECTION element from Org to ODT.
3387 CONTENTS holds the contents of the section. INFO is a plist
3388 holding contextual information."
3389 contents)
3391 ;;;; Radio Target
3393 (defun org-odt-radio-target (radio-target text info)
3394 "Transcode a RADIO-TARGET object from Org to ODT.
3395 TEXT is the text of the target. INFO is a plist holding
3396 contextual information."
3397 (org-odt--target
3398 text (org-export-solidify-link-text
3399 (org-element-property :value radio-target))))
3402 ;;;; Special Block
3404 (defun org-odt-special-block (special-block contents info)
3405 "Transcode a SPECIAL-BLOCK element from Org to ODT.
3406 CONTENTS holds the contents of the block. INFO is a plist
3407 holding contextual information."
3408 (let ((type (org-element-property :type special-block))
3409 (attributes (org-export-read-attribute :attr_odt special-block)))
3410 (cond
3411 ;; Annotation.
3412 ((string= type "annotation")
3413 (let* ((author (or (plist-get attributes :author)
3414 (let ((author (plist-get info :author)))
3415 (and author (org-export-data author info)))))
3416 (date (or (plist-get attributes :date)
3417 ;; FIXME: Is `car' right thing to do below?
3418 (car (plist-get info :date)))))
3419 (format "\n<text:p>%s</text:p>"
3420 (format "<office:annotation>\n%s\n</office:annotation>"
3421 (concat
3422 (and author
3423 (format "<dc:creator>%s</dc:creator>" author))
3424 (and date
3425 (format "<dc:date>%s</dc:date>"
3426 (org-odt--format-timestamp date nil 'iso-date)))
3427 contents)))))
3428 ;; Textbox.
3429 ((string= type "textbox")
3430 ;; Textboxes an be used for centering tables etc horizontally
3431 ;; and vertically within a page.
3433 ;; In the example below, a landscape and centered table is
3434 ;; created in the middle of what is essentially a portrait
3435 ;; document.
3437 ;; Leading text.
3439 ;; #+ATTR_ODT: :style "OrgPageBreakLandscape"
3440 ;; #+PAGEBREAK:
3442 ;; #+ATTR_ODT: :width 5 :style "OrgPageImage" :anchor "page"
3443 ;; #+BEGIN_TEXTBOX
3444 ;; | a | b |
3445 ;; | e | f |
3446 ;; #+END_TEXTBOX
3448 ;; #+ATTR_ODT: :style "OrgPageBreakDefault"
3449 ;; #+PAGEBREAK:
3451 ;; Trailing text.
3452 (let ((width (org-odt--read-attribute special-block :width))
3453 (height (org-odt--read-attribute special-block :height))
3454 (style (org-odt--read-attribute special-block :style))
3455 (extra (org-odt--read-attribute special-block :extra))
3456 (anchor (org-odt--read-attribute special-block :anchor)))
3457 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3458 "Text_20_body" (org-odt--textbox contents width height
3459 style extra anchor))))
3460 (t contents))))
3463 ;;;; Src Block
3465 (defun org-odt-hfy-face-to-css (fn)
3466 "Create custom style for face FN.
3467 When FN is the default face, use its foreground and background
3468 properties to create \"OrgSrcBlock\" paragraph style. Otherwise
3469 use its color attribute to create a character style whose name
3470 is obtained from FN. Currently all attributes of FN other than
3471 color are ignored.
3473 The style name for a face FN is derived using the following
3474 operations on the face name in that order - de-dash, CamelCase
3475 and prefix with \"OrgSrc\". For example,
3476 `font-lock-function-name-face' is associated with
3477 \"OrgSrcFontLockFunctionNameFace\"."
3478 (let* ((css-list (hfy-face-to-style fn))
3479 (style-name (concat "OrgSrc"
3480 (mapconcat
3481 'capitalize (split-string
3482 (hfy-face-or-def-to-name fn) "-")
3483 "")))
3484 (color-val (cdr (assoc "color" css-list)))
3485 (background-color-val (cdr (assoc "background" css-list)))
3486 (style (and org-odt-create-custom-styles-for-srcblocks
3487 (cond
3488 ((eq fn 'default)
3489 (format org-odt-src-block-paragraph-format
3490 background-color-val color-val))
3492 (format
3494 <style:style style:name=\"%s\" style:family=\"text\">
3495 <style:text-properties fo:color=\"%s\"/>
3496 </style:style>" style-name color-val))))))
3497 (cons style-name style)))
3499 (defun org-odt-htmlfontify-string (line)
3500 (let* ((hfy-html-quote-regex "\\([<\"&> ]\\)")
3501 (hfy-html-quote-map '(("\"" "&quot;")
3502 ("<" "&lt;")
3503 ("&" "&amp;")
3504 (">" "&gt;")
3505 (" " "<text:s/>")
3506 (" " "<text:tab/>")))
3507 (hfy-face-to-css 'org-odt-hfy-face-to-css)
3508 (hfy-optimisations-1 (copy-sequence hfy-optimisations))
3509 (hfy-optimisations (add-to-list 'hfy-optimisations-1
3510 'body-text-only))
3511 (hfy-begin-span-handler
3512 (lambda (style text-block text-id text-begins-block-p)
3513 (insert (format "<text:span text:style-name=\"%s\">" style))))
3514 (hfy-end-span-handler (lambda nil (insert "</text:span>"))))
3515 (org-no-warnings (htmlfontify-string line))))
3517 (defun org-odt-do-format-code
3518 (code &optional lang refs retain-labels num-start)
3519 (let* ((lang (or (assoc-default lang org-src-lang-modes) lang))
3520 (lang-mode (and lang (intern (format "%s-mode" lang))))
3521 (code-lines (org-split-string code "\n"))
3522 (code-length (length code-lines))
3523 (use-htmlfontify-p (and (functionp lang-mode)
3524 org-odt-fontify-srcblocks
3525 (require 'htmlfontify nil t)
3526 (fboundp 'htmlfontify-string)))
3527 (code (if (not use-htmlfontify-p) code
3528 (with-temp-buffer
3529 (insert code)
3530 (funcall lang-mode)
3531 (font-lock-ensure)
3532 (buffer-string))))
3533 (fontifier (if use-htmlfontify-p 'org-odt-htmlfontify-string
3534 'org-odt--encode-plain-text))
3535 (par-style (if use-htmlfontify-p "OrgSrcBlock"
3536 "OrgFixedWidthBlock"))
3537 (i 0))
3538 (assert (= code-length (length (org-split-string code "\n"))))
3539 (setq code
3540 (org-export-format-code
3541 code
3542 (lambda (loc line-num ref)
3543 (setq par-style
3544 (concat par-style (and (= (incf i) code-length) "LastLine")))
3546 (setq loc (concat loc (and ref retain-labels (format " (%s)" ref))))
3547 (setq loc (funcall fontifier loc))
3548 (when ref
3549 (setq loc (org-odt--target loc (concat "coderef-" ref))))
3550 (assert par-style)
3551 (setq loc (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3552 par-style loc))
3553 (if (not line-num) loc
3554 (format "\n<text:list-item>%s\n</text:list-item>" loc)))
3555 num-start refs))
3556 (cond
3557 ((not num-start) code)
3558 ((= num-start 0)
3559 (format
3560 "\n<text:list text:style-name=\"OrgSrcBlockNumberedLine\"%s>%s</text:list>"
3561 " text:continue-numbering=\"false\"" code))
3563 (format
3564 "\n<text:list text:style-name=\"OrgSrcBlockNumberedLine\"%s>%s</text:list>"
3565 " text:continue-numbering=\"true\"" code)))))
3567 (defun org-odt-format-code (element info)
3568 (let* ((lang (org-element-property :language element))
3569 ;; Extract code and references.
3570 (code-info (org-export-unravel-code element))
3571 (code (car code-info))
3572 (refs (cdr code-info))
3573 ;; Does the src block contain labels?
3574 (retain-labels (org-element-property :retain-labels element))
3575 ;; Does it have line numbers?
3576 (num-start (case (org-element-property :number-lines element)
3577 (continued (org-export-get-loc element info))
3578 (new 0))))
3579 (org-odt-do-format-code code lang refs retain-labels num-start)))
3581 (defun org-odt-src-block (src-block contents info)
3582 "Transcode a SRC-BLOCK element from Org to ODT.
3583 CONTENTS holds the contents of the item. INFO is a plist holding
3584 contextual information."
3585 (let* ((lang (org-element-property :language src-block))
3586 (captions (org-odt-format-label src-block info 'definition))
3587 (caption (car captions)) (short-caption (cdr captions)))
3588 (concat
3589 (and caption
3590 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3591 "Listing" caption))
3592 (let ((--src-block (org-odt-format-code src-block info)))
3593 ;; Is `:textbox' property non-nil?
3594 (if (not (org-odt--read-attribute src-block :textbox)) --src-block
3595 ;; Yes. Enclose it in a Text Box.
3596 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3597 "Text_20_body"
3598 (org-odt--textbox --src-block nil nil nil)))))))
3601 ;;;; Statistics Cookie
3603 (defun org-odt-statistics-cookie (statistics-cookie contents info)
3604 "Transcode a STATISTICS-COOKIE object from Org to ODT.
3605 CONTENTS is nil. INFO is a plist holding contextual information."
3606 (let ((cookie-value (org-element-property :value statistics-cookie)))
3607 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3608 "OrgCode" cookie-value)))
3611 ;;;; Strike-Through
3613 (defun org-odt-strike-through (strike-through contents info)
3614 "Transcode STRIKE-THROUGH from Org to ODT.
3615 CONTENTS is the text with strike-through markup. INFO is a plist
3616 holding contextual information."
3617 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3618 "Strikethrough" contents))
3621 ;;;; Subscript
3623 (defun org-odt-subscript (subscript contents info)
3624 "Transcode a SUBSCRIPT object from Org to ODT.
3625 CONTENTS is the contents of the object. INFO is a plist holding
3626 contextual information."
3627 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3628 "OrgSubscript" contents))
3631 ;;;; Superscript
3633 (defun org-odt-superscript (superscript contents info)
3634 "Transcode a SUPERSCRIPT object from Org to ODT.
3635 CONTENTS is the contents of the object. INFO is a plist holding
3636 contextual information."
3637 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3638 "OrgSuperscript" contents))
3641 ;;;; Table Cell
3643 (defun org-odt-table-style-spec (element info)
3644 (let* ((table (org-export-get-parent-table element))
3645 (table-style (org-odt--read-attribute table :style)))
3646 (assoc table-style org-odt-table-styles)))
3648 (defun org-odt-get-table-cell-styles (table-cell info)
3649 "Retrieve styles applicable to a table cell.
3650 R and C are (zero-based) row and column numbers of the table
3651 cell. STYLE-SPEC is an entry in `org-odt-table-styles'
3652 applicable to the current table. It is `nil' if the table is not
3653 associated with any style attributes.
3655 Return a cons of (TABLE-CELL-STYLE-NAME . PARAGRAPH-STYLE-NAME).
3657 When STYLE-SPEC is nil, style the table cell the conventional way
3658 - choose cell borders based on row and column groupings and
3659 choose paragraph alignment based on `org-col-cookies' text
3660 property. See also
3661 `org-odt-get-paragraph-style-cookie-for-table-cell'.
3663 When STYLE-SPEC is non-nil, ignore the above cookie and return
3664 styles congruent with the ODF-1.2 specification."
3665 (let* ((table-cell-address (org-export-table-cell-address table-cell info))
3666 (r (car table-cell-address)) (c (cdr table-cell-address))
3667 (style-spec (org-odt-table-style-spec table-cell info))
3668 (table-dimensions (org-export-table-dimensions
3669 (org-export-get-parent-table table-cell)
3670 info)))
3671 (when style-spec
3672 ;; LibreOffice - particularly the Writer - honors neither table
3673 ;; templates nor custom table-cell styles. Inorder to retain
3674 ;; inter-operability with LibreOffice, only automatic styles are
3675 ;; used for styling of table-cells. The current implementation is
3676 ;; congruent with ODF-1.2 specification and hence is
3677 ;; future-compatible.
3679 ;; Additional Note: LibreOffice's AutoFormat facility for tables -
3680 ;; which recognizes as many as 16 different cell types - is much
3681 ;; richer. Unfortunately it is NOT amenable to easy configuration
3682 ;; by hand.
3683 (let* ((template-name (nth 1 style-spec))
3684 (cell-style-selectors (nth 2 style-spec))
3685 (cell-type
3686 (cond
3687 ((and (cdr (assoc 'use-first-column-styles cell-style-selectors))
3688 (= c 0)) "FirstColumn")
3689 ((and (cdr (assoc 'use-last-column-styles cell-style-selectors))
3690 (= (1+ c) (cdr table-dimensions)))
3691 "LastColumn")
3692 ((and (cdr (assoc 'use-first-row-styles cell-style-selectors))
3693 (= r 0)) "FirstRow")
3694 ((and (cdr (assoc 'use-last-row-styles cell-style-selectors))
3695 (= (1+ r) (car table-dimensions)))
3696 "LastRow")
3697 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
3698 (= (% r 2) 1)) "EvenRow")
3699 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
3700 (= (% r 2) 0)) "OddRow")
3701 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
3702 (= (% c 2) 1)) "EvenColumn")
3703 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
3704 (= (% c 2) 0)) "OddColumn")
3705 (t ""))))
3706 (concat template-name cell-type)))))
3708 (defun org-odt--table-cell-widths (table info)
3709 (let* ((user-widths (org-export-read-attribute :attr_odt table :widths))
3710 (user-width-p (and user-widths t))
3711 (user-widths (and user-width-p (split-string user-widths ","))))
3712 (org-element-map
3713 (org-element-map table 'table-row
3714 (lambda (row)
3715 (unless (eq (org-element-property :type row) 'rule) row))
3716 info 'first-match)
3717 'table-cell
3718 (lambda (table-cell)
3719 (or (and user-width-p (string-to-number (or (pop user-widths) "0")))
3720 (org-export-table-cell-width table-cell info) 0))
3721 info)))
3723 (defun org-odt-table-cell (table-cell contents info)
3724 "Transcode a TABLE-CELL element from Org to ODT.
3725 CONTENTS is nil. INFO is a plist used as a communication
3726 channel."
3727 (let* ((table-cell-address (org-export-table-cell-address table-cell info))
3728 (table-cell-borders (org-export-table-cell-borders table-cell info))
3729 (r (car table-cell-address))
3730 (c (cdr table-cell-address))
3731 (horiz-span (nth c (org-odt--table-cell-widths
3732 (org-export-get-parent-table table-cell) info)))
3733 (table-row (org-export-get-parent table-cell))
3734 (custom-style-prefix (org-odt-get-table-cell-styles
3735 table-cell info))
3736 (paragraph-style
3738 (and custom-style-prefix
3739 (format "%sTableParagraph" custom-style-prefix))
3740 (concat
3741 (cond
3742 ((and (= 1 (org-export-table-row-group table-row info))
3743 (org-export-table-has-header-p
3744 (org-export-get-parent-table table-row) info))
3745 "OrgTableHeading")
3746 ((let* ((table (org-export-get-parent-table table-cell))
3747 (table-header-columns
3748 (let ((cols (org-odt--read-attribute table :header-columns)))
3749 (and cols (read cols)))))
3750 (<= c (cond ((wholenump table-header-columns)
3751 (- table-header-columns 1))
3752 (table-header-columns 0)
3753 (t -1))))
3754 "OrgTableHeading")
3755 (t "OrgTableContents"))
3756 (capitalize (symbol-name (org-export-table-cell-alignment
3757 table-cell info))))))
3758 (cell-style-name
3760 (and custom-style-prefix (format "%sTableCell"
3761 custom-style-prefix))
3762 (concat
3763 "OrgTblCell"
3764 (when (memq 'above table-cell-borders) "T")
3765 (when (memq 'below table-cell-borders) "B")
3766 (when (memq 'left table-cell-borders) "L")
3767 (when (memq 'right table-cell-borders) "R"))))
3768 (cell-attributes
3769 (concat
3770 (format " table:style-name=\"%s\"" cell-style-name)
3771 (and (> horiz-span 0)
3772 (format " table:number-columns-spanned=\"%d\""
3773 (1+ horiz-span))))))
3774 (unless contents (setq contents ""))
3775 (concat
3776 (assert paragraph-style)
3777 (format "\n<table:table-cell%s>\n%s\n</table:table-cell>"
3778 cell-attributes
3779 (let ((table-cell-contents (org-element-contents table-cell)))
3780 (if (memq (org-element-type (car table-cell-contents))
3781 org-element-all-elements)
3782 contents
3783 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3784 paragraph-style contents))))
3785 (let (s)
3786 (dotimes (i horiz-span s)
3787 (setq s (concat s "\n<table:covered-table-cell/>"))))
3788 "\n")))
3791 ;;;; Table Row
3793 (defun org-odt-table-row (table-row contents info)
3794 "Transcode a TABLE-ROW element from Org to ODT.
3795 CONTENTS is the contents of the row. INFO is a plist used as a
3796 communication channel."
3797 ;; Rules are ignored since table separators are deduced from
3798 ;; borders of the current row.
3799 (when (eq (org-element-property :type table-row) 'standard)
3800 (let* ((rowgroup-tags
3801 (if (and (= 1 (org-export-table-row-group table-row info))
3802 (org-export-table-has-header-p
3803 (org-export-get-parent-table table-row) info))
3804 ;; If the row belongs to the first rowgroup and the
3805 ;; table has more than one row groups, then this row
3806 ;; belongs to the header row group.
3807 '("\n<table:table-header-rows>" . "\n</table:table-header-rows>")
3808 ;; Otherwise, it belongs to non-header row group.
3809 '("\n<table:table-rows>" . "\n</table:table-rows>"))))
3810 (concat
3811 ;; Does this row begin a rowgroup?
3812 (when (org-export-table-row-starts-rowgroup-p table-row info)
3813 (car rowgroup-tags))
3814 ;; Actual table row
3815 (let* ((custom-table-style (nth 1 (org-odt-table-style-spec table-row info)))
3816 (table-style (or custom-table-style "OrgTable"))
3817 (row-style (format "%sRow" table-style)))
3818 (format "\n<table:table-row table:style-name=\"%s\">\n%s\n</table:table-row>"
3819 row-style contents))
3820 ;; Does this row end a rowgroup?
3821 (when (org-export-table-row-ends-rowgroup-p table-row info)
3822 (cdr rowgroup-tags))))))
3825 ;;;; Table
3827 (defun org-odt--table (table contents info)
3828 "Transcode a TABLE element from Org to ODT.
3829 CONTENTS is the contents of the table. INFO is a plist holding
3830 contextual information."
3831 (case (org-element-property :type table)
3832 ;; Case 1: table.el doesn't support export to OD format. Strip
3833 ;; such tables from export.
3834 (table.el
3835 (prog1 nil
3836 (message
3837 (concat
3838 "(ox-odt): Found table.el-type table in the source Org file."
3839 " table.el doesn't support export to ODT format."
3840 " Stripping the table from export."))))
3841 ;; Case 2: Native Org tables.
3842 (otherwise
3843 (let* ((captions (org-odt-format-label table info 'definition))
3844 (caption (car captions)) (short-caption (cdr captions))
3845 (attributes (org-export-read-attribute :attr_odt table))
3846 (custom-table-style (nth 1 (org-odt-table-style-spec table info)))
3847 (table-column-specs
3848 (function
3849 (lambda (table info)
3850 (let* ((table-style (or custom-table-style "OrgTable"))
3851 (column-style (format "%sColumn" table-style)))
3852 (mapconcat
3853 (lambda (width)
3854 (setq width (1+ width))
3855 (let ((s (format
3856 "\n<table:table-column table:style-name=\"%s\"/>"
3857 column-style))
3858 out)
3859 (dotimes (i width out) (setq out (concat s out)))))
3860 (org-odt--table-cell-widths table info) "\n"))))))
3861 (concat
3862 ;; caption.
3863 (when caption
3864 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3865 "Table" caption))
3866 ;; begin table.
3867 (let* ((automatic-name
3868 (org-odt-add-automatic-style "Table" attributes)))
3869 (format
3870 "\n<table:table table:style-name=\"%s\"%s>"
3871 (or custom-table-style (cdr automatic-name) "OrgTable")
3872 (concat (when short-caption
3873 (format " table:name=\"%s\"" short-caption)))))
3874 ;; column specification.
3875 (funcall table-column-specs table info)
3876 ;; actual contents.
3877 "\n" contents
3878 ;; end table.
3879 "</table:table>")))))
3881 (defun org-odt-table (table contents info)
3882 "Transcode a TABLE element from Org to ODT.
3883 CONTENTS is the contents of the table. INFO is a plist holding
3884 contextual information.
3886 Use `org-odt--table' to typeset the table. Handle details
3887 pertaining to indentation here."
3888 (let* ((--element-preceded-by-table-p
3889 (function
3890 (lambda (element info)
3891 (loop for el in (org-export-get-previous-element element info t)
3892 thereis (eq (org-element-type el) 'table)))))
3893 (--walk-list-genealogy-and-collect-tags
3894 (function
3895 (lambda (table info)
3896 (let* ((genealogy (org-element-lineage table))
3897 (list-genealogy
3898 (when (eq (org-element-type (car genealogy)) 'item)
3899 (loop for el in genealogy
3900 when (memq (org-element-type el)
3901 '(item plain-list))
3902 collect el)))
3903 (llh-genealogy
3904 (apply 'nconc
3905 (loop for el in genealogy
3906 when (and (eq (org-element-type el) 'headline)
3907 (org-export-low-level-p el info))
3908 collect
3909 (list el
3910 (assq 'headline
3911 (org-element-contents
3912 (org-export-get-parent el)))))))
3913 parent-list)
3914 (nconc
3915 ;; Handle list genealogy.
3916 (loop for el in list-genealogy collect
3917 (case (org-element-type el)
3918 (plain-list
3919 (setq parent-list el)
3920 (cons "</text:list>"
3921 (format "\n<text:list text:style-name=\"%s\" %s>"
3922 (case (org-element-property :type el)
3923 (ordered "OrgNumberedList")
3924 (unordered "OrgBulletedList")
3925 (descriptive-1 "OrgDescriptionList")
3926 (descriptive-2 "OrgDescriptionList"))
3927 "text:continue-numbering=\"true\"")))
3928 (item
3929 (cond
3930 ((not parent-list)
3931 (if (funcall --element-preceded-by-table-p table info)
3932 '("</text:list-header>" . "<text:list-header>")
3933 '("</text:list-item>" . "<text:list-header>")))
3934 ((funcall --element-preceded-by-table-p
3935 parent-list info)
3936 '("</text:list-header>" . "<text:list-header>"))
3937 (t '("</text:list-item>" . "<text:list-item>"))))))
3938 ;; Handle low-level headlines.
3939 (loop for el in llh-genealogy
3940 with step = 'item collect
3941 (case step
3942 (plain-list
3943 (setq step 'item) ; Flip-flop
3944 (setq parent-list el)
3945 (cons "</text:list>"
3946 (format "\n<text:list text:style-name=\"%s\" %s>"
3947 (if (org-export-numbered-headline-p
3948 el info)
3949 "OrgNumberedList"
3950 "OrgBulletedList")
3951 "text:continue-numbering=\"true\"")))
3952 (item
3953 (setq step 'plain-list) ; Flip-flop
3954 (cond
3955 ((not parent-list)
3956 (if (funcall --element-preceded-by-table-p table info)
3957 '("</text:list-header>" . "<text:list-header>")
3958 '("</text:list-item>" . "<text:list-header>")))
3959 ((let ((section? (org-export-get-previous-element
3960 parent-list info)))
3961 (and section?
3962 (eq (org-element-type section?) 'section)
3963 (assq 'table (org-element-contents section?))))
3964 '("</text:list-header>" . "<text:list-header>"))
3966 '("</text:list-item>" . "<text:list-item>")))))))))))
3967 (close-open-tags (funcall --walk-list-genealogy-and-collect-tags
3968 table info)))
3969 ;; OpenDocument schema does not permit table to occur within a
3970 ;; list item.
3972 ;; One solution - the easiest and lightweight, in terms of
3973 ;; implementation - is to put the table in an indented text box
3974 ;; and make the text box part of the list-item. Unfortunately if
3975 ;; the table is big and spans multiple pages, the text box could
3976 ;; overflow. In this case, the following attribute will come
3977 ;; handy.
3979 ;; ,---- From OpenDocument-v1.1.pdf
3980 ;; | 15.27.28 Overflow behavior
3981 ;; |
3982 ;; | For text boxes contained within text document, the
3983 ;; | style:overflow-behavior property specifies the behavior of text
3984 ;; | boxes where the containing text does not fit into the text
3985 ;; | box.
3986 ;; |
3987 ;; | If the attribute's value is clip, the text that does not fit
3988 ;; | into the text box is not displayed.
3989 ;; |
3990 ;; | If the attribute value is auto-create-new-frame, a new frame
3991 ;; | will be created on the next page, with the same position and
3992 ;; | dimensions of the original frame.
3993 ;; |
3994 ;; | If the style:overflow-behavior property's value is
3995 ;; | auto-create-new-frame and the text box has a minimum width or
3996 ;; | height specified, then the text box will grow until the page
3997 ;; | bounds are reached before a new frame is created.
3998 ;; `----
4000 ;; Unfortunately, LibreOffice-3.4.6 doesn't honor
4001 ;; auto-create-new-frame property and always resorts to clipping
4002 ;; the text box. This results in table being truncated.
4004 ;; So we solve the problem the hard (and fun) way using list
4005 ;; continuations.
4007 ;; The problem only becomes more interesting if you take in to
4008 ;; account the following facts:
4010 ;; - Description lists are simulated as plain lists.
4011 ;; - Low-level headlines can be listified.
4012 ;; - In Org-mode, a table can occur not only as a regular list
4013 ;; item, but also within description lists and low-level
4014 ;; headlines.
4016 ;; See `org-odt--translate-description-lists' and
4017 ;; `org-odt-translate-low-level-headlines' for how this is
4018 ;; tackled.
4020 (concat "\n"
4021 ;; Discontinue the list.
4022 (mapconcat 'car close-open-tags "\n")
4023 ;; Put the table in an indented section.
4024 (let* ((table (org-odt--table table contents info))
4025 (level (/ (length (mapcar 'car close-open-tags)) 2))
4026 (style (format "OrgIndentedSection-Level-%d" level)))
4027 (when table (org-odt-format-section table style)))
4028 ;; Continue the list.
4029 (mapconcat 'cdr (nreverse close-open-tags) "\n"))))
4032 ;;;; Target
4034 (defun org-odt-target (target contents info)
4035 "Transcode a TARGET object from Org to ODT.
4036 CONTENTS is nil. INFO is a plist holding contextual
4037 information."
4038 (let ((value (org-element-property :value target)))
4039 (org-odt--target "" (org-export-solidify-link-text value))))
4042 ;;;; Timestamp
4044 (defun org-odt-timestamp (timestamp contents info)
4045 "Transcode a TIMESTAMP object from Org to ODT.
4046 CONTENTS is nil. INFO is a plist used as a communication
4047 channel."
4048 (let* ((raw-value (org-element-property :raw-value timestamp))
4049 (type (org-element-property :type timestamp)))
4050 (if (not org-odt-use-date-fields)
4051 (let ((value (org-odt-plain-text
4052 (org-timestamp-translate timestamp) info)))
4053 (case (org-element-property :type timestamp)
4054 ((active active-range)
4055 (format "<text:span text:style-name=\"%s\">%s</text:span>"
4056 "OrgActiveTimestamp" value))
4057 ((inactive inactive-range)
4058 (format "<text:span text:style-name=\"%s\">%s</text:span>"
4059 "OrgInactiveTimestamp" value))
4060 (otherwise value)))
4061 (case type
4062 (active
4063 (format "<text:span text:style-name=\"%s\">%s</text:span>"
4064 "OrgActiveTimestamp"
4065 (format "&lt;%s&gt;" (org-odt--format-timestamp timestamp))))
4066 (inactive
4067 (format "<text:span text:style-name=\"%s\">%s</text:span>"
4068 "OrgInactiveTimestamp"
4069 (format "[%s]" (org-odt--format-timestamp timestamp))))
4070 (active-range
4071 (format "<text:span text:style-name=\"%s\">%s</text:span>"
4072 "OrgActiveTimestamp"
4073 (format "&lt;%s&gt;&#x2013;&lt;%s&gt;"
4074 (org-odt--format-timestamp timestamp)
4075 (org-odt--format-timestamp timestamp 'end))))
4076 (inactive-range
4077 (format "<text:span text:style-name=\"%s\">%s</text:span>"
4078 "OrgInactiveTimestamp"
4079 (format "[%s]&#x2013;[%s]"
4080 (org-odt--format-timestamp timestamp)
4081 (org-odt--format-timestamp timestamp 'end))))
4082 (otherwise
4083 (format "<text:span text:style-name=\"%s\">%s</text:span>"
4084 "OrgDiaryTimestamp"
4085 (org-odt-plain-text (org-timestamp-translate timestamp)
4086 info)))))))
4089 ;;;; Underline
4091 (defun org-odt-underline (underline contents info)
4092 "Transcode UNDERLINE from Org to ODT.
4093 CONTENTS is the text with underline markup. INFO is a plist
4094 holding contextual information."
4095 (format "<text:span text:style-name=\"%s\">%s</text:span>"
4096 "Underline" contents))
4099 ;;;; Verbatim
4101 (defun org-odt-verbatim (verbatim contents info)
4102 "Transcode a VERBATIM object from Org to ODT.
4103 CONTENTS is nil. INFO is a plist used as a communication
4104 channel."
4105 (format "<text:span text:style-name=\"%s\">%s</text:span>"
4106 "OrgCode" (org-odt--encode-plain-text
4107 (org-element-property :value verbatim))))
4110 ;;;; Verse Block
4112 (defun org-odt-verse-block (verse-block contents info)
4113 "Transcode a VERSE-BLOCK element from Org to ODT.
4114 CONTENTS is verse block contents. INFO is a plist holding
4115 contextual information."
4116 ;; Add line breaks to each line of verse.
4117 (setq contents (replace-regexp-in-string
4118 "\\(<text:line-break/>\\)?[ \t]*\n"
4119 "<text:line-break/>" contents))
4120 ;; Replace tabs and spaces.
4121 (setq contents (org-odt--encode-tabs-and-spaces contents))
4122 ;; Surround it in a verse environment.
4123 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
4124 "OrgVerse" contents))
4128 ;;; Filters
4130 ;;;; LaTeX fragments
4132 (defun org-odt--translate-latex-fragments (tree backend info)
4133 (let ((processing-type (plist-get info :with-latex))
4134 (count 0))
4135 ;; Normalize processing-type to one of dvipng, mathml or verbatim.
4136 ;; If the desired converter is not available, force verbatim
4137 ;; processing.
4138 (case processing-type
4139 ((t mathml)
4140 (if (and (fboundp 'org-format-latex-mathml-available-p)
4141 (org-format-latex-mathml-available-p))
4142 (setq processing-type 'mathml)
4143 (message "LaTeX to MathML converter not available.")
4144 (setq processing-type 'verbatim)))
4145 ((dvipng imagemagick)
4146 (unless (and (org-check-external-command "latex" "" t)
4147 (org-check-external-command
4148 (if (eq processing-type 'dvipng) "dvipng" "convert") "" t))
4149 (message "LaTeX to PNG converter not available.")
4150 (setq processing-type 'verbatim)))
4151 (otherwise
4152 (message "Unknown LaTeX option. Forcing verbatim.")
4153 (setq processing-type 'verbatim)))
4155 ;; Store normalized value for later use.
4156 (when (plist-get info :with-latex)
4157 (plist-put info :with-latex processing-type))
4158 (message "Formatting LaTeX using %s" processing-type)
4160 ;; Convert `latex-fragment's and `latex-environment's.
4161 (when (memq processing-type '(mathml dvipng imagemagick))
4162 (org-element-map tree '(latex-fragment latex-environment)
4163 (lambda (latex-*)
4164 (incf count)
4165 (let* ((latex-frag (org-element-property :value latex-*))
4166 (input-file (plist-get info :input-file))
4167 (cache-dir (file-name-directory input-file))
4168 (cache-subdir (concat
4169 (case processing-type
4170 ((dvipng imagemagick) "ltxpng/")
4171 (mathml "ltxmathml/"))
4172 (file-name-sans-extension
4173 (file-name-nondirectory input-file))))
4174 (display-msg
4175 (case processing-type
4176 ((dvipng imagemagick) (format "Creating LaTeX Image %d..." count))
4177 (mathml (format "Creating MathML snippet %d..." count))))
4178 ;; Get an Org-style link to PNG image or the MathML
4179 ;; file.
4180 (org-link
4181 (let ((link (with-temp-buffer
4182 (insert latex-frag)
4183 (org-format-latex cache-subdir cache-dir
4184 nil display-msg
4185 nil processing-type)
4186 (buffer-substring-no-properties
4187 (point-min) (point-max)))))
4188 (if (not (string-match "file:\\([^]]*\\)" link))
4189 (prog1 nil (message "LaTeX Conversion failed."))
4190 link))))
4191 (when org-link
4192 ;; Conversion succeeded. Parse above Org-style link to a
4193 ;; `link' object.
4194 (let* ((link (car (org-element-map (with-temp-buffer
4195 (org-mode)
4196 (insert org-link)
4197 (org-element-parse-buffer))
4198 'link 'identity))))
4199 ;; Orphan the link.
4200 (org-element-put-property link :parent nil)
4201 (let* (
4202 (replacement
4203 (case (org-element-type latex-*)
4204 ;; Case 1: LaTeX environment.
4205 ;; Mimic a "standalone image or formula" by
4206 ;; enclosing the `link' in a `paragraph'.
4207 ;; Copy over original attributes, captions to
4208 ;; the enclosing paragraph.
4209 (latex-environment
4210 (org-element-adopt-elements
4211 (list 'paragraph
4212 (list :style "OrgFormula"
4213 :name (org-element-property :name
4214 latex-*)
4215 :caption (org-element-property :caption
4216 latex-*)))
4217 link))
4218 ;; Case 2: LaTeX fragment.
4219 ;; No special action.
4220 (latex-fragment link))))
4221 ;; Note down the object that link replaces.
4222 (org-element-put-property replacement :replaces
4223 (list (org-element-type latex-*)
4224 (list :value latex-frag)))
4225 ;; Replace now.
4226 (org-element-set-element latex-* replacement))))))
4227 info)))
4228 tree)
4231 ;;;; Description lists
4233 ;; This translator is necessary to handle indented tables in a uniform
4234 ;; manner. See comment in `org-odt--table'.
4236 ;; Depending on user option `org-odt-description-list-style',
4237 ;; description lists can be typeset either as in HTML documents or as
4238 ;; in LaTeX documents.
4240 (defun org-odt--translate-description-lists/html (tree backend info)
4241 ;; OpenDocument has no notion of a description list. So simulate it
4242 ;; using plain lists. Description lists in the exported document
4243 ;; are typeset in the same manner as they are in a typical HTML
4244 ;; document. See `org-odt--translate-description-lists/latex' for
4245 ;; yet another way of translation.
4247 ;; Specifically, a description list like this:
4249 ;; ,----
4250 ;; | - term-1 :: definition-1
4251 ;; |
4252 ;; | paragraph-1
4253 ;; |
4254 ;; | - term-2 :: definition-2
4255 ;; |
4256 ;; | paragraph-2
4257 ;; `----
4259 ;; gets translated in to the following form:
4261 ;; ,----
4262 ;; | - term-1
4263 ;; |
4264 ;; | - definition-1
4265 ;; |
4266 ;; | paragraph-1
4267 ;; |
4268 ;; | - term-2
4269 ;; |
4270 ;; | - definition-2
4271 ;; |
4272 ;; | paragraph-2
4273 ;; `----
4275 ;; Further effect is achieved by fixing the OD styles as below:
4277 ;; 1. Set the :type property of the simulated lists to
4278 ;; `descriptive-1' and `descriptive-2'. Map these to list-styles
4279 ;; that has *no* bullets whatsoever.
4281 ;; 2. The paragraph containing the definition term is styled to be
4282 ;; in bold.
4284 (org-element-map tree 'plain-list
4285 (lambda (el)
4286 (when (equal (org-element-property :type el) 'descriptive)
4287 (org-element-set-element
4289 (apply 'org-element-adopt-elements
4290 (list 'plain-list (list :type 'descriptive-1))
4291 (mapcar
4292 (lambda (item)
4293 (org-element-adopt-elements
4294 (list 'item (list :checkbox (org-element-property
4295 :checkbox item)))
4296 (list 'paragraph nil
4297 (list 'bold (list :style "OrgDescriptionTerm")
4298 (or (org-element-property :tag item) "(no term)")))
4299 (org-element-adopt-elements
4300 (list 'plain-list (list :type 'descriptive-2))
4301 (apply 'org-element-adopt-elements
4302 (list 'item nil)
4303 (org-element-contents item)))))
4304 (org-element-contents el)))))
4305 nil)
4306 info)
4307 tree)
4309 (defun org-odt--translate-description-lists/latex (tree backend info)
4310 ;; OpenDocument has no notion of a description list. So simulate it
4311 ;; using plain lists. Description lists in the exported document
4312 ;; are typeset in the same manner as they are in a typical LaTeX
4313 ;; style document. See `org-odt--translate-description-lists/html'
4314 ;; for yet another way of translation.
4316 ;; Specifically, a description list like this:
4318 ;; ,----
4319 ;; | - term-1 :: definition-1
4320 ;; |
4321 ;; | paragraph-1
4322 ;; |
4323 ;; | - term-2 :: definition-2
4324 ;; |
4325 ;; | paragraph-2
4326 ;; `----
4328 ;; gets translated in to the following form:
4330 ;; ,----
4331 ;; | - *term-1* definition-1
4332 ;; |
4333 ;; | - paragraph-1
4334 ;; |
4335 ;; | - *term-2* definition-2
4336 ;; |
4337 ;; | - paragraph-2
4338 ;; `----
4340 ;; Further effect is achieved by fixing the OD styles as below:
4342 ;; 1. Set the :type property of the simulated lists to
4343 ;; `descriptive-1' and `descriptive-2'. Map these to list-styles
4344 ;; that has *no* bullets whatsoever.
4346 ;; 2. The paragraph containing the definition term is styled to be
4347 ;; use hanging indent.
4349 (org-element-map tree 'plain-list
4350 (lambda (el)
4351 (when (equal (org-element-property :type el) 'descriptive)
4352 (org-element-set-element
4354 (apply 'org-element-adopt-elements
4355 (list 'plain-list (list :type 'descriptive-1))
4356 (mapcar
4357 (lambda (item)
4358 (let* ((item-contents (org-element-contents item))
4359 (leading-paragraph (car item-contents))
4360 (item-contents (cdr item-contents)))
4361 (org-element-adopt-elements
4362 (list 'item (list :checkbox (org-element-property :checkbox item)))
4363 (apply 'org-element-adopt-elements
4364 (list 'paragraph (list :style "OrgDescriptionDefinition"))
4365 (list 'bold (list :style "OrgDescriptionTerm" :post-blank 1)
4366 (or (org-element-property :tag item) "(no term)"))
4367 (org-element-contents leading-paragraph))
4368 (org-element-adopt-elements
4369 (list 'plain-list (list :type 'descriptive-2))
4370 (apply 'org-element-adopt-elements
4371 (list 'item nil)
4372 item-contents)))))
4373 (org-element-contents el)))))
4374 nil)
4375 info)
4376 tree)
4378 ;;;; List tables
4380 ;; Lists that are marked with attribute `:list-table' are called as
4381 ;; list tables. They will be rendered as a table within the exported
4382 ;; document.
4384 ;; Consider an example. The following list table
4386 ;; #+ATTR_ODT: :rel-width 80
4387 ;; #+ATTR_ODT: :list-table t
4388 ;; - Row 1
4389 ;; - 1.1
4390 ;; - 1.2
4391 ;; - 1.3
4392 ;; - -----
4393 ;; - Row 2
4394 ;; - 2.1
4395 ;; - 2.2
4396 ;; - 2.3
4398 ;; will be exported as though it were an Org table like the one show
4399 ;; below.
4401 ;; | Row 1 | 1.1 | 1.2 | 1.3 |
4402 ;; |-------+-----+-----+-----|
4403 ;; | Row 2 | 2.1 | 2.2 | 2.3 |
4405 ;; List tables can contain hrule (see example above). They can also
4406 ;; contain table specific attributes.
4408 ;; Note that org-tables are NOT multi-line and each line is mapped to
4409 ;; a unique row in the exported document. So if an exported table
4410 ;; needs to contain a single paragraph (with copious text) it needs to
4411 ;; be typed up in a single line. Editing such long lines using the
4412 ;; table editor will be a cumbersome task. Furthermore inclusion of
4413 ;; multi-paragraph text in a table cell is well-nigh impossible.
4415 ;; A LIST-TABLE circumvents above problems.
4417 ;; Note that in the example above the list items could be paragraphs
4418 ;; themselves and the list can be arbitrarily deep.
4420 ;; Inspired by following thread:
4421 ;; https://lists.gnu.org/archive/html/emacs-orgmode/2011-03/msg01101.html
4423 ;; Translate lists to tables
4425 (defun org-odt--translate-list-tables (tree backend info)
4426 (org-element-map tree 'plain-list
4427 (lambda (l1-list)
4428 (when (org-odt--read-attribute l1-list :list-table)
4429 ;; Replace list with table.
4430 (org-element-set-element
4431 l1-list
4432 ;; Build replacement table.
4433 (apply 'org-element-adopt-elements
4434 (list 'table (list :type 'org :attr_odt
4435 (org-element-property :attr_odt l1-list)))
4436 (org-element-map l1-list 'item
4437 (lambda (l1-item)
4438 (let* ((l1-item-contents (org-element-contents l1-item))
4439 l1-item-leading-text l2-list)
4440 ;; Remove Level-2 list from the Level-item. It
4441 ;; will be subsequently attached as table-cells.
4442 (let ((cur l1-item-contents) prev)
4443 (while (and cur (not (eq (org-element-type (car cur))
4444 'plain-list)))
4445 (setq prev cur)
4446 (setq cur (cdr cur)))
4447 (when prev
4448 (setcdr prev nil)
4449 (setq l2-list (car cur)))
4450 (setq l1-item-leading-text l1-item-contents))
4451 (cond
4452 ;; Check for hrule.
4453 ((and
4454 (null l2-list)
4455 (not (cdr l1-item-leading-text))
4456 (eq (org-element-type (car l1-item-leading-text))
4457 'paragraph)
4458 (string-match "\\`[[:space:]]*-\\{5,\\}[[:space:]]*\\'"
4459 (org-element-interpret-data
4460 (car l1-item-leading-text))))
4461 ;; Level-1 items start a table row.
4462 (org-element-adopt-elements
4463 (list 'table-row (list :type 'rule))))
4464 ;; No hrule.
4466 ;; Level-1 items start a table row.
4467 (apply 'org-element-adopt-elements
4468 (list 'table-row (list :type 'standard))
4469 ;; Leading text of level-1 item define
4470 ;; the first table-cell.
4471 (apply 'org-element-adopt-elements
4472 (list 'table-cell nil)
4473 l1-item-leading-text)
4474 ;; Level-2 items define subsequent
4475 ;; table-cells of the row.
4476 (org-element-map l2-list 'item
4477 (lambda (l2-item)
4478 (apply 'org-element-adopt-elements
4479 (list 'table-cell nil)
4480 (org-element-contents l2-item)))
4481 info nil 'item))))))
4482 info nil 'item))))
4483 nil)
4484 info)
4485 tree)
4488 ;;; Interactive functions
4490 (defun org-odt-create-manifest-file-entry (&rest args)
4491 (push args org-odt-manifest-file-entries))
4493 (defun org-odt-write-manifest-file ()
4494 (make-directory (concat org-odt-zip-dir "META-INF"))
4495 (let ((manifest-file (concat org-odt-zip-dir "META-INF/manifest.xml")))
4496 (with-current-buffer
4497 (let ((nxml-auto-insert-xml-declaration-flag nil))
4498 (find-file-noselect manifest-file t))
4499 (insert
4500 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
4501 <manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"1.2\">\n")
4502 (mapc
4503 (lambda (file-entry)
4504 (let* ((version (nth 2 file-entry))
4505 (extra (if (not version) ""
4506 (format " manifest:version=\"%s\"" version))))
4507 (insert
4508 (format org-odt-manifest-file-entry-tag
4509 (nth 0 file-entry) (nth 1 file-entry) extra))))
4510 org-odt-manifest-file-entries)
4511 (insert "\n</manifest:manifest>"))))
4513 (defmacro org-odt--export-wrap (out-file &rest body)
4514 `(let* ((--out-file ,out-file)
4515 (out-file-type (file-name-extension --out-file))
4516 ;; XML files created by the exporter.
4517 (org-odt-xml-files '("META-INF/manifest.xml" "content.xml"
4518 "meta.xml" "styles.xml"))
4519 ;; Encode all the above XML files using utf-8.
4520 (coding-system-for-write 'utf-8)
4521 (save-buffer-coding-system 'utf-8)
4522 ;; Initialize temporary workarea. All files that end up in
4523 ;; the exported document get parked/created here.
4524 (org-odt-zip-dir (file-name-as-directory
4525 (make-temp-file (format "%s-" out-file-type) t)))
4526 (org-odt-manifest-file-entries nil)
4527 (--cleanup-xml-buffers
4528 (function
4529 (lambda nil
4530 ;; Kill all XML buffers.
4531 (mapc (lambda (file)
4532 (let ((buf (find-buffer-visiting
4533 (concat org-odt-zip-dir file))))
4534 (when buf
4535 (with-current-buffer buf
4536 (set-buffer-modified-p nil)
4537 (kill-buffer buf)))))
4538 org-odt-xml-files)
4539 ;; Delete temporary directory and also other embedded
4540 ;; files that get copied there.
4541 (delete-directory org-odt-zip-dir t)))))
4542 (condition-case err
4543 (progn
4544 (unless (executable-find "zip")
4545 ;; Not at all OSes ship with zip by default
4546 (error "Executable \"zip\" needed for creating OpenDocument files"))
4547 ;; Do export. This creates a bunch of xml files ready to be
4548 ;; saved and zipped.
4549 (progn ,@body)
4550 ;; Create a manifest entry for content.xml.
4551 (org-odt-create-manifest-file-entry "text/xml" "content.xml")
4552 ;; Write mimetype file
4553 (let* ((mimetypes
4554 '(("odt" . "application/vnd.oasis.opendocument.text")
4555 ("odf" . "application/vnd.oasis.opendocument.formula")))
4556 (mimetype (cdr (assoc-string out-file-type mimetypes t))))
4557 (unless mimetype
4558 (error "Unknown OpenDocument backend %S" out-file-type))
4559 (write-region mimetype nil (concat org-odt-zip-dir "mimetype"))
4560 (org-odt-create-manifest-file-entry mimetype "/" "1.2"))
4561 ;; Write out the manifest entries before zipping
4562 (org-odt-write-manifest-file)
4563 ;; Save all XML files.
4564 (mapc (lambda (file)
4565 (let ((buf (find-buffer-visiting
4566 (concat org-odt-zip-dir file))))
4567 (when buf
4568 (with-current-buffer buf
4569 ;; Prettify output if needed.
4570 (when org-odt-prettify-xml
4571 (indent-region (point-min) (point-max)))
4572 (save-buffer 0)))))
4573 org-odt-xml-files)
4574 ;; Run zip.
4575 (let* ((target --out-file)
4576 (target-name (file-name-nondirectory target))
4577 (cmds `(("zip" "-mX0" ,target-name "mimetype")
4578 ("zip" "-rmTq" ,target-name "."))))
4579 ;; If a file with same name as the desired output file
4580 ;; exists, remove it.
4581 (when (file-exists-p target)
4582 (delete-file target))
4583 ;; Zip up the xml files.
4584 (let ((coding-system-for-write 'no-conversion) exitcode err-string)
4585 (message "Creating ODT file...")
4586 ;; Switch temporarily to content.xml. This way Zip
4587 ;; process will inherit `org-odt-zip-dir' as the current
4588 ;; directory.
4589 (with-current-buffer
4590 (find-file-noselect (concat org-odt-zip-dir "content.xml") t)
4591 (mapc
4592 (lambda (cmd)
4593 (message "Running %s" (mapconcat 'identity cmd " "))
4594 (setq err-string
4595 (with-output-to-string
4596 (setq exitcode
4597 (apply 'call-process (car cmd)
4598 nil standard-output nil (cdr cmd)))))
4599 (or (zerop exitcode)
4600 (error (concat "Unable to create OpenDocument file."
4601 (format " Zip failed with error (%s)"
4602 err-string)))))
4603 cmds)))
4604 ;; Move the zip file from temporary work directory to
4605 ;; user-mandated location.
4606 (rename-file (concat org-odt-zip-dir target-name) target)
4607 (message "Created %s" (expand-file-name target))
4608 ;; Cleanup work directory and work files.
4609 (funcall --cleanup-xml-buffers)
4610 ;; Open the OpenDocument file in archive-mode for
4611 ;; examination.
4612 (find-file-noselect target t)
4613 ;; Return exported file.
4614 (cond
4615 ;; Case 1: Conversion desired on exported file. Run the
4616 ;; converter on the OpenDocument file. Return the
4617 ;; converted file.
4618 (org-odt-preferred-output-format
4619 (or (org-odt-convert target org-odt-preferred-output-format)
4620 target))
4621 ;; Case 2: No further conversion. Return exported
4622 ;; OpenDocument file.
4623 (t target))))
4624 (error
4625 ;; Cleanup work directory and work files.
4626 (funcall --cleanup-xml-buffers)
4627 (message "OpenDocument export failed: %s"
4628 (error-message-string err))))))
4631 ;;;; Export to OpenDocument formula
4633 ;;;###autoload
4634 (defun org-odt-export-as-odf (latex-frag &optional odf-file)
4635 "Export LATEX-FRAG as OpenDocument formula file ODF-FILE.
4636 Use `org-create-math-formula' to convert LATEX-FRAG first to
4637 MathML. When invoked as an interactive command, use
4638 `org-latex-regexps' to infer LATEX-FRAG from currently active
4639 region. If no LaTeX fragments are found, prompt for it. Push
4640 MathML source to kill ring depending on the value of
4641 `org-export-copy-to-kill-ring'."
4642 (interactive
4643 `(,(let (frag)
4644 (setq frag (and (setq frag (and (region-active-p)
4645 (buffer-substring (region-beginning)
4646 (region-end))))
4647 (loop for e in org-latex-regexps
4648 thereis (when (string-match (nth 1 e) frag)
4649 (match-string (nth 2 e) frag)))))
4650 (read-string "LaTeX Fragment: " frag nil frag))
4651 ,(let ((odf-filename (expand-file-name
4652 (concat
4653 (file-name-sans-extension
4654 (or (file-name-nondirectory buffer-file-name)))
4655 "." "odf")
4656 (file-name-directory buffer-file-name))))
4657 (read-file-name "ODF filename: " nil odf-filename nil
4658 (file-name-nondirectory odf-filename)))))
4659 (let ((filename (or odf-file
4660 (expand-file-name
4661 (concat
4662 (file-name-sans-extension
4663 (or (file-name-nondirectory buffer-file-name)))
4664 "." "odf")
4665 (file-name-directory buffer-file-name)))))
4666 (org-odt--export-wrap
4667 filename
4668 (let* ((buffer (progn
4669 (require 'nxml-mode)
4670 (let ((nxml-auto-insert-xml-declaration-flag nil))
4671 (find-file-noselect (concat org-odt-zip-dir
4672 "content.xml") t)))))
4673 (set-buffer buffer)
4674 (set-buffer-file-coding-system coding-system-for-write)
4675 (let ((mathml (org-create-math-formula latex-frag)))
4676 (unless mathml (error "No Math formula created"))
4677 (insert mathml)
4678 ;; Add MathML to kill ring, if needed.
4679 (when (org-export--copy-to-kill-ring-p)
4680 (org-kill-new (buffer-string))))))))
4682 ;;;###autoload
4683 (defun org-odt-export-as-odf-and-open ()
4684 "Export LaTeX fragment as OpenDocument formula and immediately open it.
4685 Use `org-odt-export-as-odf' to read LaTeX fragment and OpenDocument
4686 formula file."
4687 (interactive)
4688 (org-open-file (call-interactively 'org-odt-export-as-odf) 'system))
4691 ;;;; Export to OpenDocument Text
4693 ;;;###autoload
4694 (defun org-odt-export-to-odt (&optional async subtreep visible-only ext-plist)
4695 "Export current buffer to a ODT file.
4697 If narrowing is active in the current buffer, only export its
4698 narrowed part.
4700 If a region is active, export that region.
4702 A non-nil optional argument ASYNC means the process should happen
4703 asynchronously. The resulting file should be accessible through
4704 the `org-export-stack' interface.
4706 When optional argument SUBTREEP is non-nil, export the sub-tree
4707 at point, extracting information from the headline properties
4708 first.
4710 When optional argument VISIBLE-ONLY is non-nil, don't export
4711 contents of hidden elements.
4713 EXT-PLIST, when provided, is a property list with external
4714 parameters overriding Org default settings, but still inferior to
4715 file-local settings.
4717 Return output file's name."
4718 (interactive)
4719 (let ((outfile (org-export-output-file-name ".odt" subtreep)))
4720 (if async
4721 (org-export-async-start (lambda (f) (org-export-add-to-stack f 'odt))
4722 `(expand-file-name
4723 (org-odt--export-wrap
4724 ,outfile
4725 (let* ((org-odt-embedded-images-count 0)
4726 (org-odt-embedded-formulas-count 0)
4727 (org-odt-automatic-styles nil)
4728 (org-odt-object-counters nil)
4729 ;; Let `htmlfontify' know that we are interested in
4730 ;; collecting styles.
4731 (hfy-user-sheet-assoc nil))
4732 ;; Initialize content.xml and kick-off the export
4733 ;; process.
4734 (let ((out-buf
4735 (progn
4736 (require 'nxml-mode)
4737 (let ((nxml-auto-insert-xml-declaration-flag nil))
4738 (find-file-noselect
4739 (concat org-odt-zip-dir "content.xml") t))))
4740 (output (org-export-as
4741 'odt ,subtreep ,visible-only nil ,ext-plist)))
4742 (with-current-buffer out-buf
4743 (erase-buffer)
4744 (insert output)))))))
4745 (org-odt--export-wrap
4746 outfile
4747 (let* ((org-odt-embedded-images-count 0)
4748 (org-odt-embedded-formulas-count 0)
4749 (org-odt-automatic-styles nil)
4750 (org-odt-object-counters nil)
4751 ;; Let `htmlfontify' know that we are interested in collecting
4752 ;; styles.
4753 (hfy-user-sheet-assoc nil))
4754 ;; Initialize content.xml and kick-off the export process.
4755 (let ((output (org-export-as 'odt subtreep visible-only nil ext-plist))
4756 (out-buf (progn
4757 (require 'nxml-mode)
4758 (let ((nxml-auto-insert-xml-declaration-flag nil))
4759 (find-file-noselect
4760 (concat org-odt-zip-dir "content.xml") t)))))
4761 (with-current-buffer out-buf (erase-buffer) (insert output))))))))
4764 ;;;; Convert between OpenDocument and other formats
4766 (defun org-odt-reachable-p (in-fmt out-fmt)
4767 "Return non-nil if IN-FMT can be converted to OUT-FMT."
4768 (catch 'done
4769 (let ((reachable-formats (org-odt-do-reachable-formats in-fmt)))
4770 (dolist (e reachable-formats)
4771 (let ((out-fmt-spec (assoc out-fmt (cdr e))))
4772 (when out-fmt-spec
4773 (throw 'done (cons (car e) out-fmt-spec))))))))
4775 (defun org-odt-do-convert (in-file out-fmt &optional prefix-arg)
4776 "Workhorse routine for `org-odt-convert'."
4777 (require 'browse-url)
4778 (let* ((in-file (expand-file-name (or in-file buffer-file-name)))
4779 (dummy (or (file-readable-p in-file)
4780 (error "Cannot read %s" in-file)))
4781 (in-fmt (file-name-extension in-file))
4782 (out-fmt (or out-fmt (error "Output format unspecified")))
4783 (how (or (org-odt-reachable-p in-fmt out-fmt)
4784 (error "Cannot convert from %s format to %s format?"
4785 in-fmt out-fmt)))
4786 (convert-process (car how))
4787 (out-file (concat (file-name-sans-extension in-file) "."
4788 (nth 1 (or (cdr how) out-fmt))))
4789 (extra-options (or (nth 2 (cdr how)) ""))
4790 (out-dir (file-name-directory in-file))
4791 (cmd (format-spec convert-process
4792 `((?i . ,(shell-quote-argument in-file))
4793 (?I . ,(browse-url-file-url in-file))
4794 (?f . ,out-fmt)
4795 (?o . ,out-file)
4796 (?O . ,(browse-url-file-url out-file))
4797 (?d . , (shell-quote-argument out-dir))
4798 (?D . ,(browse-url-file-url out-dir))
4799 (?x . ,extra-options)))))
4800 (when (file-exists-p out-file)
4801 (delete-file out-file))
4803 (message "Executing %s" cmd)
4804 (let ((cmd-output (shell-command-to-string cmd)))
4805 (message "%s" cmd-output))
4807 (cond
4808 ((file-exists-p out-file)
4809 (message "Exported to %s" out-file)
4810 (when prefix-arg
4811 (message "Opening %s..." out-file)
4812 (org-open-file out-file 'system))
4813 out-file)
4815 (message "Export to %s failed" out-file)
4816 nil))))
4818 (defun org-odt-do-reachable-formats (in-fmt)
4819 "Return verbose info about formats to which IN-FMT can be converted.
4820 Return a list where each element is of the
4821 form (CONVERTER-PROCESS . OUTPUT-FMT-ALIST). See
4822 `org-odt-convert-processes' for CONVERTER-PROCESS and see
4823 `org-odt-convert-capabilities' for OUTPUT-FMT-ALIST."
4824 (let* ((converter
4825 (and org-odt-convert-process
4826 (cadr (assoc-string org-odt-convert-process
4827 org-odt-convert-processes t))))
4828 (capabilities
4829 (and org-odt-convert-process
4830 (cadr (assoc-string org-odt-convert-process
4831 org-odt-convert-processes t))
4832 org-odt-convert-capabilities))
4833 reachable-formats)
4834 (when converter
4835 (dolist (c capabilities)
4836 (when (member in-fmt (nth 1 c))
4837 (push (cons converter (nth 2 c)) reachable-formats))))
4838 reachable-formats))
4840 (defun org-odt-reachable-formats (in-fmt)
4841 "Return list of formats to which IN-FMT can be converted.
4842 The list of the form (OUTPUT-FMT-1 OUTPUT-FMT-2 ...)."
4843 (let (l)
4844 (mapc (lambda (e) (add-to-list 'l e))
4845 (apply 'append (mapcar
4846 (lambda (e) (mapcar 'car (cdr e)))
4847 (org-odt-do-reachable-formats in-fmt))))
4850 (defun org-odt-convert-read-params ()
4851 "Return IN-FILE and OUT-FMT params for `org-odt-do-convert'.
4852 This is a helper routine for interactive use."
4853 (let* ((input (if (featurep 'ido) 'ido-completing-read 'completing-read))
4854 (in-file (read-file-name "File to be converted: "
4855 nil buffer-file-name t))
4856 (in-fmt (file-name-extension in-file))
4857 (out-fmt-choices (org-odt-reachable-formats in-fmt))
4858 (out-fmt
4859 (or (and out-fmt-choices
4860 (funcall input "Output format: "
4861 out-fmt-choices nil nil nil))
4862 (error
4863 "No known converter or no known output formats for %s files"
4864 in-fmt))))
4865 (list in-file out-fmt)))
4867 ;;;###autoload
4868 (defun org-odt-convert (&optional in-file out-fmt prefix-arg)
4869 "Convert IN-FILE to format OUT-FMT using a command line converter.
4870 IN-FILE is the file to be converted. If unspecified, it defaults
4871 to variable `buffer-file-name'. OUT-FMT is the desired output
4872 format. Use `org-odt-convert-process' as the converter.
4873 If PREFIX-ARG is non-nil then the newly converted file is opened
4874 using `org-open-file'."
4875 (interactive
4876 (append (org-odt-convert-read-params) current-prefix-arg))
4877 (org-odt-do-convert in-file out-fmt prefix-arg))
4879 ;;; Library Initializations
4881 (mapc
4882 (lambda (desc)
4883 ;; Let Emacs open all OpenDocument files in archive mode
4884 (add-to-list 'auto-mode-alist
4885 (cons (concat "\\." (car desc) "\\'") 'archive-mode)))
4886 org-odt-file-extensions)
4888 (provide 'ox-odt)
4890 ;;; ox-odt.el ends here