org-odt.el: When zip command fails, log its output as a message
[org-mode.git] / contrib / lisp / org-odt.el
blob4db2dc3330b27aa215cd9835c29e2dd955b5d152
1 ;;; org-odt.el --- OpenDocumentText export for Org-mode
3 ;; Copyright (C) 2010-2011 Jambunathan <kjambunathan at gmail dot com>
5 ;; Author: Jambunathan K <kjambunathan at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 0.8
10 ;; This file is not (yet) part of GNU Emacs.
11 ;; However, it is distributed under the same license.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;;; Code:
30 (eval-when-compile (require 'cl))
31 (require 'org-lparse)
33 (defun org-odt-end-export ()
34 (org-odt-fixup-label-references)
36 ;; remove empty paragraphs
37 (goto-char (point-min))
38 (while (re-search-forward
39 "<text:p\\( text:style-name=\"Text_20_body\"\\)?>[ \r\n\t]*</text:p>"
40 nil t)
41 (replace-match ""))
42 (goto-char (point-min))
44 ;; Convert whitespace place holders
45 (goto-char (point-min))
46 (let (beg end n)
47 (while (setq beg (next-single-property-change (point) 'org-whitespace))
48 (setq n (get-text-property beg 'org-whitespace)
49 end (next-single-property-change beg 'org-whitespace))
50 (goto-char beg)
51 (delete-region beg end)
52 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
53 (make-string n ?x)))))
55 ;; Remove empty lines at the beginning of the file.
56 (goto-char (point-min))
57 (when (looking-at "\\s-+\n") (replace-match ""))
59 ;; Remove display properties
60 (remove-text-properties (point-min) (point-max) '(display t)))
62 (defvar org-odt-suppress-xref nil)
63 (defconst org-export-odt-special-string-regexps
64 '(("\\\\-" . "&#x00ad;\\1") ; shy
65 ("---\\([^-]\\)" . "&#x2014;\\1") ; mdash
66 ("--\\([^-]\\)" . "&#x2013;\\1") ; ndash
67 ("\\.\\.\\." . "&#x2026;")) ; hellip
68 "Regular expressions for special string conversion.")
70 (defconst org-odt-lib-dir (file-name-directory load-file-name))
71 (defconst org-odt-data-dir
72 (let ((dir1 (expand-file-name "../odt" org-odt-lib-dir)) ; git
73 (dir2 (expand-file-name "./contrib/odt" org-odt-lib-dir))) ; elpa
74 (cond
75 ((file-directory-p dir1) dir1)
76 ((file-directory-p dir2) dir2)
77 (t (error "Cannot find factory styles file. Check package dir layout"))))
78 "Directory that holds auxiliary files used by the ODT exporter.
80 The 'styles' subdir contains the following xml files -
81 'OrgOdtStyles.xml' and 'OrgOdtContentTemplate.xml' - which are
82 used as factory settings of `org-export-odt-styles-file' and
83 `org-export-odt-content-template-file'.
85 The 'etc/schema' subdir contains rnc files for validating of
86 OpenDocument xml files.")
88 (defvar org-odt-file-extensions
89 '(("odt" . "OpenDocument Text")
90 ("ott" . "OpenDocument Text Template")
91 ("odm" . "OpenDocument Master Document")
92 ("ods" . "OpenDocument Spreadsheet")
93 ("ots" . "OpenDocument Spreadsheet Template")
94 ("odg" . "OpenDocument Drawing (Graphics)")
95 ("otg" . "OpenDocument Drawing Template")
96 ("odp" . "OpenDocument Presentation")
97 ("otp" . "OpenDocument Presentation Template")
98 ("odi" . "OpenDocument Image")
99 ("odf" . "OpenDocument Formula")
100 ("odc" . "OpenDocument Chart")
101 ("doc" . "Microsoft Text")
102 ("docx" . "Microsoft Text")
103 ("xls" . "Microsoft Spreadsheet")
104 ("xlsx" . "Microsoft Spreadsheet")
105 ("ppt" . "Microsoft Presentation")
106 ("pptx" . "Microsoft Presentation")))
108 (defvar org-odt-ms-file-extensions
109 '(("doc" . "Microsoft Text")
110 ("docx" . "Microsoft Text")
111 ("xls" . "Microsoft Spreadsheet")
112 ("xlsx" . "Microsoft Spreadsheet")
113 ("ppt" . "Microsoft Presentation")
114 ("pptx" . "Microsoft Presentation")))
116 ;; RelaxNG validation of OpenDocument xml files
117 (eval-after-load 'rng-nxml
118 '(setq rng-nxml-auto-validate-flag t))
120 (eval-after-load 'rng-loc
121 '(add-to-list 'rng-schema-locating-files
122 (expand-file-name "etc/schema/schemas.xml" org-odt-data-dir)))
124 (mapc
125 (lambda (desc)
126 ;; Let Org open all OpenDocument files using system-registered app
127 (add-to-list 'org-file-apps
128 (cons (concat "\\." (car desc) "\\'") 'system))
129 ;; Let Emacs open all OpenDocument files in archive mode
130 (add-to-list 'auto-mode-alist
131 (cons (concat "\\." (car desc) "\\'") 'archive-mode)))
132 org-odt-file-extensions)
134 (mapc
135 (lambda (desc)
136 ;; Let Org open all Microsoft files using system-registered app
137 (add-to-list 'org-file-apps
138 (cons (concat "\\." (car desc) "\\'") 'system)))
139 org-odt-ms-file-extensions)
141 ;; register the odt exporter with the pre-processor
142 (add-to-list 'org-export-backends 'odt)
144 ;; register the odt exporter with org-lparse library
145 (org-lparse-register-backend 'odt)
147 (defun org-odt-unload-function ()
148 (org-lparse-unregister-backend 'odt)
149 (remove-hook 'org-export-preprocess-after-blockquote-hook
150 'org-export-odt-preprocess-latex-fragments)
151 nil)
153 (defcustom org-export-odt-content-template-file nil
154 "Template file for \"content.xml\".
155 The exporter embeds the exported content just before
156 \"</office:text>\" element.
158 If unspecified, the file named \"OrgOdtContentTemplate.xml\"
159 under `org-odt-data-dir' is used."
160 :type 'file
161 :group 'org-export-odt)
163 (defcustom org-export-odt-styles-file nil
164 "Default styles file for use with ODT export.
165 Valid values are one of:
166 1. nil
167 2. path to a styles.xml file
168 3. path to a *.odt or a *.ott file
169 4. list of the form (ODT-OR-OTT-FILE (FILE-MEMBER-1 FILE-MEMBER-2
170 ...))
172 In case of option 1, an in-built styles.xml is used. See
173 `org-odt-data-dir' for more information.
175 In case of option 3, the specified file is unzipped and the
176 styles.xml embedded therein is used.
178 In case of option 4, the specified ODT-OR-OTT-FILE is unzipped
179 and FILE-MEMBER-1, FILE-MEMBER-2 etc are copied in to the
180 generated odt file. Use relative path for specifying the
181 FILE-MEMBERS. styles.xml must be specified as one of the
182 FILE-MEMBERS.
184 Use options 1, 2 or 3 only if styles.xml alone suffices for
185 achieving the desired formatting. Use option 4, if the styles.xml
186 references additional files like header and footer images for
187 achieving the desired formattting."
188 :group 'org-export-odt
189 :type
190 '(choice
191 (const :tag "Factory settings" nil)
192 (file :must-match t :tag "styles.xml")
193 (file :must-match t :tag "ODT or OTT file")
194 (list :tag "ODT or OTT file + Members"
195 (file :must-match t :tag "ODF Text or Text Template file")
196 (cons :tag "Members"
197 (file :tag " Member" "styles.xml")
198 (repeat (file :tag "Member"))))))
200 (defconst org-export-odt-tmpdir-prefix "odt-")
201 (defconst org-export-odt-bookmark-prefix "OrgXref.")
202 (defcustom org-export-odt-use-bookmarks-for-internal-links t
203 "Export Internal links as bookmarks?."
204 :type 'boolean
205 :group 'org-export-odt)
207 (defcustom org-export-odt-embed-images t
208 "Should the images be copied in to the odt file or just linked?"
209 :type 'boolean
210 :group 'org-export-odt)
212 (defcustom org-odt-export-inline-images 'maybe
213 "Non-nil means inline images into exported HTML pages.
214 This is done using an <img> tag. When nil, an anchor with href is used to
215 link to the image. If this option is `maybe', then images in links with
216 an empty description will be inlined, while images with a description will
217 be linked only."
218 :group 'org-odt-export
219 :type '(choice (const :tag "Never" nil)
220 (const :tag "Always" t)
221 (const :tag "When there is no description" maybe)))
223 (defcustom org-odt-export-inline-image-extensions
224 '("png" "jpeg" "jpg" "gif")
225 "Extensions of image files that can be inlined into HTML."
226 :type '(repeat (string :tag "Extension"))
227 :group 'org-odt-export)
229 (defcustom org-export-odt-pixels-per-inch display-pixels-per-inch
230 ;; FIXME add docstring
232 :type 'float
233 :group 'org-export-odt)
235 (defvar org-export-odt-default-org-styles-alist
236 '((paragraph . ((default . "Text_20_body")
237 (fixedwidth . "OrgFixedWidthBlock")
238 (verse . "OrgVerse")
239 (quote . "Quotations")
240 (blockquote . "Quotations")
241 (center . "OrgCenter")
242 (left . "OrgLeft")
243 (right . "OrgRight")
244 (title . "Heading_20_1.title")
245 (footnote . "Footnote")
246 (src . "OrgSrcBlock")
247 (illustration . "Illustration")
248 (table . "Table")
249 (definition-term . "Text_20_body_20_bold")
250 (horizontal-line . "Horizontal_20_Line")))
251 (character . ((bold . "Bold")
252 (emphasis . "Emphasis")
253 (code . "OrgCode")
254 (verbatim . "OrgCode")
255 (strike . "Strikethrough")
256 (underline . "Underline")
257 (subscript . "OrgSubscript")
258 (superscript . "OrgSuperscript")))
259 (list . ((ordered . "OrgNumberedList")
260 (unordered . "OrgBulletedList")
261 (description . "OrgDescriptionList"))))
262 "Default styles for various entities.")
264 (defvar org-export-odt-org-styles-alist org-export-odt-default-org-styles-alist)
265 (defun org-odt-get-style-name-for-entity (category &optional entity)
266 (let ((entity (or entity 'default)))
268 (cdr (assoc entity (cdr (assoc category
269 org-export-odt-org-styles-alist))))
270 (cdr (assoc entity (cdr (assoc category
271 org-export-odt-default-org-styles-alist))))
272 (error "Cannot determine style name for entity %s of type %s"
273 entity category))))
275 (defcustom org-export-odt-preferred-output-format nil
276 "Automatically post-process to this format after exporting to \"odt\".
277 Interactive commands `org-export-as-odt' and
278 `org-export-as-odt-and-open' export first to \"odt\" format and
279 then use an external converter to convert the resulting document
280 to this format.
282 The converter used is that specified with CONVERT-METHOD option
283 in `org-odt-get'. If the above option is unspecified then
284 `org-lparse-convert-process' is used.
286 The format specified here should be listed in OTHER-BACKENDS
287 option of `org-odt-get' or `org-lparse-convert-capabilities' as
288 appropriate."
289 :group 'org-odt
290 :type '(choice :convert-widget
291 (lambda (w)
292 (apply 'widget-convert (widget-type w)
293 (eval (car (widget-get w :args)))))
294 `((const :tag "None" nil)
295 ,@(mapcar (lambda (c)
296 `(const :tag ,(car c) ,(car c)))
297 (org-lparse-get-other-backends "odt")))))
299 ;;;###autoload
300 (defun org-export-as-odt-and-open (arg)
301 "Export the outline as ODT and immediately open it with a browser.
302 If there is an active region, export only the region.
303 The prefix ARG specifies how many levels of the outline should become
304 headlines. The default is 3. Lower levels will become bulleted lists."
305 (interactive "P")
306 (org-lparse-and-open
307 (or org-export-odt-preferred-output-format "odt") "odt" arg))
309 ;;;###autoload
310 (defun org-export-as-odt-batch ()
311 "Call the function `org-lparse-batch'.
312 This function can be used in batch processing as:
313 emacs --batch
314 --load=$HOME/lib/emacs/org.el
315 --eval \"(setq org-export-headline-levels 2)\"
316 --visit=MyFile --funcall org-export-as-odt-batch"
317 (org-lparse-batch "odt"))
319 ;;;###autoload
320 (defun org-export-as-odt-to-buffer (arg)
321 "Call `org-lparse-odt` with output to a temporary buffer.
322 No file is created. The prefix ARG is passed through to `org-lparse-to-buffer'."
323 (interactive "P")
324 (org-lparse-to-buffer "odt" arg))
326 ;;;###autoload
327 (defun org-replace-region-by-odt (beg end)
328 "Assume the current region has org-mode syntax, and convert it to ODT.
329 This can be used in any buffer. For example, you could write an
330 itemized list in org-mode syntax in an ODT buffer and then use this
331 command to convert it."
332 (interactive "r")
333 (org-replace-region-by "odt" beg end))
335 ;;;###autoload
336 (defun org-export-region-as-odt (beg end &optional body-only buffer)
337 "Convert region from BEG to END in org-mode buffer to ODT.
338 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
339 contents, and only produce the region of converted text, useful for
340 cut-and-paste operations.
341 If BUFFER is a buffer or a string, use/create that buffer as a target
342 of the converted ODT. If BUFFER is the symbol `string', return the
343 produced ODT as a string and leave not buffer behind. For example,
344 a Lisp program could call this function in the following way:
346 (setq odt (org-export-region-as-odt beg end t 'string))
348 When called interactively, the output buffer is selected, and shown
349 in a window. A non-interactive call will only return the buffer."
350 (interactive "r\nP")
351 (org-lparse-region "odt" beg end body-only buffer))
353 ;;; org-export-as-odt
354 ;;;###autoload
355 (defun org-export-as-odt (arg &optional hidden ext-plist
356 to-buffer body-only pub-dir)
357 "Export the outline as a OpenDocumentText file.
358 If there is an active region, export only the region. The prefix
359 ARG specifies how many levels of the outline should become
360 headlines. The default is 3. Lower levels will become bulleted
361 lists. HIDDEN is obsolete and does nothing.
362 EXT-PLIST is a property list with external parameters overriding
363 org-mode's default settings, but still inferior to file-local
364 settings. When TO-BUFFER is non-nil, create a buffer with that
365 name and export to that buffer. If TO-BUFFER is the symbol
366 `string', don't leave any buffer behind but just return the
367 resulting XML as a string. When BODY-ONLY is set, don't produce
368 the file header and footer, simply return the content of
369 <body>...</body>, without even the body tags themselves. When
370 PUB-DIR is set, use this as the publishing directory."
371 (interactive "P")
372 (org-lparse (or org-export-odt-preferred-output-format "odt")
373 "odt" arg hidden ext-plist to-buffer body-only pub-dir))
375 (defvar org-odt-entity-control-callbacks-alist
376 `((EXPORT
377 . (org-odt-begin-export org-odt-end-export))
378 (DOCUMENT-CONTENT
379 . (org-odt-begin-document-content org-odt-end-document-content))
380 (DOCUMENT-BODY
381 . (org-odt-begin-document-body org-odt-end-document-body))
382 (TOC
383 . (org-odt-begin-toc org-odt-end-toc))
384 (ENVIRONMENT
385 . (org-odt-begin-environment org-odt-end-environment))
386 (FOOTNOTE-DEFINITION
387 . (org-odt-begin-footnote-definition org-odt-end-footnote-definition))
388 (TABLE
389 . (org-odt-begin-table org-odt-end-table))
390 (TABLE-ROWGROUP
391 . (org-odt-begin-table-rowgroup org-odt-end-table-rowgroup))
392 (LIST
393 . (org-odt-begin-list org-odt-end-list))
394 (LIST-ITEM
395 . (org-odt-begin-list-item org-odt-end-list-item))
396 (OUTLINE
397 . (org-odt-begin-outline org-odt-end-outline))
398 (OUTLINE-TEXT
399 . (org-odt-begin-outline-text org-odt-end-outline-text))
400 (PARAGRAPH
401 . (org-odt-begin-paragraph org-odt-end-paragraph)))
404 (defvar org-odt-entity-format-callbacks-alist
405 `((EXTRA-TARGETS . org-lparse-format-extra-targets)
406 (ORG-TAGS . org-lparse-format-org-tags)
407 (SECTION-NUMBER . org-lparse-format-section-number)
408 (HEADLINE . org-odt-format-headline)
409 (TOC-ENTRY . org-odt-format-toc-entry)
410 (TOC-ITEM . org-odt-format-toc-item)
411 (TAGS . org-odt-format-tags)
412 (SPACES . org-odt-format-spaces)
413 (TABS . org-odt-format-tabs)
414 (LINE-BREAK . org-odt-format-line-break)
415 (FONTIFY . org-odt-format-fontify)
416 (TODO . org-lparse-format-todo)
417 (LINK . org-odt-format-link)
418 (INLINE-IMAGE . org-odt-format-inline-image)
419 (ORG-LINK . org-odt-format-org-link)
420 (HEADING . org-odt-format-heading)
421 (ANCHOR . org-odt-format-anchor)
422 (TABLE . org-lparse-format-table)
423 (TABLE-ROW . org-odt-format-table-row)
424 (TABLE-CELL . org-odt-format-table-cell)
425 (FOOTNOTES-SECTION . ignore)
426 (FOOTNOTE-REFERENCE . org-odt-format-footnote-reference)
427 (HORIZONTAL-LINE . org-odt-format-horizontal-line)
428 (COMMENT . org-odt-format-comment)
429 (LINE . org-odt-format-line)
430 (ORG-ENTITY . org-odt-format-org-entity))
433 ;;;_. callbacks
434 ;;;_. control callbacks
435 ;;;_ , document body
436 (defun org-odt-begin-office-body ()
437 ;; automatic styles
438 (insert-file-contents
439 (or org-export-odt-content-template-file
440 (expand-file-name "styles/OrgOdtContentTemplate.xml"
441 org-odt-data-dir)))
442 (goto-char (point-min))
443 (re-search-forward "</office:text>" nil nil)
444 (delete-region (match-beginning 0) (point-max)))
446 ;; Following variable is let bound when `org-do-lparse' is in
447 ;; progress. See org-html.el.
448 (defvar org-lparse-toc)
449 (defun org-odt-begin-document-body (opt-plist)
450 (org-odt-begin-office-body)
451 (let ((title (plist-get opt-plist :title)))
452 (when title
453 (insert
454 (org-odt-format-stylized-paragraph 'title title))))
456 ;; insert toc
457 (when org-lparse-toc
458 (insert "\n" org-lparse-toc "\n")))
460 (defvar org-lparse-body-only) ; let bound during org-do-lparse
461 (defvar org-lparse-to-buffer) ; let bound during org-do-lparse
462 (defun org-odt-end-document-body (opt-plist)
463 (unless org-lparse-body-only
464 (org-lparse-insert-tag "</office:text>")
465 (org-lparse-insert-tag "</office:body>")))
467 (defun org-odt-begin-document-content (opt-plist)
468 (ignore))
470 (defun org-odt-end-document-content ()
471 (org-lparse-insert-tag "</office:document-content>"))
473 (defun org-odt-begin-outline (level1 snumber title tags
474 target extra-targets class)
475 (org-lparse-insert
476 'HEADING (org-lparse-format
477 'HEADLINE title extra-targets tags snumber level1)
478 level1 target))
480 (defun org-odt-end-outline ()
481 (ignore))
483 (defun org-odt-begin-outline-text (level1 snumber class)
484 (ignore))
486 (defun org-odt-end-outline-text ()
487 (ignore))
489 (defun org-odt-begin-paragraph (&optional style)
490 (org-lparse-insert-tag
491 "<text:p%s>" (org-odt-get-extra-attrs-for-paragraph-style style)))
493 (defun org-odt-end-paragraph ()
494 (org-lparse-insert-tag "</text:p>"))
496 (defun org-odt-get-extra-attrs-for-paragraph-style (style)
497 (let (style-name)
498 (setq style-name
499 (cond
500 ((stringp style) style)
501 ((symbolp style) (org-odt-get-style-name-for-entity
502 'paragraph style))))
503 (unless style-name
504 (error "Don't know how to handle paragraph style %s" style))
505 (format " text:style-name=\"%s\"" style-name)))
507 (defun org-odt-format-stylized-paragraph (style text)
508 (org-odt-format-tags
509 '("<text:p%s>" . "</text:p>") text
510 (org-odt-get-extra-attrs-for-paragraph-style style)))
512 (defun org-odt-begin-environment (style)
513 (case style
514 ((blockquote verse center quote)
515 (org-lparse-begin-paragraph style)
516 (list))
517 ((fixedwidth native)
518 (org-lparse-end-paragraph)
519 (list))
520 (t (error "Unknown environment %s" style))))
522 (defun org-odt-end-environment (style)
523 (case style
524 ((blockquote verse center quote)
525 (org-lparse-end-paragraph)
526 (list))
527 ((fixedwidth native)
528 (org-lparse-begin-paragraph)
529 (list))
530 (t (error "Unknown environment %s" style))))
532 (defvar org-lparse-list-level) ; dynamically bound in org-do-lparse
533 (defun org-odt-begin-list (ltype)
534 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
535 ltype))
536 (let* ((style-name (org-odt-get-style-name-for-entity 'list ltype))
537 (extra (concat (when (= org-lparse-list-level 1)
538 " text:continue-numbering=\"false\"")
539 (when style-name
540 (format " text:style-name=\"%s\"" style-name)))))
541 (case ltype
542 ((ordered unordered description)
543 (org-lparse-end-paragraph)
544 (org-lparse-insert-tag "<text:list%s>" extra))
545 (t (error "Unknown list type: %s" ltype)))))
547 (defun org-odt-end-list (ltype)
548 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
549 ltype))
550 (if ltype
551 (org-lparse-insert-tag "</text:list>")
552 (error "Unknown list type: %s" ltype)))
554 (defun org-odt-begin-list-item (ltype &optional arg headline)
555 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
556 ltype))
557 (case ltype
558 (ordered
559 (assert (not headline) t)
560 (let* ((counter arg) (extra ""))
561 (org-lparse-insert-tag "<text:list-item>")
562 (org-lparse-begin-paragraph)))
563 (unordered
564 (let* ((id arg) (extra ""))
565 (org-lparse-insert-tag "<text:list-item>")
566 (org-lparse-begin-paragraph)
567 (insert (if headline (org-odt-format-target headline id)
568 (org-odt-format-bookmark "" id)))))
569 (description
570 (assert (not headline) t)
571 (let ((term (or arg "(no term)")))
572 (insert
573 (org-odt-format-tags
574 '("<text:list-item>" . "</text:list-item>")
575 (org-odt-format-stylized-paragraph 'definition-term term)))
576 (org-lparse-begin-list-item 'unordered)
577 (org-lparse-begin-list 'description)
578 (org-lparse-begin-list-item 'unordered)))
579 (t (error "Unknown list type"))))
581 (defun org-odt-end-list-item (ltype)
582 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
583 ltype))
584 (case ltype
585 ((ordered unordered)
586 (org-lparse-insert-tag "</text:list-item>"))
587 (description
588 (org-lparse-end-list-item-1)
589 (org-lparse-end-list 'description)
590 (org-lparse-end-list-item-1))
591 (t (error "Unknown list type"))))
593 ;; Following variables are let bound when table emission is in
594 ;; progress. See org-lparse.el.
595 (defvar org-lparse-table-begin-marker)
596 (defvar org-lparse-table-ncols)
597 (defvar org-lparse-table-rowgrp-open)
598 (defvar org-lparse-table-rownum)
599 (defvar org-lparse-table-cur-rowgrp-is-hdr)
600 (defvar org-lparse-table-is-styled)
601 (defvar org-lparse-table-rowgrp-info)
602 (defvar org-lparse-table-colalign-vector)
604 (defvar org-odt-table-style nil
605 "Table style specified by \"#+ATTR_ODT: <style-name>\" line.
606 This is set during `org-odt-begin-table'.")
608 (defvar org-odt-table-style-spec nil
609 "Entry for `org-odt-table-style' in `org-export-odt-table-styles'.")
611 (defcustom org-export-odt-table-styles nil
612 "Specify how Table Styles should be derived from a Table Template.
613 This is a list where each element is of the
614 form (TABLE-STYLE-NAME TABLE-TEMPLATE-NAME TABLE-CELL-OPTIONS).
616 TABLE-STYLE-NAME is the style associated with the table through
617 `org-odt-table-style'.
619 TABLE-TEMPLATE-NAME is a set of - upto 9 - automatic
620 TABLE-CELL-STYLE-NAMEs and PARAGRAPH-STYLE-NAMEs (as defined
621 below) that is included in
622 `org-export-odt-content-template-file'.
624 TABLE-CELL-STYLE-NAME := TABLE-TEMPLATE-NAME + TABLE-CELL-TYPE +
625 \"TableCell\"
626 PARAGRAPH-STYLE-NAME := TABLE-TEMPLATE-NAME + TABLE-CELL-TYPE +
627 \"TableParagraph\"
628 TABLE-CELL-TYPE := \"FirstRow\" | \"LastColumn\" |
629 \"FirstRow\" | \"LastRow\" |
630 \"EvenRow\" | \"OddRow\" |
631 \"EvenColumn\" | \"OddColumn\" | \"\"
632 where \"+\" above denotes string concatenation.
634 TABLE-CELL-OPTIONS is an alist where each element is of the
635 form (TABLE-CELL-STYLE-SELECTOR . ON-OR-OFF).
636 TABLE-CELL-STYLE-SELECTOR := `use-first-row-styles' |
637 `use-last-row-styles' |
638 `use-first-column-styles' |
639 `use-last-column-styles' |
640 `use-banding-rows-styles' |
641 `use-banding-columns-styles' |
642 `use-first-row-styles'
643 ON-OR-OFF := `t' | `nil'
645 For example, with the following configuration
647 \(setq org-export-odt-table-styles
648 '\(\(\"TableWithHeaderRowsAndColumns\" \"Custom\"
649 \(\(use-first-row-styles . t\)
650 \(use-first-column-styles . t\)\)\)
651 \(\"TableWithHeaderColumns\" \"Custom\"
652 \(\(use-first-column-styles . t\)\)\)\)\)
654 1. A table associated with \"TableWithHeaderRowsAndColumns\"
655 style will use the following table-cell styles -
656 \"CustomFirstRowTableCell\", \"CustomFirstColumnTableCell\",
657 \"CustomTableCell\" and the following paragraph styles
658 \"CustomFirstRowTableParagraph\",
659 \"CustomFirstColumnTableParagraph\", \"CustomTableParagraph\"
660 as appropriate.
662 2. A table associated with \"TableWithHeaderColumns\" style will
663 use the following table-cell styles -
664 \"CustomFirstColumnTableCell\", \"CustomTableCell\" and the
665 following paragraph styles
666 \"CustomFirstColumnTableParagraph\", \"CustomTableParagraph\"
667 as appropriate..
669 Note that TABLE-TEMPLATE-NAME corresponds to the
670 \"<table:table-template>\" elements contained within
671 \"<office:styles>\". The entries (TABLE-STYLE-NAME
672 TABLE-TEMPLATE-NAME TABLE-CELL-OPTIONS) correspond to
673 \"table:template-name\" and \"table:use-first-row-styles\" etc
674 attributes of \"<table:table>\" element. Refer ODF-1.2
675 specification for more information. Also consult the
676 implementation filed under `org-odt-get-table-cell-styles'."
677 :group 'org-export-odt
678 :type '(choice
679 (const :tag "None" nil)
680 (repeat :tag "Table Styles"
681 (list :tag "Table Style Specification"
682 (string :tag "Table Style Name")
683 (string :tag "Table Template Name")
684 (alist :options (use-first-row-styles
685 use-last-row-styles
686 use-first-column-styles
687 use-last-column-styles
688 use-banding-rows-styles
689 use-banding-columns-styles)
690 :key-type symbol
691 :value-type (const :tag "True" t))))))
693 (defun org-odt-begin-table (caption label attributes)
694 (setq org-odt-table-style attributes)
695 (setq org-odt-table-style-spec
696 (assoc org-odt-table-style org-export-odt-table-styles))
697 (when label
698 (insert
699 (org-odt-format-stylized-paragraph
700 'table (org-odt-format-entity-caption label caption "Table"))))
701 (org-lparse-insert-tag
702 "<table:table table:name=\"%s\" table:style-name=\"%s\">"
703 (or label "") (or (nth 1 org-odt-table-style-spec) "OrgTable"))
704 (setq org-lparse-table-begin-marker (point)))
706 (defun org-odt-end-table ()
707 (goto-char org-lparse-table-begin-marker)
708 (loop for level from 0 below org-lparse-table-ncols
709 do (insert
710 (org-odt-format-tags
711 "<table:table-column table:style-name=\"%sColumn\"/>"
712 "" (or (nth 1 org-odt-table-style-spec) "OrgTable"))))
714 ;; fill style attributes for table cells
715 (when org-lparse-table-is-styled
716 (while (re-search-forward "@@\\(table-cell:p\\|table-cell:style-name\\)@@\\([0-9]+\\)@@\\([0-9]+\\)@@" nil t)
717 (let* ((spec (match-string 1))
718 (r (string-to-number (match-string 2)))
719 (c (string-to-number (match-string 3)))
720 (cell-styles (org-odt-get-table-cell-styles
721 r c org-odt-table-style-spec))
722 (table-cell-style (car cell-styles))
723 (table-cell-paragraph-style (cdr cell-styles)))
724 (cond
725 ((equal spec "table-cell:p")
726 (replace-match table-cell-paragraph-style t t))
727 ((equal spec "table-cell:style-name")
728 (replace-match table-cell-style t t))))))
729 (goto-char (point-max))
730 (org-lparse-insert-tag "</table:table>"))
732 (defun org-odt-begin-table-rowgroup (&optional is-header-row)
733 (when org-lparse-table-rowgrp-open
734 (org-lparse-end 'TABLE-ROWGROUP))
735 (org-lparse-insert-tag (if is-header-row
736 "<table:table-header-rows>"
737 "<table:table-rows>"))
738 (setq org-lparse-table-rowgrp-open t)
739 (setq org-lparse-table-cur-rowgrp-is-hdr is-header-row))
741 (defun org-odt-end-table-rowgroup ()
742 (when org-lparse-table-rowgrp-open
743 (setq org-lparse-table-rowgrp-open nil)
744 (org-lparse-insert-tag
745 (if org-lparse-table-cur-rowgrp-is-hdr
746 "</table:table-header-rows>" "</table:table-rows>"))))
748 (defun org-odt-format-table-row (row)
749 (org-odt-format-tags
750 '("<table:table-row>" . "</table:table-row>") row))
752 (defun org-odt-get-table-cell-styles (r c &optional style-spec)
753 "Retrieve styles applicable to a table cell.
754 R and C are (zero-based) row and column numbers of the table
755 cell. STYLE-SPEC is an entry in `org-export-odt-table-styles'
756 applicable to the current table. It is `nil' if the table is not
757 associated with any style attributes.
759 Return a cons of (TABLE-CELL-STYLE-NAME . PARAGRAPH-STYLE-NAME).
761 When STYLE-SPEC is nil, style the table cell the conventional way
762 - choose cell borders based on row and column groupings and
763 choose paragraph alignment based on `org-col-cookies' text
764 property. See also
765 `org-odt-get-paragraph-style-cookie-for-table-cell'.
767 When STYLE-SPEC is non-nil, ignore the above cookie and return
768 styles congruent with the ODF-1.2 specification."
769 (cond
770 (style-spec
772 ;; LibreOffice - particularly the Writer - honors neither table
773 ;; templates nor custom table-cell styles. Inorder to retain
774 ;; inter-operability with LibreOffice, only automatic styles are
775 ;; used for styling of table-cells. The current implementation is
776 ;; congruent with ODF-1.2 specification and hence is
777 ;; future-compatible.
779 ;; Additional Note: LibreOffice's AutoFormat facility for tables -
780 ;; which recognizes as many as 16 different cell types - is much
781 ;; richer. Unfortunately it is NOT amenable to easy configuration
782 ;; by hand.
784 (let* ((template-name (nth 1 style-spec))
785 (cell-style-selectors (nth 2 style-spec))
786 (cell-type
787 (cond
788 ((and (cdr (assoc 'use-first-column-styles cell-style-selectors))
789 (= c 0)) "FirstColumn")
790 ((and (cdr (assoc 'use-last-column-styles cell-style-selectors))
791 (= c (1- org-lparse-table-ncols))) "LastColumn")
792 ((and (cdr (assoc 'use-first-row-styles cell-style-selectors))
793 (= r 0)) "FirstRow")
794 ((and (cdr (assoc 'use-last-row-styles cell-style-selectors))
795 (= r org-lparse-table-rownum))
796 "LastRow")
797 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
798 (= (% r 2) 1)) "EvenRow")
799 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
800 (= (% r 2) 0)) "OddRow")
801 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
802 (= (% c 2) 1)) "EvenColumn")
803 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
804 (= (% c 2) 0)) "OddColumn")
805 (t ""))))
806 (cons
807 (concat template-name cell-type "TableCell")
808 (concat template-name cell-type "TableParagraph"))))
810 (cons
811 (concat
812 "OrgTblCell"
813 (cond
814 ((= r 0) "T")
815 ((eq (cdr (assoc r org-lparse-table-rowgrp-info)) :start) "T")
816 (t ""))
817 (when (= r org-lparse-table-rownum) "B")
818 (cond
819 ((= c 0) "")
820 ((or (memq (nth c org-table-colgroup-info) '(:start :startend))
821 (memq (nth (1- c) org-table-colgroup-info) '(:end :startend))) "L")
822 (t "")))
823 (capitalize (aref org-lparse-table-colalign-vector c))))))
825 (defun org-odt-get-paragraph-style-cookie-for-table-cell (r c)
826 (concat
827 (and (not org-odt-table-style-spec)
828 (cond
829 (org-lparse-table-cur-rowgrp-is-hdr "OrgTableHeading")
830 ((and (= c 0) (org-lparse-get 'TABLE-FIRST-COLUMN-AS-LABELS))
831 "OrgTableHeading")
832 (t "OrgTableContents")))
833 (and org-lparse-table-is-styled
834 (format "@@table-cell:p@@%03d@@%03d@@" r c))))
836 (defun org-odt-get-style-name-cookie-for-table-cell (r c)
837 (when org-lparse-table-is-styled
838 (format "@@table-cell:style-name@@%03d@@%03d@@" r c)))
840 (defun org-odt-format-table-cell (data r c)
841 (let* ((paragraph-style-cookie
842 (org-odt-get-paragraph-style-cookie-for-table-cell r c))
843 (style-name-cookie
844 (org-odt-get-style-name-cookie-for-table-cell r c))
845 (extra (if style-name-cookie
846 (format " table:style-name=\"%s\"" style-name-cookie) "")))
847 (org-odt-format-tags
848 '("<table:table-cell%s>" . "</table:table-cell>")
849 (if org-lparse-list-table-p data
850 (org-odt-format-stylized-paragraph paragraph-style-cookie data)) extra)))
852 (defun org-odt-begin-footnote-definition (n)
853 (org-lparse-begin-paragraph 'footnote))
855 (defun org-odt-end-footnote-definition (n)
856 (org-lparse-end-paragraph))
858 (defun org-odt-begin-toc (lang-specific-heading)
859 (insert
860 (format "
861 <text:table-of-content text:style-name=\"Sect2\" text:protected=\"true\" text:name=\"Table of Contents1\">
862 <text:table-of-content-source text:outline-level=\"10\">
863 <text:index-title-template text:style-name=\"Contents_20_Heading\">%s</text:index-title-template>
864 " lang-specific-heading))
866 (loop for level from 1 upto 10
867 do (insert (format
869 <text:table-of-content-entry-template text:outline-level=\"%d\" text:style-name=\"Contents_20_%d\">
870 <text:index-entry-link-start text:style-name=\"Internet_20_link\"/>
871 <text:index-entry-chapter/>
872 <text:index-entry-text/>
873 <text:index-entry-link-end/>
874 </text:table-of-content-entry-template>
875 " level level)))
877 (insert
878 (format "
879 </text:table-of-content-source>
881 <text:index-body>
882 <text:index-title text:style-name=\"Sect1\" text:name=\"Table of Contents1_Head\">
883 <text:p text:style-name=\"Contents_20_Heading\">%s</text:p>
884 </text:index-title>
885 " lang-specific-heading)))
887 (defun org-odt-end-toc ()
888 (insert "
889 </text:index-body>
890 </text:table-of-content>
893 (defun org-odt-format-toc-entry (snumber todo headline tags href)
894 (setq headline (concat
895 (and org-export-with-section-numbers
896 (concat snumber ". "))
897 headline
898 (and tags
899 (concat
900 (org-lparse-format 'SPACES 3)
901 (org-lparse-format 'FONTIFY tags "tag")))))
902 (when todo
903 (setq headline (org-lparse-format 'FONTIFY headline "todo")))
905 (let ((org-odt-suppress-xref t))
906 (org-odt-format-link headline (concat "#" href))))
908 (defun org-odt-format-toc-item (toc-entry level org-last-level)
909 (let ((style (format "Contents_20_%d"
910 (+ level (or (org-lparse-get 'TOPLEVEL-HLEVEL) 1) -1))))
911 (insert "\n" (org-odt-format-stylized-paragraph style toc-entry) "\n")))
913 ;; Following variable is let bound during 'ORG-LINK callback. See
914 ;; org-html.el
915 (defvar org-lparse-link-description-is-image nil)
916 (defun org-odt-format-link (desc href &optional attr)
917 (cond
918 ((and (= (string-to-char href) ?#) (not org-odt-suppress-xref))
919 (setq href (concat org-export-odt-bookmark-prefix (substring href 1)))
920 (org-odt-format-tags
921 '("<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"%s\">" .
922 "</text:bookmark-ref>")
923 desc href))
924 (org-lparse-link-description-is-image
925 (org-odt-format-tags
926 '("<draw:a xlink:type=\"simple\" xlink:href=\"%s\" %s>" . "</draw:a>")
927 desc href (or attr "")))
929 (org-odt-format-tags
930 '("<text:a xlink:type=\"simple\" xlink:href=\"%s\" %s>" . "</text:a>")
931 desc href (or attr "")))))
933 (defun org-odt-format-spaces (n)
934 (cond
935 ((= n 1) " ")
936 ((> n 1) (concat
937 " " (org-odt-format-tags "<text:s text:c=\"%d\"/>" "" (1- n))))
938 (t "")))
940 (defun org-odt-format-tabs (&optional n)
941 (let ((tab "<text:tab/>")
942 (n (or n 1)))
943 (insert tab)))
945 (defun org-odt-format-line-break ()
946 (org-odt-format-tags "<text:line-break/>" ""))
948 (defun org-odt-format-horizontal-line ()
949 (org-odt-format-stylized-paragraph 'horizontal-line ""))
951 (defun org-odt-format-line (line)
952 (case org-lparse-dyn-current-environment
953 (fixedwidth (concat
954 (org-odt-format-stylized-paragraph
955 'fixedwidth (org-odt-fill-tabs-and-spaces
956 (org-xml-encode-plain-text line))) "\n"))
957 (t (concat line "\n"))))
959 (defun org-odt-format-comment (fmt &rest args)
960 (let ((comment (apply 'format fmt args)))
961 (format "\n<!-- %s -->\n" comment)))
963 (defun org-odt-format-org-entity (wd)
964 (org-entity-get-representation wd 'utf8))
966 (defun org-odt-fill-tabs-and-spaces (line)
967 (replace-regexp-in-string
968 "\\([\t]\\|\\([ ]+\\)\\)" (lambda (s)
969 (cond
970 ((string= s "\t") (org-odt-format-tabs))
971 (t (org-odt-format-spaces (length s))))) line))
973 (defcustom org-export-odt-use-htmlfontify t
974 "Specify whether or not source blocks need to be fontified.
975 Turn this option on if you want to colorize the source code
976 blocks in the exported file. For colorization to work, you need
977 to make available an enhanced version of `htmlfontify' library."
978 :type 'boolean
979 :group 'org-export-odt)
981 (defun org-odt-format-source-code-or-example-plain
982 (lines lang caption textareap cols rows num cont rpllbl fmt)
983 "Format source or example blocks much like fixedwidth blocks.
984 Use this when `org-export-odt-use-htmlfontify' option is turned
985 off."
986 (setq lines (org-export-number-lines (org-xml-encode-plain-text-lines lines)
987 0 0 num cont rpllbl fmt))
988 (mapconcat
989 (lambda (line)
990 (org-odt-format-stylized-paragraph
991 'fixedwidth (org-odt-fill-tabs-and-spaces line)))
992 (org-split-string lines "[\r\n]") "\n"))
994 (defvar org-src-block-paragraph-format
995 "<style:style style:name=\"OrgSrcBlock\" style:family=\"paragraph\" style:parent-style-name=\"Preformatted_20_Text\">
996 <style:paragraph-properties fo:background-color=\"%s\" fo:padding=\"0.049cm\" fo:border=\"0.51pt solid #000000\" style:shadow=\"none\">
997 <style:background-image/>
998 </style:paragraph-properties>
999 <style:text-properties fo:color=\"%s\"/>
1000 </style:style>"
1001 "Custom paragraph style for colorized source and example blocks.
1002 This style is much the same as that of \"OrgFixedWidthBlock\"
1003 except that the foreground and background colors are set
1004 according to the default face identified by the `htmlfontify'.")
1006 (defun org-odt-hfy-face-to-css (fn)
1007 "Create custom style for face FN.
1008 When FN is the default face, use it's foreground and background
1009 properties to create \"OrgSrcBlock\" paragraph style. Otherwise
1010 use it's color attribute to create a character style whose name
1011 is obtained from FN. Currently all attributes of FN other than
1012 color are ignored.
1014 The style name for a face FN is derived using the following
1015 operations on the face name in that order - de-dash, CamelCase
1016 and prefix with \"OrgSrc\". For example,
1017 `font-lock-function-name-face' is associated with
1018 \"OrgSrcFontLockFunctionNameFace\"."
1019 (let* ((css-list (hfy-face-to-style fn))
1020 (style-name ((lambda (fn)
1021 (concat "OrgSrc"
1022 (mapconcat
1023 'capitalize (split-string
1024 (hfy-face-or-def-to-name fn) "-")
1025 ""))) fn))
1026 (color-val (cdr (assoc "color" css-list)))
1027 (background-color-val (cdr (assoc "background" css-list)))
1028 (style (and org-export-odt-create-custom-styles-for-srcblocks
1029 (cond
1030 ((eq fn 'default)
1031 (format org-src-block-paragraph-format
1032 background-color-val color-val))
1034 (format
1036 <style:style style:name=\"%s\" style:family=\"text\">
1037 <style:text-properties fo:color=\"%s\"/>
1038 </style:style>" style-name color-val))))))
1039 (cons style-name style)))
1041 (defcustom org-export-odt-create-custom-styles-for-srcblocks t
1042 "Whether custom styles for colorized source blocks be automatically created.
1043 When this option is turned on, the exporter creates custom styles
1044 for source blocks based on the advice of `htmlfontify'. Creation
1045 of custom styles happen as part of `org-odt-hfy-face-to-css'.
1047 When this option is turned off exporter does not create such
1048 styles.
1050 Use the latter option if you do not want the custom styles to be
1051 based on your current display settings. It is necessary that the
1052 styles.xml already contains needed styles for colorizing to work.
1054 This variable is effective only if
1055 `org-export-odt-use-htmlfontify' is turned on."
1056 :group 'org-export-odt
1057 :type 'boolean)
1059 (defun org-odt-insert-custom-styles-for-srcblocks (styles)
1060 "Save STYLES used for colorizing of source blocks.
1061 Update styles.xml with styles that were collected as part of
1062 `org-odt-hfy-face-to-css' callbacks."
1063 (when styles
1064 (with-current-buffer
1065 (find-file-noselect (expand-file-name "styles.xml") t)
1066 (goto-char (point-min))
1067 (when (re-search-forward "</office:styles>" nil t)
1068 (goto-char (match-beginning 0))
1069 (insert "\n<!-- Org Htmlfontify Styles -->\n" styles "\n")))))
1071 (defun org-odt-format-source-code-or-example-colored
1072 (lines lang caption textareap cols rows num cont rpllbl fmt)
1073 "Format source or example blocks using `htmlfontify-string'.
1074 Use this routine when `org-export-odt-use-htmlfontify' option is
1075 turned on."
1076 (let* ((lang-m (and lang (or (cdr (assoc lang org-src-lang-modes)) lang)))
1077 (mode (and lang-m (intern (concat (if (symbolp lang-m)
1078 (symbol-name lang-m)
1079 lang-m) "-mode"))))
1080 (org-inhibit-startup t)
1081 (org-startup-folded nil)
1082 (lines (with-temp-buffer
1083 (insert lines)
1084 (if (functionp mode) (funcall mode) (fundamental-mode))
1085 (font-lock-fontify-buffer)
1086 (buffer-string)))
1087 (hfy-html-quote-regex "\\([<\"&> ]\\)")
1088 (hfy-html-quote-map '(("\"" "&quot;")
1089 ("<" "&lt;")
1090 ("&" "&amp;")
1091 (">" "&gt;")
1092 (" " "<text:s/>")
1093 (" " "<text:tab/>")))
1094 (hfy-face-to-css 'org-odt-hfy-face-to-css)
1095 (hfy-optimisations-1 (copy-seq hfy-optimisations))
1096 (hfy-optimisations (add-to-list 'hfy-optimisations-1
1097 'body-text-only))
1098 (hfy-begin-span-handler
1099 (lambda (style text-block text-id text-begins-block-p)
1100 (insert (format "<text:span text:style-name=\"%s\">" style))))
1101 (hfy-end-span-handler (lambda nil (insert "</text:span>"))))
1102 (when (fboundp 'htmlfontify-string)
1103 (mapconcat
1104 (lambda (line)
1105 (org-odt-format-stylized-paragraph 'src (htmlfontify-string line)))
1106 (org-split-string lines "[\r\n]") "\n"))))
1108 (defun org-odt-format-source-code-or-example (lines lang caption textareap
1109 cols rows num cont
1110 rpllbl fmt)
1111 "Format source or example blocks for export.
1112 Use `org-odt-format-source-code-or-example-plain' or
1113 `org-odt-format-source-code-or-example-colored' depending on the
1114 value of `org-export-odt-use-htmlfontify."
1115 (funcall
1116 (if (and org-export-odt-use-htmlfontify
1117 (or (featurep 'htmlfontify) (require 'htmlfontify))
1118 (fboundp 'htmlfontify-string))
1119 'org-odt-format-source-code-or-example-colored
1120 'org-odt-format-source-code-or-example-plain)
1121 lines lang caption textareap cols rows num cont rpllbl fmt))
1123 (defun org-xml-encode-plain-text-lines (rtn)
1124 (mapconcat 'org-xml-encode-plain-text (org-split-string rtn "[\r\n]") "\n"))
1126 (defun org-odt-remap-stylenames (style-name)
1128 (cdr (assoc style-name '(("timestamp-wrapper" . "OrgTimestampWrapper")
1129 ("timestamp" . "OrgTimestamp")
1130 ("timestamp-kwd" . "OrgTimestampKeyword")
1131 ("tag" . "OrgTag")
1132 ("todo" . "OrgTodo")
1133 ("done" . "OrgDone")
1134 ("target" . "OrgTarget"))))
1135 style-name))
1137 (defun org-odt-format-fontify (text style &optional id)
1138 (let* ((style-name
1139 (cond
1140 ((stringp style)
1141 (org-odt-remap-stylenames style))
1142 ((symbolp style)
1143 (org-odt-get-style-name-for-entity 'character style))
1144 ((listp style)
1145 (assert (< 1 (length style)))
1146 (let ((parent-style (pop style)))
1147 (mapconcat (lambda (s)
1148 ;; (assert (stringp s) t)
1149 (org-odt-remap-stylenames s)) style "")
1150 (org-odt-remap-stylenames parent-style)))
1151 (t (error "Don't how to handle style %s" style)))))
1152 (org-odt-format-tags
1153 '("<text:span text:style-name=\"%s\">" . "</text:span>")
1154 text style-name)))
1156 (defun org-odt-relocate-relative-path (path dir)
1157 (if (file-name-absolute-p path) path
1158 (file-relative-name (expand-file-name path dir)
1159 (expand-file-name "eyecandy" dir))))
1161 (defun org-odt-format-inline-image (thefile)
1162 (let* ((thelink (if (file-name-absolute-p thefile) thefile
1163 (org-xml-format-href
1164 (org-odt-relocate-relative-path
1165 thefile org-current-export-file))))
1166 (href
1167 (org-odt-format-tags
1168 "<draw:image xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>" ""
1169 (if org-export-odt-embed-images
1170 (org-odt-copy-image-file thefile) thelink))))
1171 (org-export-odt-format-image thefile href)))
1173 (defun org-export-odt-format-formula (src href &optional embed-as)
1174 "Create image tag with source and attributes."
1175 (save-match-data
1176 (let* ((caption (org-find-text-property-in-string 'org-caption src))
1177 (caption (and caption (org-xml-format-desc caption)))
1178 (label (org-find-text-property-in-string 'org-label src))
1179 (embed-as (or embed-as
1180 (and (org-find-text-property-in-string
1181 'org-latex-src src)
1182 (org-find-text-property-in-string
1183 'org-latex-src-embed-type src))
1184 'paragraph))
1185 width height)
1186 (cond
1187 ((eq embed-as 'character)
1188 (org-odt-format-entity "InlineFormula" href width height))
1190 (org-lparse-end-paragraph)
1191 (org-lparse-insert-list-table
1192 `((,(org-odt-format-entity
1193 (if caption "CaptionedDisplayFormula" "DisplayFormula")
1194 href width height caption nil)
1195 ,(if (not label) ""
1196 (org-odt-format-entity-caption label nil "Equation"))))
1197 nil nil nil "OrgEquation" nil '((1 "c" 8) (2 "c" 1)))
1198 (throw 'nextline nil))))))
1200 (defvar org-odt-embedded-formulas-count 0)
1201 (defun org-odt-copy-formula-file (path)
1202 "Returns the internal name of the file"
1203 (let* ((src-file (expand-file-name
1204 path (file-name-directory org-current-export-file)))
1205 (target-dir (format "Formula-%04d/"
1206 (incf org-odt-embedded-formulas-count)))
1207 (target-file (concat target-dir "content.xml")))
1208 (when (not org-lparse-to-buffer)
1209 (message "Embedding %s as %s ..."
1210 (substring-no-properties path) target-file)
1212 (make-directory target-dir)
1213 (org-odt-create-manifest-file-entry
1214 "application/vnd.oasis.opendocument.formula" target-dir "1.2")
1216 (copy-file src-file target-file 'overwrite)
1217 (org-odt-create-manifest-file-entry "text/xml" target-file))
1218 target-file))
1220 (defun org-odt-format-inline-formula (thefile)
1221 (let* ((thelink (if (file-name-absolute-p thefile) thefile
1222 (org-xml-format-href
1223 (org-odt-relocate-relative-path
1224 thefile org-current-export-file))))
1225 (href
1226 (org-odt-format-tags
1227 "<draw:object xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>" ""
1228 (file-name-directory (org-odt-copy-formula-file thefile)))))
1229 (org-export-odt-format-formula thefile href)))
1231 (defun org-odt-is-formula-link-p (file)
1232 (member (downcase (file-name-extension file)) '("mathml")))
1234 (defun org-odt-format-org-link (opt-plist type-1 path fragment desc attr
1235 descp)
1236 "Make an HTML link.
1237 OPT-PLIST is an options list.
1238 TYPE is the device-type of the link (THIS://foo.html)
1239 PATH is the path of the link (http://THIS#locationx)
1240 FRAGMENT is the fragment part of the link, if any (foo.html#THIS)
1241 DESC is the link description, if any.
1242 ATTR is a string of other attributes of the a element.
1243 MAY-INLINE-P allows inlining it as an image."
1244 (declare (special org-lparse-par-open))
1245 (save-match-data
1246 (let* ((may-inline-p
1247 (and (member type-1 '("http" "https" "file"))
1248 (org-lparse-should-inline-p path descp)
1249 (not fragment)))
1250 (type (if (equal type-1 "id") "file" type-1))
1251 (filename path)
1252 (thefile path))
1253 (cond
1254 ;; check for inlined images
1255 ((and (member type '("file"))
1256 (not fragment)
1257 (org-file-image-p
1258 filename org-odt-export-inline-image-extensions)
1259 (or (eq t org-odt-export-inline-images)
1260 (and org-odt-export-inline-images (not descp))))
1261 (org-odt-format-inline-image thefile))
1262 ;; check for embedded formulas
1263 ((and (member type '("file"))
1264 (not fragment)
1265 (org-odt-is-formula-link-p filename)
1266 (or (not descp)))
1267 (org-odt-format-inline-formula thefile))
1269 (when (string= type "file")
1270 (setq thefile
1271 (cond
1272 ((file-name-absolute-p path)
1273 (concat "file://" (expand-file-name path)))
1274 (t (org-odt-relocate-relative-path
1275 thefile org-current-export-file)))))
1277 (when (and (member type '("" "http" "https" "file" "coderef"))
1278 fragment)
1279 (setq thefile (concat thefile "#" fragment)))
1281 (setq thefile (org-xml-format-href thefile))
1283 (when (not (member type '("" "file" "coderef")))
1284 (setq thefile (concat type ":" thefile)))
1286 (let ((org-odt-suppress-xref (string= type "coderef")))
1287 (org-odt-format-link
1288 (org-xml-format-desc desc) thefile attr)))))))
1290 (defun org-odt-format-heading (text level &optional id)
1291 (let* ((text (if id (org-odt-format-target text id) text)))
1292 (org-odt-format-tags
1293 '("<text:h text:style-name=\"Heading_20_%s\" text:outline-level=\"%s\">" .
1294 "</text:h>") text level level)))
1296 (defun org-odt-format-headline (title extra-targets tags
1297 &optional snumber level)
1298 (concat
1299 (org-lparse-format 'EXTRA-TARGETS extra-targets)
1301 ;; No need to generate section numbers. They are auto-generated by
1302 ;; the application
1304 ;; (concat (org-lparse-format 'SECTION-NUMBER snumber level) " ")
1305 title
1306 (and tags (concat (org-lparse-format 'SPACES 3)
1307 (org-lparse-format 'ORG-TAGS tags)))))
1309 (defun org-odt-format-anchor (text name &optional class)
1310 (org-odt-format-target text name))
1312 (defun org-odt-format-bookmark (text id)
1313 (if id
1314 (org-odt-format-tags "<text:bookmark text:name=\"%s\"/>" text id)
1315 text))
1317 (defun org-odt-format-target (text id)
1318 (let ((name (concat org-export-odt-bookmark-prefix id)))
1319 (concat
1320 (and id (org-odt-format-tags
1321 "<text:bookmark-start text:name=\"%s\"/>" "" name))
1322 (org-odt-format-bookmark text id)
1323 (and id (org-odt-format-tags
1324 "<text:bookmark-end text:name=\"%s\"/>" "" name)))))
1326 (defun org-odt-format-footnote (n def)
1327 (let ((id (concat "fn" n))
1328 (note-class "footnote")
1329 (par-style "Footnote"))
1330 (org-odt-format-tags
1331 '("<text:note text:id=\"%s\" text:note-class=\"%s\">" .
1332 "</text:note>")
1333 (concat
1334 (org-odt-format-tags
1335 '("<text:note-citation>" . "</text:note-citation>")
1337 (org-odt-format-tags
1338 '("<text:note-body>" . "</text:note-body>")
1339 def))
1340 id note-class)))
1342 (defun org-odt-format-footnote-reference (n def refcnt)
1343 (if (= refcnt 1)
1344 (org-odt-format-footnote n def)
1345 (org-odt-format-footnote-ref n)))
1347 (defun org-odt-format-footnote-ref (n)
1348 (let ((note-class "footnote")
1349 (ref-format "text")
1350 (ref-name (concat "fn" n)))
1351 (org-odt-format-tags
1352 '("<text:span text:style-name=\"%s\">" . "</text:span>")
1353 (org-odt-format-tags
1354 '("<text:note-ref text:note-class=\"%s\" text:reference-format=\"%s\" text:ref-name=\"%s\">" . "</text:note-ref>")
1355 n note-class ref-format ref-name)
1356 "OrgSuperscript")))
1358 (defun org-odt-get-image-name (file-name)
1359 (require 'sha1)
1360 (file-relative-name
1361 (expand-file-name
1362 (concat (sha1 file-name) "." (file-name-extension file-name)) "Pictures")))
1364 (defun org-export-odt-format-image (src href &optional embed-as)
1365 "Create image tag with source and attributes."
1366 (save-match-data
1367 (let* ((caption (org-find-text-property-in-string 'org-caption src))
1368 (caption (and caption (org-xml-format-desc caption)))
1369 (attr (org-find-text-property-in-string 'org-attributes src))
1370 (label (org-find-text-property-in-string 'org-label src))
1371 (embed-as (or embed-as
1372 (if (org-find-text-property-in-string
1373 'org-latex-src src)
1374 (or (org-find-text-property-in-string
1375 'org-latex-src-embed-type src) 'character)
1376 'paragraph)))
1377 (attr-plist (when attr (read attr)))
1378 (size (org-odt-image-size-from-file
1379 src (plist-get attr-plist :width)
1380 (plist-get attr-plist :height)
1381 (plist-get attr-plist :scale) nil embed-as))
1382 (width (car size)) (height (cdr size)))
1383 (cond
1384 ((not (or caption label))
1385 (case embed-as
1386 (paragraph (org-odt-format-entity "DisplayImage" href width height))
1387 (character (org-odt-format-entity "InlineImage" href width height))
1388 (t (error "Unknown value for embed-as %S" embed-as))))
1390 (org-odt-format-entity
1391 "CaptionedDisplayImage" href width height caption label))))))
1393 (defun org-odt-format-frame (text width height style &optional
1394 extra anchor-type)
1395 (let ((frame-attrs
1396 (concat
1397 (if width (format " svg:width=\"%0.2fcm\"" width) "")
1398 (if height (format " svg:height=\"%0.2fcm\"" height) "")
1399 extra
1400 (format " text:anchor-type=\"%s\"" (or anchor-type "paragraph")))))
1401 (org-odt-format-tags
1402 '("<draw:frame draw:style-name=\"%s\"%s>" . "</draw:frame>")
1403 text style frame-attrs)))
1405 (defun org-odt-format-textbox (text width height style &optional
1406 extra anchor-type)
1407 (org-odt-format-frame
1408 (org-odt-format-tags
1409 '("<draw:text-box %s>" . "</draw:text-box>")
1410 text (concat (format " fo:min-height=\"%0.2fcm\"" (or height .2))
1411 (format " fo:min-width=\"%0.2fcm\"" (or width .2))))
1412 width nil style extra anchor-type))
1414 (defun org-odt-format-inlinetask (heading content
1415 &optional todo priority tags)
1416 (org-odt-format-stylized-paragraph
1417 nil (org-odt-format-textbox
1418 (concat (org-odt-format-stylized-paragraph
1419 "OrgInlineTaskHeading"
1420 (org-lparse-format
1421 'HEADLINE (concat (org-lparse-format-todo todo) " " heading)
1422 nil tags))
1423 content) nil nil "OrgInlineTaskFrame" " style:rel-width=\"100%\"")))
1425 (defvar org-odt-entity-frame-styles
1426 '(("InlineImage" "Figure" ("OrgInlineImage" nil "as-char"))
1427 ("DisplayImage" "Figure" ("OrgDisplayImage" nil "paragraph"))
1428 ("CaptionedDisplayImage" "Figure"
1429 ("OrgCaptionedImage"
1430 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
1431 ("OrgImageCaptionFrame"))
1432 ("InlineFormula" "Equation" ("OrgInlineFormula" nil "as-char"))
1433 ("DisplayFormula" "Equation" ("OrgDisplayFormula" nil "as-char"))
1434 ("CaptionedDisplayFormula" "Equation"
1435 ("OrgCaptionedFormula" nil "paragraph")
1436 ("OrgFormulaCaptionFrame" nil "as-char"))))
1438 (defun org-odt-format-entity (entity href width height &optional caption label)
1439 (let* ((entity-style (assoc entity org-odt-entity-frame-styles))
1440 (entity-frame (apply 'org-odt-format-frame
1441 href width height (nth 2 entity-style))))
1442 (if (not (or caption label)) entity-frame
1443 (apply 'org-odt-format-textbox
1444 (org-odt-format-stylized-paragraph
1445 'illustration
1446 (concat entity-frame (org-odt-format-entity-caption
1447 label caption (nth 1 entity-style))))
1448 width height (nth 3 entity-style)))))
1452 (defvar org-odt-embedded-images-count 0)
1453 (defun org-odt-copy-image-file (path)
1454 "Returns the internal name of the file"
1455 (let* ((image-type (file-name-extension path))
1456 (media-type (format "image/%s" image-type))
1457 (src-file (expand-file-name
1458 path (file-name-directory org-current-export-file)))
1459 (target-dir "Images/")
1460 (target-file
1461 (format "%s%04d.%s" target-dir
1462 (incf org-odt-embedded-images-count) image-type)))
1463 (when (not org-lparse-to-buffer)
1464 (message "Embedding %s as %s ..."
1465 (substring-no-properties path) target-file)
1467 (when (= 1 org-odt-embedded-images-count)
1468 (make-directory target-dir)
1469 (org-odt-create-manifest-file-entry "" target-dir))
1471 (copy-file src-file target-file 'overwrite)
1472 (org-odt-create-manifest-file-entry media-type target-file))
1473 target-file))
1475 (defvar org-export-odt-image-size-probe-method
1476 '(emacs imagemagick force)
1477 "Ordered list of methods by for determining size of an embedded
1478 image.")
1480 (defvar org-export-odt-default-image-sizes-alist
1481 '(("character" . (5 . 0.4))
1482 ("paragraph" . (5 . 5)))
1483 "Hardcoded image dimensions one for each of the anchor
1484 methods.")
1486 (defun org-odt-do-image-size (probe-method file &optional dpi anchor-type)
1487 (setq dpi (or dpi org-export-odt-pixels-per-inch))
1488 (setq anchor-type (or anchor-type "paragraph"))
1489 (flet ((size-in-cms (size-in-pixels)
1490 (flet ((pixels-to-cms (pixels)
1491 (let* ((cms-per-inch 2.54)
1492 (inches (/ pixels dpi)))
1493 (* cms-per-inch inches))))
1494 (and size-in-pixels
1495 (cons (pixels-to-cms (car size-in-pixels))
1496 (pixels-to-cms (cdr size-in-pixels)))))))
1497 (case probe-method
1498 (emacs
1499 (size-in-cms (ignore-errors (image-size (create-image file) 'pixels))))
1500 (imagemagick
1501 (size-in-cms
1502 (let ((dim (shell-command-to-string
1503 (format "identify -format \"%%w:%%h\" \"%s\"" file))))
1504 (when (string-match "\\([0-9]+\\):\\([0-9]+\\)" dim)
1505 (cons (string-to-number (match-string 1 dim))
1506 (string-to-number (match-string 2 dim)))))))
1508 (cdr (assoc-string anchor-type
1509 org-export-odt-default-image-sizes-alist))))))
1511 (defun org-odt-image-size-from-file (file &optional user-width
1512 user-height scale dpi embed-as)
1513 (unless (file-name-absolute-p file)
1514 (setq file (expand-file-name
1515 file (file-name-directory org-current-export-file))))
1516 (let* (size width height)
1517 (unless (and user-height user-width)
1518 (loop for probe-method in org-export-odt-image-size-probe-method
1519 until size
1520 do (setq size (org-odt-do-image-size
1521 probe-method file dpi embed-as)))
1522 (or size (error "Cannot determine Image size. Aborting ..."))
1523 (setq width (car size) height (cdr size)))
1524 (cond
1525 (scale
1526 (setq width (* width scale) height (* height scale)))
1527 ((and user-height user-width)
1528 (setq width user-width height user-height))
1529 (user-height
1530 (setq width (* user-height (/ width height)) height user-height))
1531 (user-width
1532 (setq height (* user-width (/ height width)) width user-width))
1533 (t (ignore)))
1534 (cons width height)))
1536 (defvar org-odt-entity-labels-alist nil
1537 "Associate Labels with the Labelled entities.
1538 Each element of the alist is of the form (LABEL-NAME
1539 CATEGORY-NAME SEQNO). LABEL-NAME is same as that specified by
1540 \"#+LABEL: ...\" line. CATEGORY-NAME is the type of the entity
1541 that LABEL-NAME is attached to. CATEGORY-NAME can be one of
1542 \"Table\", \"Figure\" or \"Equation\". SEQNO is the unique
1543 number assigned to the referenced entity on a per-CATEGORY basis.
1544 It is generated sequentially and is 1-based.
1546 Update this alist with `org-odt-add-label-definition' and
1547 retrieve an entry with `org-odt-get-label-definition'.")
1549 (defvar org-odt-entity-counts-plist nil
1550 "Plist of running counters of SEQNOs for each of the CATEGORY-NAMEs.
1551 See `org-odt-entity-labels-alist' for known CATEGORY-NAMEs.")
1553 (defvar org-odt-label-def-ref-spec
1554 '(("Equation" "(%n)" "text" "(%n)")
1555 ("" "%e %n%c" "category-and-value" "%e %n"))
1556 "Specify how labels are applied and referenced.
1557 This is an alist where each element is of the form (CATEGORY-NAME
1558 LABEL-APPLY-FMT LABEL-REF-MODE LABEL-REF-FMT). CATEGORY-NAME is
1559 as defined in `org-odt-entity-labels-alist'. It can additionally
1560 be an empty string in which case it is used as a catch-all
1561 specifier.
1563 LABEL-APPLY-FMT is used for applying labels and captions. It may
1564 contain following specifiers - %e, %n and %c. %e is replaced
1565 with the CATEGORY-NAME. %n is replaced with \"<text:sequence
1566 ...> SEQNO </text:sequence>\". %c is replaced with CAPTION. See
1567 `org-odt-format-label-definition'.
1569 LABEL-REF-MODE and LABEL-REF-FMT are used for generating the
1570 following label reference - \"<text:sequence-ref
1571 text:reference-format=\"LABEL-REF-MODE\" ...> LABEL-REF-FMT
1572 </text:sequence-ref>\". LABEL-REF-FMT may contain following
1573 specifiers - %e and %n. %e is replaced with the CATEGORY-NAME. %n is
1574 replaced with SEQNO. See `org-odt-format-label-reference'.")
1576 (defun org-odt-add-label-definition (label category)
1577 "Return (SEQNO . LABEL-APPLY-FMT).
1578 See `org-odt-label-def-ref-spec'."
1579 (setq label (substring-no-properties label))
1580 (let (seqno label-props fmt (category-sym (intern category)))
1581 (setq seqno (1+ (plist-get org-odt-entity-counts-plist category-sym))
1582 org-odt-entity-counts-plist (plist-put org-odt-entity-counts-plist
1583 category-sym seqno)
1584 fmt (cadr (or (assoc-string category org-odt-label-def-ref-spec t)
1585 (assoc-string "" org-odt-label-def-ref-spec t)))
1586 label-props (list label category seqno))
1587 (push label-props org-odt-entity-labels-alist)
1588 (cons seqno fmt)))
1590 (defun org-odt-get-label-definition (label)
1591 "Return (LABEL-NAME CATEGORY-NAME SEQNO LABEL-REF-MODE LABEL-REF-FMT).
1592 See `org-odt-entity-labels-alist' and
1593 `org-odt-label-def-ref-spec'."
1594 (let* ((label-props (assoc label org-odt-entity-labels-alist))
1595 (category (nth 1 label-props)))
1596 (append label-props
1597 (cddr (or (assoc-string category org-odt-label-def-ref-spec t)
1598 (assoc-string "" org-odt-label-def-ref-spec t))))))
1600 (defun org-odt-format-label-definition (label category caption)
1601 (assert label)
1602 (let* ((label-props (org-odt-add-label-definition label category))
1603 (seqno (car label-props))
1604 (fmt (cdr label-props)))
1605 (or (format-spec
1607 `((?e . ,category)
1608 (?n . ,(org-odt-format-tags
1609 '("<text:sequence text:ref-name=\"%s\" text:name=\"%s\" text:formula=\"ooow:%s+1\" style:num-format=\"1\">" . "</text:sequence>")
1610 (format "%d" seqno) label category category))
1611 (?c . ,(or (and caption (concat ": " caption)) ""))))
1612 caption "")))
1614 (defun org-odt-format-label-reference (label category seqno fmt1 fmt2)
1615 (assert label)
1616 (save-match-data
1617 (org-odt-format-tags
1618 '("<text:sequence-ref text:reference-format=\"%s\" text:ref-name=\"%s\">"
1619 . "</text:sequence-ref>")
1620 (format-spec fmt2 `((?e . ,category)
1621 (?n . ,(format "%d" seqno)))) fmt1 label)))
1623 (defun org-odt-fixup-label-references ()
1624 (goto-char (point-min))
1625 (while (re-search-forward
1626 "<text:sequence-ref text:ref-name=\"\\([^\"]+\\)\"/>" nil t)
1627 (let* ((label (match-string 1)))
1628 (replace-match
1629 (apply 'org-odt-format-label-reference
1630 (org-odt-get-label-definition label)) t t))))
1632 (defun org-odt-format-entity-caption (label caption category)
1633 (or (and label (org-odt-format-label-definition label category caption))
1634 caption ""))
1636 (defun org-odt-format-tags (tag text &rest args)
1637 (let ((prefix (when org-lparse-encode-pending "@"))
1638 (suffix (when org-lparse-encode-pending "@")))
1639 (apply 'org-lparse-format-tags tag text prefix suffix args)))
1641 (defun org-odt-init-outfile (filename)
1642 (unless (executable-find "zip")
1643 ;; Not at all OSes ship with zip by default
1644 (error "Executable \"zip\" needed for creating OpenDocument files"))
1646 (let* ((outdir (make-temp-file org-export-odt-tmpdir-prefix t))
1647 (content-file (expand-file-name "content.xml" outdir)))
1649 ;; init conten.xml
1650 (with-current-buffer (find-file-noselect content-file t))
1652 ;; reset variables
1653 (setq org-odt-manifest-file-entries nil
1654 org-odt-embedded-images-count 0
1655 org-odt-embedded-formulas-count 0
1656 org-odt-entity-labels-alist nil
1657 org-odt-entity-counts-plist (list 'Table 0 'Equation 0 'Figure 0))
1658 content-file))
1660 (defcustom org-export-odt-prettify-xml nil
1661 "Specify whether or not the xml output should be prettified.
1662 When this option is turned on, `indent-region' is run on all
1663 component xml buffers before they are saved. Turn this off for
1664 regular use. Turn this on if you need to examine the xml
1665 visually."
1666 :group 'org-export-odt
1667 :type 'boolean)
1669 (defvar hfy-user-sheet-assoc) ; bound during org-do-lparse
1670 (defun org-odt-save-as-outfile (target opt-plist)
1671 ;; create mimetype file
1672 (write-region "application/vnd.oasis.opendocument.text" nil
1673 (expand-file-name "mimetype"))
1675 ;; write meta file
1676 (org-odt-update-meta-file opt-plist)
1678 ;; write styles file
1679 (org-odt-copy-styles-file)
1681 ;; Update styles.xml - take care of outline numbering
1682 (with-current-buffer
1683 (find-file-noselect (expand-file-name "styles.xml") t)
1684 ;; Don't make automatic backup of styles.xml file. This setting
1685 ;; prevents the backedup styles.xml file from being zipped in to
1686 ;; odt file. This is more of a hackish fix. Better alternative
1687 ;; would be to fix the zip command so that the output odt file
1688 ;; includes only the needed files and excludes any auto-generated
1689 ;; extra files like backups and auto-saves etc etc. Note that
1690 ;; currently the zip command zips up the entire temp directory so
1691 ;; that any auto-generated files created under the hood ends up in
1692 ;; the resulting odt file.
1693 (set (make-local-variable 'backup-inhibited) t)
1695 ;; Import local setting of `org-export-with-section-numbers'
1696 (org-lparse-bind-local-variables opt-plist)
1697 (org-odt-configure-outline-numbering
1698 (if org-export-with-section-numbers org-export-headline-levels 0)))
1700 ;; Write custom stlyes for source blocks
1701 (org-odt-insert-custom-styles-for-srcblocks
1702 (mapconcat
1703 (lambda (style)
1704 (format " %s\n" (cddr style)))
1705 hfy-user-sheet-assoc ""))
1707 ;; create a manifest entry for content.xml
1708 (org-odt-create-manifest-file-entry
1709 "application/vnd.oasis.opendocument.text" "/" "1.2")
1711 (org-odt-create-manifest-file-entry "text/xml" "content.xml")
1713 ;; write out the manifest entries before zipping
1714 (org-odt-write-manifest-file)
1716 (let ((xml-files '("mimetype" "META-INF/manifest.xml" "content.xml"
1717 "meta.xml" "styles.xml"))
1718 (zipdir default-directory))
1719 (message "Switching to directory %s" (expand-file-name zipdir))
1721 ;; save all xml files
1722 (mapc (lambda (file)
1723 (with-current-buffer
1724 (find-file-noselect (expand-file-name file) t)
1725 ;; prettify output if needed
1726 (when org-export-odt-prettify-xml
1727 (indent-region (point-min) (point-max)))
1728 (save-buffer 0)))
1729 xml-files)
1731 (let* ((target-name (file-name-nondirectory target))
1732 (target-dir (file-name-directory target))
1733 (cmds `(("zip" "-mX0" ,target-name "mimetype")
1734 ("zip" "-rmTq" ,target-name "."))))
1735 (when (file-exists-p target)
1736 ;; FIXME: If the file is locked this throws a cryptic error
1737 (delete-file target))
1739 (let ((coding-system-for-write 'no-conversion) exitcode err-string)
1740 (message "Creating odt file...")
1741 (mapc
1742 (lambda (cmd)
1743 (message "Running %s" (mapconcat 'identity cmd " "))
1744 (setq err-string
1745 (with-output-to-string
1746 (setq exitcode
1747 (apply 'call-process (car cmd)
1748 nil standard-output nil (cdr cmd)))))
1749 (or (zerop exitcode)
1750 (ignore (message "%s" err-string))
1751 (error "Unable to create odt file (%S)" exitcode)))
1752 cmds))
1754 ;; move the file from outdir to target-dir
1755 (rename-file target-name target-dir)
1757 ;; kill all xml buffers
1758 (mapc (lambda (file)
1759 (kill-buffer
1760 (find-file-noselect (expand-file-name file zipdir) t)))
1761 xml-files)
1763 (delete-directory zipdir)))
1765 (message "Created %s" target)
1766 (set-buffer (find-file-noselect target t)))
1768 (defun org-odt-format-date (date)
1769 (let ((warning-msg
1770 "OpenDocument files require that dates be in ISO-8601 format. Please review your DATE options for compatibility."))
1771 ;; If the user is not careful with the date specification, an
1772 ;; invalid meta.xml will be emitted.
1774 ;; For now honor user's diktat and let him off with a warning
1775 ;; message. This is OK as LibreOffice (and possibly other
1776 ;; apps) doesn't deem this deviation as critical and continue
1777 ;; to load the file.
1779 ;; FIXME: Surely there a better way to handle this. Revisit this
1780 ;; later.
1781 (cond
1782 ((and date (string-match "%" date))
1783 ;; Honor user's diktat. See comments above
1784 (org-lparse-warn warning-msg)
1785 (format-time-string date))
1786 (date
1787 ;; Honor user's diktat. See comments above
1788 (org-lparse-warn warning-msg)
1789 date)
1791 ;; ISO 8601 format
1792 (let ((stamp (format-time-string "%Y-%m-%dT%H:%M:%S%z")))
1793 (format "%s:%s" (substring stamp 0 -2) (substring stamp -2)))))))
1795 (defconst org-odt-manifest-file-entry-tag
1797 <manifest:file-entry manifest:media-type=\"%s\" manifest:full-path=\"%s\"%s/>")
1799 (defvar org-odt-manifest-file-entries nil)
1801 (defun org-odt-create-manifest-file-entry (&rest args)
1802 (push args org-odt-manifest-file-entries))
1804 (defun org-odt-write-manifest-file ()
1805 (make-directory "META-INF")
1806 (let ((manifest-file (expand-file-name "META-INF/manifest.xml")))
1807 (write-region
1808 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
1809 <manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"1.2\">\n"
1810 nil manifest-file)
1811 (mapc
1812 (lambda (file-entry)
1813 (let* ((version (nth 2 file-entry))
1814 (extra (if version
1815 (format " manifest:version=\"%s\"" version)
1816 "")))
1817 (write-region
1818 (format org-odt-manifest-file-entry-tag
1819 (nth 0 file-entry) (nth 1 file-entry) extra)
1820 nil manifest-file t))) org-odt-manifest-file-entries)
1821 (write-region "\n</manifest:manifest>" nil manifest-file t)))
1823 (defun org-odt-update-meta-file (opt-plist)
1824 (let ((date (org-odt-format-date (plist-get opt-plist :date)))
1825 (author (or (plist-get opt-plist :author) ""))
1826 (email (plist-get opt-plist :email))
1827 (keywords (plist-get opt-plist :keywords))
1828 (description (plist-get opt-plist :description))
1829 (title (plist-get opt-plist :title)))
1831 (write-region
1832 (concat
1833 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
1834 <office:document-meta
1835 xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"
1836 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
1837 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
1838 xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"
1839 xmlns:ooo=\"http://openoffice.org/2004/office\"
1840 office:version=\"1.2\">
1841 <office:meta>" "\n"
1842 (org-odt-format-tags '("<dc:creator>" . "</dc:creator>") author)
1843 (org-odt-format-tags
1844 '("\n<meta:initial-creator>" . "</meta:initial-creator>") author)
1845 (org-odt-format-tags '("\n<dc:date>" . "</dc:date>") date)
1846 (org-odt-format-tags
1847 '("\n<meta:creation-date>" . "</meta:creation-date>") date)
1848 (org-odt-format-tags '("\n<meta:generator>" . "</meta:generator>")
1849 (when org-export-creator-info
1850 (format "Org-%s/Emacs-%s"
1851 org-version emacs-version)))
1852 (org-odt-format-tags '("\n<meta:keyword>" . "</meta:keyword>") keywords)
1853 (org-odt-format-tags '("\n<dc:subject>" . "</dc:subject>") description)
1854 (org-odt-format-tags '("\n<dc:title>" . "</dc:title>") title)
1855 "\n"
1856 " </office:meta>" "</office:document-meta>")
1857 nil (expand-file-name "meta.xml")))
1859 ;; create a manifest entry for meta.xml
1860 (org-odt-create-manifest-file-entry "text/xml" "meta.xml"))
1862 (defun org-odt-finalize-outfile ()
1863 (org-odt-delete-empty-paragraphs))
1865 (defun org-odt-delete-empty-paragraphs ()
1866 (goto-char (point-min))
1867 (let ((open "<text:p[^>]*>")
1868 (close "</text:p>"))
1869 (while (re-search-forward (format "%s[ \r\n\t]*%s" open close) nil t)
1870 (replace-match ""))))
1872 (defun org-odt-get (what &optional opt-plist)
1873 (case what
1874 (BACKEND 'odt)
1875 (EXPORT-DIR (org-export-directory :html opt-plist))
1876 (FILE-NAME-EXTENSION "odt")
1877 (EXPORT-BUFFER-NAME "*Org ODT Export*")
1878 (ENTITY-CONTROL org-odt-entity-control-callbacks-alist)
1879 (ENTITY-FORMAT org-odt-entity-format-callbacks-alist)
1880 (INIT-METHOD 'org-odt-init-outfile)
1881 (FINAL-METHOD 'org-odt-finalize-outfile)
1882 (SAVE-METHOD 'org-odt-save-as-outfile)
1883 ;; (OTHER-BACKENDS) ; see note in `org-xhtml-get'
1884 ;; (CONVERT-METHOD) ; see note in `org-xhtml-get'
1885 (TOPLEVEL-HLEVEL 1)
1886 (SPECIAL-STRING-REGEXPS org-export-odt-special-string-regexps)
1887 (INLINE-IMAGES 'maybe)
1888 (INLINE-IMAGE-EXTENSIONS '("png" "jpeg" "jpg" "gif" "svg"))
1889 (PLAIN-TEXT-MAP '(("&" . "&amp;") ("<" . "&lt;") (">" . "&gt;")))
1890 (TABLE-FIRST-COLUMN-AS-LABELS nil)
1891 (FOOTNOTE-SEPARATOR (org-lparse-format 'FONTIFY "," 'superscript))
1892 (CODING-SYSTEM-FOR-WRITE 'utf-8)
1893 (CODING-SYSTEM-FOR-SAVE 'utf-8)
1894 (t (error "Unknown property: %s" what))))
1896 (defvar org-lparse-latex-fragment-fallback) ; set by org-do-lparse
1897 (defvar org-lparse-opt-plist) ; bound during org-do-lparse
1898 (defun org-export-odt-do-preprocess-latex-fragments ()
1899 "Convert LaTeX fragments to images."
1900 (let* ((latex-frag-opt (plist-get org-lparse-opt-plist :LaTeX-fragments))
1901 (latex-frag-opt ; massage the options
1902 (or (and (member latex-frag-opt '(mathjax t))
1903 (not (and (fboundp 'org-format-latex-mathml-available-p)
1904 (org-format-latex-mathml-available-p)))
1905 (prog1 org-lparse-latex-fragment-fallback
1906 (org-lparse-warn
1907 (concat
1908 "LaTeX to MathML converter not available. "
1909 (format "Using %S instead."
1910 org-lparse-latex-fragment-fallback)))))
1911 latex-frag-opt))
1912 cache-dir display-msg)
1913 (cond
1914 ((eq latex-frag-opt 'dvipng)
1915 (setq cache-dir "ltxpng/")
1916 (setq display-msg "Creating LaTeX image %s"))
1917 ((member latex-frag-opt '(mathjax t))
1918 (setq latex-frag-opt 'mathml)
1919 (setq cache-dir "ltxmathml/")
1920 (setq display-msg "Creating MathML formula %s")))
1921 (when (and org-current-export-file)
1922 (org-format-latex
1923 (concat cache-dir (file-name-sans-extension
1924 (file-name-nondirectory org-current-export-file)))
1925 org-current-export-dir nil display-msg
1926 nil nil latex-frag-opt))))
1928 (defun org-export-odt-preprocess-latex-fragments ()
1929 (when (equal org-export-current-backend 'odt)
1930 (org-export-odt-do-preprocess-latex-fragments)))
1932 (defun org-export-odt-preprocess-label-references ()
1933 (goto-char (point-min))
1934 (let (label label-components category value pretty-label)
1935 (while (re-search-forward "\\\\ref{\\([^{}\n]+\\)}" nil t)
1936 (org-if-unprotected-at (match-beginning 1)
1937 (replace-match
1938 (let ((org-lparse-encode-pending t)
1939 (label (match-string 1)))
1940 ;; markup generated below is mostly an eye-candy. At
1941 ;; pre-processing stage, there is no information on which
1942 ;; entity a label reference points to. The actual markup
1943 ;; is generated as part of `org-odt-fixup-label-references'
1944 ;; which gets called at the fag end of export. By this
1945 ;; time we would have seen and collected all the label
1946 ;; definitions in `org-odt-entity-labels-alist'.
1947 (org-odt-format-tags
1948 "<text:sequence-ref text:ref-name=\"%s\"/>" "" label)) t t)))))
1950 ;; process latex fragments as part of
1951 ;; `org-export-preprocess-after-blockquote-hook'. Note that this hook
1952 ;; is the one that is closest and well before the call to
1953 ;; `org-export-attach-captions-and-attributes' in
1954 ;; `org-export-preprocess-stirng'. The above arrangement permits
1955 ;; captions, labels and attributes to be attached to png images
1956 ;; generated out of latex equations.
1957 (add-hook 'org-export-preprocess-after-blockquote-hook
1958 'org-export-odt-preprocess-latex-fragments)
1960 (defun org-export-odt-preprocess (parameters)
1961 (org-export-odt-preprocess-label-references))
1963 (declare-function archive-zip-extract "arc-mode.el" (archive name))
1964 (defun org-odt-zip-extract-one (archive member &optional target)
1965 (require 'arc-mode)
1966 (let* ((target (or target default-directory))
1967 (archive (expand-file-name archive))
1968 (archive-zip-extract
1969 (list "unzip" "-qq" "-o" "-d" target))
1970 exit-code command-output)
1971 (setq command-output
1972 (with-temp-buffer
1973 (setq exit-code (archive-zip-extract archive member))
1974 (buffer-string)))
1975 (unless (zerop exit-code)
1976 (message command-output)
1977 (error "Extraction failed"))))
1979 (defun org-odt-zip-extract (archive members &optional target)
1980 (when (atom members) (setq members (list members)))
1981 (mapc (lambda (member)
1982 (org-odt-zip-extract-one archive member target))
1983 members))
1985 (defun org-odt-copy-styles-file (&optional styles-file)
1986 ;; Non-availability of styles.xml is not a critical error. For now
1987 ;; throw an error purely for aesthetic reasons.
1988 (setq styles-file (or styles-file
1989 org-export-odt-styles-file
1990 (expand-file-name "styles/OrgOdtStyles.xml"
1991 org-odt-data-dir)
1992 (error "org-odt: Missing styles file?")))
1993 (cond
1994 ((listp styles-file)
1995 (let ((archive (nth 0 styles-file))
1996 (members (nth 1 styles-file)))
1997 (org-odt-zip-extract archive members)
1998 (mapc
1999 (lambda (member)
2000 (when (org-file-image-p member)
2001 (let* ((image-type (file-name-extension member))
2002 (media-type (format "image/%s" image-type)))
2003 (org-odt-create-manifest-file-entry media-type member))))
2004 members)))
2005 ((and (stringp styles-file) (file-exists-p styles-file))
2006 (let ((styles-file-type (file-name-extension styles-file)))
2007 (cond
2008 ((string= styles-file-type "xml")
2009 (copy-file styles-file "styles.xml" t))
2010 ((member styles-file-type '("odt" "ott"))
2011 (org-odt-zip-extract styles-file "styles.xml")))))
2013 (error (format "Invalid specification of styles.xml file: %S"
2014 org-export-odt-styles-file))))
2016 ;; create a manifest entry for styles.xml
2017 (org-odt-create-manifest-file-entry "text/xml" "styles.xml"))
2019 (defvar org-export-odt-factory-settings
2020 "d4328fb9d1b6cb211d4320ff546829f26700dc5e"
2021 "SHA1 hash of OrgOdtStyles.xml.")
2023 (defun org-odt-configure-outline-numbering (level)
2024 "Outline numbering is retained only upto LEVEL.
2025 To disable outline numbering pass a LEVEL of 0."
2026 (goto-char (point-min))
2027 (let ((regex
2028 "<text:outline-level-style\\(.*\\)text:level=\"\\([^\"]*\\)\"\\(.*\\)>")
2029 (replacement
2030 "<text:outline-level-style\\1text:level=\"\\2\" style:num-format=\"\">"))
2031 (while (re-search-forward regex nil t)
2032 (when (> (string-to-number (match-string 2)) level)
2033 (replace-match replacement t nil))))
2034 (save-buffer 0))
2036 (provide 'org-odt)
2038 ;;; org-odt.el ends here