Republish org-odt-20111011.tar
[org-mode/org-jambu.git] / lisp / org-odt.el
blob1a496322aeaee712c8ccc152ea2452f2abda0b5b
1 ;;; org-odt.el --- OpenDocumentText export for Org-mode
3 ;; Copyright (C) 2010-2011
4 ;; Jambunathan <kjambunathan at gmail dot com>
6 ;; Author: Jambunathan K <kjambunathan at gmail dot com>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 0.8
11 ;; This file is not (yet) part of GNU Emacs.
12 ;; However, it is distributed under the same license.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;;; Code:
31 (eval-when-compile (require 'cl))
32 (require 'org-lparse)
34 (defun org-odt-end-export ()
35 ;; remove empty paragraphs
36 (goto-char (point-min))
37 (while (re-search-forward
38 "<text:p\\( text:style-name=\"Text_20_body\"\\)?>[ \r\n\t]*</text:p>"
39 nil t)
40 (replace-match ""))
41 (goto-char (point-min))
43 ;; Convert whitespace place holders
44 (goto-char (point-min))
45 (let (beg end n)
46 (while (setq beg (next-single-property-change (point) 'org-whitespace))
47 (setq n (get-text-property beg 'org-whitespace)
48 end (next-single-property-change beg 'org-whitespace))
49 (goto-char beg)
50 (delete-region beg end)
51 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
52 (make-string n ?x)))))
54 ;; Remove empty lines at the beginning of the file.
55 (goto-char (point-min))
56 (when (looking-at "\\s-+\n") (replace-match ""))
58 ;; Remove display properties
59 (remove-text-properties (point-min) (point-max) '(display t)))
61 (defvar org-odt-suppress-xref nil)
62 (defconst org-export-odt-special-string-regexps
63 '(("\\\\-" . "&#x00ad;\\1") ; shy
64 ("---\\([^-]\\)" . "&#x2014;\\1") ; mdash
65 ("--\\([^-]\\)" . "&#x2013;\\1") ; ndash
66 ("\\.\\.\\." . "&#x2026;")) ; hellip
67 "Regular expressions for special string conversion.")
69 (defconst org-odt-lib-dir (file-name-directory load-file-name))
70 (defconst org-odt-data-dir
71 (let ((dir1 (expand-file-name "../contrib/odt" org-odt-lib-dir)) ; git
72 (dir2 (expand-file-name "./contrib/odt" org-odt-lib-dir))) ; elpa
73 (cond
74 ((file-directory-p dir1) dir1)
75 ((file-directory-p dir2) dir2)
76 (t (error "Cannot find factory styles file. Check package dir layout")))))
78 (defvar org-odt-file-extensions
79 '(("odt" . "OpenDocument Text")
80 ("ott" . "OpenDocument Text Template")
81 ("odm" . "OpenDocument Master Document")
82 ("ods" . "OpenDocument Spreadsheet")
83 ("ots" . "OpenDocument Spreadsheet Template")
84 ("odg" . "OpenDocument Drawing (Graphics)")
85 ("otg" . "OpenDocument Drawing Template")
86 ("odp" . "OpenDocument Presentation")
87 ("otp" . "OpenDocument Presentation Template")
88 ("odi" . "OpenDocument Image")
89 ("odf" . "OpenDocument Formula")
90 ("odc" . "OpenDocument Chart")
91 ("doc" . "Microsoft Text")
92 ("docx" . "Microsoft Text")
93 ("xls" . "Microsoft Spreadsheet")
94 ("xlsx" . "Microsoft Spreadsheet")
95 ("ppt" . "Microsoft Presentation")
96 ("pptx" . "Microsoft Presentation")))
98 (defvar org-odt-ms-file-extensions
99 '(("doc" . "Microsoft Text")
100 ("docx" . "Microsoft Text")
101 ("xls" . "Microsoft Spreadsheet")
102 ("xlsx" . "Microsoft Spreadsheet")
103 ("ppt" . "Microsoft Presentation")
104 ("pptx" . "Microsoft Presentation")))
106 ;; RelaxNG validation of OpenDocument xml files
107 (eval-after-load 'rng-nxml
108 '(setq rng-nxml-auto-validate-flag t))
110 (eval-after-load 'rng-loc
111 '(add-to-list 'rng-schema-locating-files
112 (expand-file-name "schemas.xml" org-odt-data-dir)))
114 (mapc
115 (lambda (desc)
116 ;; Let Org open all OpenDocument files using system-registered app
117 (add-to-list 'org-file-apps
118 (cons (concat "\\." (car desc) "\\'") 'system))
119 ;; Let Emacs open all OpenDocument files in archive mode
120 (add-to-list 'auto-mode-alist
121 (cons (concat "\\." (car desc) "\\'") 'archive-mode)))
122 org-odt-file-extensions)
124 (mapc
125 (lambda (desc)
126 ;; Let Org open all Microsoft files using system-registered app
127 (add-to-list 'org-file-apps
128 (cons (concat "\\." (car desc) "\\'") 'system)))
129 org-odt-ms-file-extensions)
131 ;; register the odt exporter
132 (add-to-list 'org-export-backends 'odt)
134 (defcustom org-export-odt-automatic-styles-file nil
135 "Default style file for use with ODT exporter."
136 :group 'org-export-odt
137 :type 'file)
139 ;; TODO: Make configuration user-friendly.
140 (defcustom org-export-odt-styles-file nil
141 "Default style file for use with ODT exporter.
142 Valid values are path to an styles.xml file or a path to a valid
143 *.odt or a *.ott file or a list of the form (FILE (MEMBER1
144 MEMBER2 ...)). In the last case, the specified FILE is unzipped
145 and MEMBER1, MEMBER2 etc are copied in to the generated odt
146 file. The last form is particularly useful if the styles.xml has
147 reference to additional files like header and footer images.
149 :group 'org-export-odt
150 :type 'file)
151 (defconst org-export-odt-tmpdir-prefix "odt-")
152 (defconst org-export-odt-bookmark-prefix "OrgXref.")
153 (defcustom org-export-odt-use-bookmarks-for-internal-links t
154 "Export Internal links as bookmarks?."
155 :group 'org-export-odt
156 :type 'boolean)
158 (defcustom org-export-odt-embed-images t
159 "Should the images be copied in to the odt file or just linked?"
160 :group 'org-export-odt
161 :type 'boolean)
163 (defcustom org-odt-export-inline-images 'maybe
164 "Non-nil means inline images into exported HTML pages.
165 This is done using an <img> tag. When nil, an anchor with href is used to
166 link to the image. If this option is `maybe', then images in links with
167 an empty description will be inlined, while images with a description will
168 be linked only."
169 :group 'org-odt-export
170 :type '(choice (const :tag "Never" nil)
171 (const :tag "Always" t)
172 (const :tag "When there is no description" maybe)))
174 (defcustom org-odt-export-inline-image-extensions
175 '("png" "jpeg" "jpg" "gif")
176 "Extensions of image files that can be inlined into HTML."
177 :group 'org-odt-export
178 :type '(repeat (string :tag "Extension")))
180 (defcustom org-export-odt-pixels-per-inch display-pixels-per-inch
182 :group 'org-export-odt
183 :type 'float)
185 (defvar org-export-odt-default-org-styles-alist
186 '((paragraph . ((default . "Text_20_body")
187 (fixedwidth . "OrgSourceBlock")
188 (verse . "OrgVerse")
189 (quote . "Quotations")
190 (blockquote . "Quotations")
191 (center . "OrgCenter")
192 (left . "OrgLeft")
193 (right . "OrgRight")
194 (title . "Heading_20_1.title")
195 (footnote . "Footnote")
196 (src . "OrgSourceBlock")
197 (illustration . "Illustration")
198 (table . "Table")
199 (definition-term . "Text_20_body_20_bold")
200 (horizontal-line . "Horizontal_20_Line")))
201 (character . ((bold . "Bold")
202 (emphasis . "Emphasis")
203 (code . "OrgCode")
204 (verbatim . "OrgCode")
205 (strike . "Strikethrough")
206 (underline . "Underline")
207 (subscript . "OrgSubscript")
208 (superscript . "OrgSuperscript")))
209 (list . ((ordered . "OrgNumberedList")
210 (unordered . "OrgBulletedList")
211 (description . "OrgDescriptionList"))))
212 "Default styles for various entities.")
214 (defvar org-export-odt-org-styles-alist org-export-odt-default-org-styles-alist)
215 (defun org-odt-get-style-name-for-entity (category &optional entity)
216 (let ((entity (or entity 'default)))
218 (cdr (assoc entity (cdr (assoc category
219 org-export-odt-org-styles-alist))))
220 (cdr (assoc entity (cdr (assoc category
221 org-export-odt-default-org-styles-alist))))
222 (error "Cannot determine style name for entity %s of type %s"
223 entity category))))
225 ;;;###autoload
226 (defun org-export-as-odt-and-open (arg)
227 "Export the outline as ODT and immediately open it with a browser.
228 If there is an active region, export only the region.
229 The prefix ARG specifies how many levels of the outline should become
230 headlines. The default is 3. Lower levels will become bulleted lists."
231 (interactive "P")
232 (org-lparse-and-open "odt" "odt" arg))
234 ;;;###autoload
235 (defun org-export-as-odt-batch ()
236 "Call the function `org-lparse-batch'.
237 This function can be used in batch processing as:
238 emacs --batch
239 --load=$HOME/lib/emacs/org.el
240 --eval \"(setq org-export-headline-levels 2)\"
241 --visit=MyFile --funcall org-export-as-odt-batch"
242 (org-lparse-batch "odt"))
244 ;;;###autoload
245 (defun org-export-as-odt-to-buffer (arg)
246 "Call `org-lparse-odt` with output to a temporary buffer.
247 No file is created. The prefix ARG is passed through to `org-lparse-to-buffer'."
248 (interactive "P")
249 (org-lparse-to-buffer "odt" arg))
251 ;;;###autoload
252 (defun org-replace-region-by-odt (beg end)
253 "Assume the current region has org-mode syntax, and convert it to ODT.
254 This can be used in any buffer. For example, you could write an
255 itemized list in org-mode syntax in an ODT buffer and then use this
256 command to convert it."
257 (interactive "r")
258 (org-replace-region-by "odt" beg end))
260 ;;;###autoload
261 (defun org-export-region-as-odt (beg end &optional body-only buffer)
262 "Convert region from BEG to END in org-mode buffer to ODT.
263 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
264 contents, and only produce the region of converted text, useful for
265 cut-and-paste operations.
266 If BUFFER is a buffer or a string, use/create that buffer as a target
267 of the converted ODT. If BUFFER is the symbol `string', return the
268 produced ODT as a string and leave not buffer behind. For example,
269 a Lisp program could call this function in the following way:
271 (setq odt (org-export-region-as-odt beg end t 'string))
273 When called interactively, the output buffer is selected, and shown
274 in a window. A non-interactive call will only return the buffer."
275 (interactive "r\nP")
276 (org-lparse-region "odt" beg end body-only buffer))
278 ;;; org-export-as-odt
279 ;;;###autoload
280 (defun org-export-as-odt (arg &optional hidden ext-plist
281 to-buffer body-only pub-dir)
282 "Export the outline as a OpenDocumentText file.
283 If there is an active region, export only the region. The prefix
284 ARG specifies how many levels of the outline should become
285 headlines. The default is 3. Lower levels will become bulleted
286 lists. HIDDEN is obsolete and does nothing.
287 EXT-PLIST is a property list with external parameters overriding
288 org-mode's default settings, but still inferior to file-local
289 settings. When TO-BUFFER is non-nil, create a buffer with that
290 name and export to that buffer. If TO-BUFFER is the symbol
291 `string', don't leave any buffer behind but just return the
292 resulting XML as a string. When BODY-ONLY is set, don't produce
293 the file header and footer, simply return the content of
294 <body>...</body>, without even the body tags themselves. When
295 PUB-DIR is set, use this as the publishing directory."
296 (interactive "P")
297 (org-lparse "odt" "odt" arg hidden ext-plist to-buffer body-only pub-dir))
299 (defvar org-odt-entity-control-callbacks-alist
300 `((EXPORT
301 . (org-odt-begin-export org-odt-end-export))
302 (DOCUMENT-CONTENT
303 . (org-odt-begin-document-content org-odt-end-document-content))
304 (DOCUMENT-BODY
305 . (org-odt-begin-document-body org-odt-end-document-body))
306 (TOC
307 . (org-odt-begin-toc org-odt-end-toc))
308 (ENVIRONMENT
309 . (org-odt-begin-environment org-odt-end-environment))
310 (FOOTNOTE-DEFINITION
311 . (org-odt-begin-footnote-definition org-odt-end-footnote-definition))
312 (TABLE
313 . (org-odt-begin-table org-odt-end-table))
314 (TABLE-ROWGROUP
315 . (org-odt-begin-table-rowgroup org-odt-end-table-rowgroup))
316 (LIST
317 . (org-odt-begin-list org-odt-end-list))
318 (LIST-ITEM
319 . (org-odt-begin-list-item org-odt-end-list-item))
320 (OUTLINE
321 . (org-odt-begin-outline org-odt-end-outline))
322 (OUTLINE-TEXT
323 . (org-odt-begin-outline-text org-odt-end-outline-text))
324 (PARAGRAPH
325 . (org-odt-begin-paragraph org-odt-end-paragraph)))
328 (defvar org-odt-entity-format-callbacks-alist
329 `((EXTRA-TARGETS . org-lparse-format-extra-targets)
330 (ORG-TAGS . org-lparse-format-org-tags)
331 (SECTION-NUMBER . org-lparse-format-section-number)
332 (HEADLINE . org-odt-format-headline)
333 (TOC-ENTRY . org-odt-format-toc-entry)
334 (TOC-ITEM . org-odt-format-toc-item)
335 (TAGS . org-odt-format-tags)
336 (SPACES . org-odt-format-spaces)
337 (TABS . org-odt-format-tabs)
338 (LINE-BREAK . org-odt-format-line-break)
339 (FONTIFY . org-odt-format-fontify)
340 (TODO . org-lparse-format-todo)
341 (LINK . org-odt-format-link)
342 (INLINE-IMAGE . org-odt-format-inline-image)
343 (ORG-LINK . org-odt-format-org-link)
344 (HEADING . org-odt-format-heading)
345 (ANCHOR . org-odt-format-anchor)
346 (TABLE . org-lparse-format-table)
347 (TABLE-ROW . org-odt-format-table-row)
348 (TABLE-CELL . org-odt-format-table-cell)
349 (FOOTNOTES-SECTION . ignore)
350 (FOOTNOTE-REFERENCE . org-odt-format-footnote-reference)
351 (HORIZONTAL-LINE . org-odt-format-horizontal-line)
352 (COMMENT . org-odt-format-comment)
353 (LINE . org-odt-format-line)
354 (ORG-ENTITY . org-odt-format-org-entity))
357 ;;;_. callbacks
358 ;;;_. control callbacks
359 ;;;_ , document body
360 (defun org-odt-begin-office-body ()
361 (insert "
362 <office:body>
363 <office:text>
364 <text:sequence-decls>
365 <text:sequence-decl text:display-outline-level=\"0\" text:name=\"Illustration\"/>
366 <text:sequence-decl text:display-outline-level=\"0\" text:name=\"Table\"/>
367 <text:sequence-decl text:display-outline-level=\"0\" text:name=\"Text\"/>
368 <text:sequence-decl text:display-outline-level=\"0\" text:name=\"Drawing\"/>
369 </text:sequence-decls>"))
371 ;; Following variable is let bound when `org-do-lparse' is in
372 ;; progress. See org-html.el.
373 (defvar org-lparse-toc)
374 (defun org-odt-begin-document-body (opt-plist)
375 (org-odt-begin-office-body)
376 (let ((title (plist-get opt-plist :title)))
377 (when title
378 (insert
379 (org-odt-format-stylized-paragraph 'title title))))
381 ;; insert toc
382 (when org-lparse-toc
383 (insert "\n" org-lparse-toc "\n")))
385 (defvar org-lparse-body-only) ; let bound during org-do-lparse
386 (defvar org-lparse-to-buffer) ; let bound during org-do-lparse
387 (defun org-odt-end-document-body (opt-plist)
388 (unless org-lparse-body-only
389 (org-lparse-insert-tag "</office:text>")
390 (org-lparse-insert-tag "</office:body>")))
392 (defconst org-odt-document-content-header
393 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
394 <office:document-content
395 xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"
396 xmlns:style=\"urn:oasis:names:tc:opendocument:xmlns:style:1.0\"
397 xmlns:text=\"urn:oasis:names:tc:opendocument:xmlns:text:1.0\"
398 xmlns:table=\"urn:oasis:names:tc:opendocument:xmlns:table:1.0\"
399 xmlns:draw=\"urn:oasis:names:tc:opendocument:xmlns:drawing:1.0\"
400 xmlns:fo=\"urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0\"
401 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
402 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
403 xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"
404 xmlns:number=\"urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0\"
405 xmlns:svg=\"urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0\"
406 xmlns:chart=\"urn:oasis:names:tc:opendocument:xmlns:chart:1.0\"
407 xmlns:dr3d=\"urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0\"
408 xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
409 xmlns:form=\"urn:oasis:names:tc:opendocument:xmlns:form:1.0\"
410 xmlns:script=\"urn:oasis:names:tc:opendocument:xmlns:script:1.0\"
411 xmlns:ooo=\"http://openoffice.org/2004/office\"
412 xmlns:ooow=\"http://openoffice.org/2004/writer\"
413 xmlns:oooc=\"http://openoffice.org/2004/calc\"
414 xmlns:dom=\"http://www.w3.org/2001/xml-events\"
415 xmlns:xforms=\"http://www.w3.org/2002/xforms\"
416 xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"
417 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
418 xmlns:rpt=\"http://openoffice.org/2005/report\"
419 xmlns:of=\"urn:oasis:names:tc:opendocument:xmlns:of:1.2\"
420 xmlns:xodt=\"http://www.w3.org/1999/xodt\"
421 xmlns:field=\"urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0\" office:version=\"1.2\">
424 (defun org-odt-begin-document-content (opt-plist)
425 ;; document header
426 (insert org-odt-document-content-header)
428 ;; automatic styles
429 (insert-file-contents
430 (or org-export-odt-automatic-styles-file
431 (expand-file-name "OrgOdtAutomaticStyles.xml" org-odt-data-dir)))
432 (goto-char (point-max)))
434 (defun org-odt-end-document-content ()
435 (org-lparse-insert-tag "</office:document-content>"))
437 (defun org-odt-begin-outline (level1 snumber title tags
438 target extra-targets class)
439 (org-lparse-insert
440 'HEADING (org-lparse-format
441 'HEADLINE title extra-targets tags snumber level1)
442 level1 target))
444 (defun org-odt-end-outline ()
445 (ignore))
447 (defun org-odt-begin-outline-text (level1 snumber class)
448 (ignore))
450 (defun org-odt-end-outline-text ()
451 (ignore))
453 (defun org-odt-begin-paragraph (&optional style)
454 (org-lparse-insert-tag
455 "<text:p%s>" (org-odt-get-extra-attrs-for-paragraph-style style)))
457 (defun org-odt-end-paragraph ()
458 (org-lparse-insert-tag "</text:p>"))
460 (defun org-odt-get-extra-attrs-for-paragraph-style (style)
461 (let (style-name)
462 (setq style-name
463 (cond
464 ((stringp style) style)
465 ((symbolp style) (org-odt-get-style-name-for-entity
466 'paragraph style))))
467 (unless style-name
468 (error "Don't know how to handle paragraph style %s" style))
469 (format " text:style-name=\"%s\"" style-name)))
471 (defun org-odt-format-stylized-paragraph (style text)
472 (org-odt-format-tags
473 '("<text:p%s>" . "</text:p>") text
474 (org-odt-get-extra-attrs-for-paragraph-style style)))
476 (defun org-odt-begin-environment (style)
477 (case style
478 ((blockquote verse center quote)
479 (org-lparse-begin-paragraph style)
480 (list))
481 ((fixedwidth native)
482 (org-lparse-end-paragraph)
483 (list))
484 (t (error "Unknown environment %s" style))))
486 (defun org-odt-end-environment (style)
487 (case style
488 ((blockquote verse center quote)
489 (org-lparse-end-paragraph)
490 (list))
491 ((fixedwidth native)
492 (org-lparse-begin-paragraph)
493 (list))
494 (t (error "Unknown environment %s" style))))
496 (defun org-odt-begin-list (ltype &optional arg1)
497 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
498 ltype))
499 (let* ((style-name (org-odt-get-style-name-for-entity 'list ltype))
500 (extra (if style-name
501 (format " text:style-name=\"%s\"" style-name) "")))
503 ;; FIXME: Handle arg1 incase of ordered lists.
504 (case ltype
505 ((ordered unordered description)
506 (org-lparse-end-paragraph)
507 (org-lparse-insert-tag "<text:list%s>" extra))
508 (t (error "Unknown list type: %s" ltype)))))
510 (defun org-odt-end-list (ltype)
511 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
512 ltype))
513 (if ltype
514 (org-lparse-insert-tag "</text:list>")
515 (error "Unknown list type: %s" ltype)))
517 (defun org-odt-begin-list-item (ltype &optional arg headline)
518 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
519 ltype))
520 (case ltype
521 (ordered
522 (assert (not headline) t)
523 (let* ((counter arg) (extra ""))
524 (org-lparse-insert-tag "<text:list-item>")
525 (org-lparse-begin-paragraph)))
526 (unordered
527 (let* ((id arg) (extra ""))
528 (org-lparse-insert-tag "<text:list-item>")
529 (org-lparse-begin-paragraph)
530 (insert (if headline (org-odt-format-target headline id)
531 (org-odt-format-bookmark "" id)))))
532 (description
533 (assert (not headline) t)
534 (let ((term (or arg "(no term)")))
535 (insert
536 (org-odt-format-tags
537 '("<text:list-item>" . "</text:list-item>")
538 (org-odt-format-stylized-paragraph 'definition-term term)))
539 (org-lparse-begin 'LIST-ITEM 'unordered)
540 (org-lparse-begin 'LIST 'description)
541 (org-lparse-begin 'LIST-ITEM 'unordered)))
542 (t (error "Unknown list type"))))
544 (defun org-odt-end-list-item (ltype)
545 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
546 ltype))
547 (case ltype
548 ((ordered unordered)
549 (org-lparse-insert-tag "</text:list-item>"))
550 (description
551 (org-lparse-end-list-item)
552 (org-lparse-end 'LIST 'description)
553 (org-lparse-end-list-item))
554 (t (error "Unknown list type"))))
556 ;; Following variables are let bound when table emission is in
557 ;; progress. See org-lparse.el.
558 (defvar org-lparse-table-begin-marker)
559 (defvar org-lparse-table-ncols)
560 (defvar org-lparse-table-rowgrp-open)
561 (defvar org-lparse-table-rownum)
562 (defvar org-lparse-table-cur-rowgrp-is-hdr)
563 (defvar org-lparse-table-is-styled)
564 (defvar org-lparse-table-rowgrp-info)
565 (defvar org-lparse-table-colalign-vector)
566 (defun org-odt-begin-table (caption label attributes)
567 (when label
568 (insert
569 (org-odt-format-stylized-paragraph
570 'table (org-odt-format-entity-caption label caption "Table"))))
572 (org-lparse-insert-tag
573 "<table:table table:name=\"%s\" table:style-name=\"%s\">"
574 (or label "") "OrgTable")
575 (setq org-lparse-table-begin-marker (point)))
577 (defun org-odt-end-table ()
578 (goto-char org-lparse-table-begin-marker)
579 (loop for level from 0 below org-lparse-table-ncols
580 do (insert (org-odt-format-tags "<table:table-column/>" "")))
582 ;; fill style attributes for table cells
583 (when org-lparse-table-is-styled
584 (while (re-search-forward "@@\\(table-cell:p\\|table-cell:style-name\\)@@\\([0-9]+\\)@@\\([0-9]+\\)@@" nil t)
585 (let ((spec (match-string 1))
586 (r (string-to-number (match-string 2)))
587 (c (string-to-number (match-string 3))))
588 (cond
589 ((equal spec "table-cell:p")
590 (let ((style-name (org-odt-get-paragraph-style-for-table-cell r c)))
591 (replace-match style-name t t)))
592 ((equal spec "table-cell:style-name")
593 (let ((style-name (org-odt-get-style-name-for-table-cell r c)))
594 (replace-match style-name t t)))))))
596 (goto-char (point-max))
597 (org-lparse-insert-tag "</table:table>"))
599 (defun org-odt-begin-table-rowgroup (&optional is-header-row)
600 (when org-lparse-table-rowgrp-open
601 (org-lparse-end 'TABLE-ROWGROUP))
602 (org-lparse-insert-tag (if is-header-row
603 "<table:table-header-rows>"
604 "<table:table-rows>"))
605 (setq org-lparse-table-rowgrp-open t)
606 (setq org-lparse-table-cur-rowgrp-is-hdr is-header-row))
608 (defun org-odt-end-table-rowgroup ()
609 (when org-lparse-table-rowgrp-open
610 (setq org-lparse-table-rowgrp-open nil)
611 (org-lparse-insert-tag
612 (if org-lparse-table-cur-rowgrp-is-hdr
613 "</table:table-header-rows>" "</table:table-rows>"))))
615 (defun org-odt-format-table-row (row)
616 (org-odt-format-tags
617 '("<table:table-row>" . "</table:table-row>") row))
619 (defun org-odt-get-style-name-for-table-cell (r c)
620 (concat
621 "OrgTblCell"
622 (cond
623 ((= r 0) "T")
624 ((eq (cdr (assoc r org-lparse-table-rowgrp-info)) :start) "T")
625 (t ""))
626 (when (= r org-lparse-table-rownum) "B")
627 (cond
628 ((= c 0) "")
629 ((or (memq (nth c org-table-colgroup-info) '(:start :startend))
630 (memq (nth (1- c) org-table-colgroup-info) '(:end :startend))) "L")
631 (t ""))))
633 (defun org-odt-get-paragraph-style-for-table-cell (r c)
634 (capitalize (aref org-lparse-table-colalign-vector c)))
636 (defun org-odt-format-table-cell (data r c)
637 (if (not org-lparse-table-is-styled)
638 (org-odt-format-tags
639 '("<table:table-cell>" . "</table:table-cell>")
640 (org-odt-format-stylized-paragraph
641 (cond
642 (org-lparse-table-cur-rowgrp-is-hdr "OrgTableHeading")
643 ((and (= c 0) (org-lparse-get 'TABLE-FIRST-COLUMN-AS-LABELS))
644 "OrgTableHeading")
645 (t "OrgTableContents"))
646 data))
647 (let* ((style-name-cookie
648 (format "@@table-cell:style-name@@%03d@@%03d@@" r c))
649 (paragraph-style-cookie
650 (concat
651 (cond
652 (org-lparse-table-cur-rowgrp-is-hdr "OrgTableHeading")
653 ((and (= c 0) (org-lparse-get 'TABLE-FIRST-COLUMN-AS-LABELS))
654 "OrgTableHeading")
655 (t "OrgTableContents"))
656 (format "@@table-cell:p@@%03d@@%03d@@" r c))))
657 (org-odt-format-tags
658 '("<table:table-cell table:style-name=\"%s\">" .
659 "</table:table-cell>")
660 (org-odt-format-stylized-paragraph paragraph-style-cookie data)
661 style-name-cookie))))
663 (defun org-odt-begin-footnote-definition (n)
664 (org-lparse-begin-paragraph 'footnote))
666 (defun org-odt-end-footnote-definition (n)
667 (org-lparse-end-paragraph))
669 (defun org-odt-begin-toc (lang-specific-heading)
670 (insert
671 (format "
672 <text:table-of-content text:style-name=\"Sect2\" text:protected=\"true\" text:name=\"Table of Contents1\">
673 <text:table-of-content-source text:outline-level=\"10\">
674 <text:index-title-template text:style-name=\"Contents_20_Heading\">%s</text:index-title-template>
675 " lang-specific-heading))
677 (loop for level from 1 upto 10
678 do (insert (format
680 <text:table-of-content-entry-template text:outline-level=\"%d\" text:style-name=\"Contents_20_%d\">
681 <text:index-entry-link-start text:style-name=\"Internet_20_link\"/>
682 <text:index-entry-chapter/>
683 <text:index-entry-text/>
684 <text:index-entry-link-end/>
685 </text:table-of-content-entry-template>
686 " level level)))
688 (insert "
689 </text:table-of-content-source>
691 <text:index-body>
692 <text:index-title text:style-name=\"Sect1\" text:name=\"Table of Contents1_Head\">
693 <text:p text:style-name=\"Contents_20_Heading\">Table of Contents</text:p>
694 </text:index-title>
697 (defun org-odt-end-toc ()
698 (insert "
699 </text:index-body>
700 </text:table-of-content>
703 (defun org-odt-format-toc-entry (snumber todo headline tags href)
704 (setq headline (concat
705 (and org-export-with-section-numbers
706 (concat snumber ". "))
707 headline
708 (and tags
709 (concat
710 (org-lparse-format 'SPACES 3)
711 (org-lparse-format 'FONTIFY tags "tag")))))
712 (when todo
713 (setq headline (org-lparse-format 'FONTIFY headline "todo")))
715 (let ((org-odt-suppress-xref t))
716 (org-odt-format-link headline (concat "#" href))))
718 (defun org-odt-format-toc-item (toc-entry level org-last-level)
719 (let ((style (format "Contents_20_%d"
720 (+ level (or (org-lparse-get 'TOPLEVEL-HLEVEL) 1) -1))))
721 (insert "\n" (org-odt-format-stylized-paragraph style toc-entry) "\n")))
723 ;; Following variable is let bound during 'ORG-LINK callback. See
724 ;; org-html.el
725 (defvar org-lparse-link-description-is-image nil)
726 (defun org-odt-format-link (desc href &optional attr)
727 (cond
728 ((and (= (string-to-char href) ?#) (not org-odt-suppress-xref))
729 (setq href (concat org-export-odt-bookmark-prefix (substring href 1)))
730 (org-odt-format-tags
731 '("<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"%s\">" .
732 "</text:bookmark-ref>")
733 desc href))
734 (org-lparse-link-description-is-image
735 (org-odt-format-tags
736 '("<draw:a xlink:type=\"simple\" xlink:href=\"%s\" %s>" . "</draw:a>")
737 desc href (or attr "")))
739 (org-odt-format-tags
740 '("<text:a xlink:type=\"simple\" xlink:href=\"%s\" %s>" . "</text:a>")
741 desc href (or attr "")))))
743 (defun org-odt-format-spaces (n)
744 (org-odt-format-tags "<text:s text:c=\"%d\"/>" "" n))
746 (defun org-odt-format-tabs (&optional n)
747 (let ((tab "<text:tab/>")
748 (n (or n 1)))
749 (insert tab)))
751 (defun org-odt-format-line-break ()
752 (org-odt-format-tags "<text:line-break/>" ""))
754 (defun org-odt-format-horizontal-line ()
755 (org-odt-format-stylized-paragraph 'horizontal-line ""))
757 (defun org-odt-format-line (line)
758 (case org-lparse-dyn-current-environment
759 (fixedwidth (concat (org-odt-format-source-code-or-example-line
760 (org-xml-encode-plain-text line)) "\n"))
761 (t (concat line "\n"))))
763 (defun org-odt-format-comment (fmt &rest args)
764 (let ((comment (apply 'format fmt args)))
765 (format "\n<!-- %s -->\n" comment)))
767 (defun org-odt-format-org-entity (wd)
768 ;; FIXME: Seems to work. But is this correct?
769 (let ((s (org-entity-get-representation wd 'utf8)))
770 (and s (format "&#x%x;" (string-to-char s)))))
772 (defun org-odt-fill-tabs-and-spaces (line)
773 (replace-regexp-in-string
774 "\\([\t]\\|\\([ ]+\\)\\)" (lambda (s)
775 (cond
776 ((string= s "\t") (org-odt-format-tabs))
777 ((> (length s) 1)
778 (org-odt-format-spaces (length s)))
779 (t " "))) line))
781 (defun org-odt-format-source-code-or-example-line (line)
782 (org-odt-format-stylized-paragraph 'src (org-odt-fill-tabs-and-spaces line)))
784 (defun org-odt-format-example (lines)
785 (mapconcat
786 (lambda (line)
787 (org-odt-format-source-code-or-example-line line))
788 (org-split-string lines "[\r\n]") "\n"))
790 (defun org-odt-format-source-code-or-example (lines lang caption textareap
791 cols rows num cont
792 rpllbl fmt)
793 (org-odt-format-example (org-export-number-lines
794 (org-xml-encode-plain-text-lines lines)
795 0 0 num cont rpllbl fmt)))
797 (defun org-xml-encode-plain-text-lines (rtn)
798 (mapconcat 'org-xml-encode-plain-text (org-split-string rtn "[\r\n]") "\n"))
800 (defun org-odt-remap-stylenames (style-name)
802 (cdr (assoc style-name '(("timestamp-wrapper" . "OrgTimestampWrapper")
803 ("timestamp" . "OrgTimestamp")
804 ("timestamp-kwd" . "OrgTimestampKeyword")
805 ("tag" . "OrgTag")
806 ("todo" . "OrgTodo")
807 ("done" . "OrgDone")
808 ("target" . "OrgTarget"))))
809 style-name))
811 (defun org-odt-format-fontify (text style &optional id)
812 (let* ((style-name
813 (cond
814 ((stringp style)
815 (org-odt-remap-stylenames style))
816 ((symbolp style)
817 (org-odt-get-style-name-for-entity 'character style))
818 ((listp style)
819 (assert (< 1 (length style)))
820 (let ((parent-style (pop style)))
821 (mapconcat (lambda (s)
822 ;; (assert (stringp s) t)
823 (org-odt-remap-stylenames s)) style "")
824 (org-odt-remap-stylenames parent-style)))
825 (t (error "Don't how to handle style %s" style)))))
826 (org-odt-format-tags
827 '("<text:span text:style-name=\"%s\">" . "</text:span>")
828 text style-name)))
830 (defun org-odt-relocate-relative-path (path dir)
831 (if (file-name-absolute-p path) path
832 (file-relative-name (expand-file-name path dir)
833 (expand-file-name "eyecandy" dir))))
835 (defun org-odt-format-inline-image (thefile)
836 (let* ((thelink (if (file-name-absolute-p thefile) thefile
837 (org-xml-format-href
838 (org-odt-relocate-relative-path
839 thefile org-current-export-file))))
840 (href
841 (org-odt-format-tags
842 "<draw:image xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>" ""
843 (if org-export-odt-embed-images
844 (org-odt-copy-image-file thefile) thelink))))
845 (org-export-odt-format-image thefile href)))
847 (defun org-odt-format-org-link (opt-plist type-1 path fragment desc attr
848 descp)
849 "Make an HTML link.
850 OPT-PLIST is an options list.
851 TYPE is the device-type of the link (THIS://foo.html)
852 PATH is the path of the link (http://THIS#locationx)
853 FRAGMENT is the fragment part of the link, if any (foo.html#THIS)
854 DESC is the link description, if any.
855 ATTR is a string of other attributes of the a element.
856 MAY-INLINE-P allows inlining it as an image."
858 (declare (special org-lparse-par-open))
859 (save-match-data
860 (let* ((may-inline-p
861 (and (member type-1 '("http" "https" "file"))
862 (org-lparse-should-inline-p path descp)
863 (not fragment)))
864 (type (if (equal type-1 "id") "file" type-1))
865 (filename path)
866 (thefile path))
868 (cond
869 ;; check for inlined images
870 ((and (member type '("file"))
871 (not fragment)
872 (org-file-image-p
873 filename org-odt-export-inline-image-extensions)
874 (or (eq t org-odt-export-inline-images)
875 (and org-odt-export-inline-images (not descp))))
877 ;; (when (and (string= type "file") (file-name-absolute-p path))
878 ;; (setq thefile (concat "file://" (expand-file-name path))))
879 ;; (setq thefile (org-xml-format-href thefile))
880 ;; (org-export-html-format-image thefile)
881 (org-odt-format-inline-image thefile))
883 (when (string= type "file")
884 (setq thefile
885 (cond
886 ((file-name-absolute-p path)
887 (concat "file://" (expand-file-name path)))
888 (t (org-odt-relocate-relative-path
889 thefile org-current-export-file)))))
891 (when (and (member type '("" "http" "https" "file" "coderef"))
892 fragment)
893 (setq thefile (concat thefile "#" fragment)))
895 (setq thefile (org-xml-format-href thefile))
897 (when (not (member type '("" "file" "coderef")))
898 (setq thefile (concat type ":" thefile)))
900 (let ((org-odt-suppress-xref (string= type "coderef")))
901 (org-odt-format-link
902 (org-xml-format-desc desc) thefile attr)))))))
904 (defun org-odt-format-heading (text level &optional id)
905 (let* ((text (if id (org-odt-format-target text id) text)))
906 (org-odt-format-tags
907 '("<text:h text:style-name=\"Heading_20_%s\" text:outline-level=\"%s\">" .
908 "</text:h>") text level level)))
910 (defun org-odt-format-headline (title extra-targets tags
911 &optional snumber level)
912 (concat
913 (org-lparse-format 'EXTRA-TARGETS extra-targets)
915 ;; No need to generate section numbers. They are auto-generated by
916 ;; the application
918 ;; (concat (org-lparse-format 'SECTION-NUMBER snumber level) " ")
919 title
920 (and tags (concat (org-lparse-format 'SPACES 3)
921 (org-lparse-format 'ORG-TAGS tags)))))
923 (defun org-odt-format-anchor (text name &optional class)
924 (org-odt-format-target text name))
926 (defun org-odt-format-bookmark (text id)
927 (if id
928 (org-odt-format-tags "<text:bookmark text:name=\"%s\"/>" text id)
929 text))
931 (defun org-odt-format-target (text id)
932 (let ((name (concat org-export-odt-bookmark-prefix id)))
933 (concat
934 (and id (org-odt-format-tags
935 "<text:bookmark-start text:name=\"%s\"/>" "" name))
936 (org-odt-format-bookmark text id)
937 (and id (org-odt-format-tags
938 "<text:bookmark-end text:name=\"%s\"/>" "" name)))))
940 (defun org-odt-format-footnote (n def)
941 (let ((id (concat "fn" n))
942 (note-class "footnote")
943 (par-style "Footnote"))
944 (org-odt-format-tags
945 '("<text:note text:id=\"%s\" text:note-class=\"%s\">" .
946 "</text:note>")
947 (concat
948 (org-odt-format-tags
949 '("<text:note-citation>" . "</text:note-citation>")
951 (org-odt-format-tags
952 '("<text:note-body>" . "</text:note-body>")
953 def))
954 id note-class)))
956 (defun org-odt-format-footnote-reference (n def refcnt)
957 (if (= refcnt 1)
958 (org-odt-format-footnote n def)
959 (org-odt-format-footnote-ref n)))
961 (defun org-odt-format-footnote-ref (n)
962 (let ((note-class "footnote")
963 (ref-format "text")
964 (ref-name (concat "fn" n)))
965 (org-odt-format-tags
966 '("<text:span text:style-name=\"%s\">" . "</text:span>")
967 (org-odt-format-tags
968 '("<text:note-ref text:note-class=\"%s\" text:reference-format=\"%s\" text:ref-name=\"%s\">" . "</text:note-ref>")
969 n note-class ref-format ref-name)
970 "OrgSuperscript")))
972 (defun org-odt-get-image-name (file-name)
973 (require 'sha1)
974 (file-relative-name
975 (expand-file-name
976 (concat (sha1 file-name) "." (file-name-extension file-name)) "Pictures")))
978 (defun org-export-odt-format-image (src href
979 ;; par-open
981 "Create image tag with source and attributes."
982 (save-match-data
984 (let (embed-as caption attr label attr-plist size width height)
986 (cond
987 ((string-match "^ltxpng/" src)
988 ;; FIXME: Anyway the latex src can be embedded as an
989 ;; annotation
991 ;; (org-find-text-property-in-string 'org-latex-src src)
992 (setq caption nil attr nil label nil embed-as 'character))
995 (setq caption (org-find-text-property-in-string 'org-caption src)
996 caption (and caption (org-xml-format-desc caption))
997 attr (org-find-text-property-in-string 'org-attributes src)
998 label (org-find-text-property-in-string 'org-label src)
999 embed-as 'paragraph)))
1001 (setq attr-plist (when attr (read attr)))
1002 (setq size (org-odt-image-size-from-file
1003 src (plist-get attr-plist :width)
1004 (plist-get attr-plist :height)
1005 (plist-get attr-plist :scale) nil embed-as))
1007 (org-export-odt-do-format-image embed-as caption attr label
1008 size href))))
1010 (defun org-export-odt-do-format-image (embed-as caption attr label
1011 size href)
1012 "Create image tag with source and attributes."
1013 (save-match-data
1014 (let ((width (car size)) (height (cdr size))
1015 (draw-frame-pair
1016 '("<draw:frame draw:style-name=\"%s\"
1017 text:anchor-type=\"%s\"
1018 draw:z-index=\"%d\" %s>" . "</draw:frame>")))
1019 (cond
1020 ((and (not caption) (not label))
1021 (let (style-name anchor-type)
1022 (cond
1023 ((eq embed-as 'paragraph)
1024 (setq style-name "OrgGraphicsParagraph" anchor-type "paragraph"))
1025 ((eq embed-as 'character)
1026 (setq style-name "OrgGraphicsBaseline" anchor-type "as-char")))
1027 (org-odt-format-tags
1028 draw-frame-pair href style-name anchor-type 0
1029 (org-odt-image-attrs-from-size width height))))
1032 (concat
1033 ;; (when par-open (org-odt-close-par))
1034 (org-odt-format-tags
1035 draw-frame-pair
1036 (org-odt-format-tags
1037 '("<draw:text-box fo:min-height=\"%dcm\">" . "</draw:text-box>")
1038 (org-odt-format-stylized-paragraph
1039 'illustration
1040 (concat
1041 (let ((extra " style:rel-width=\"100%\" style:rel-height=\"scale\""))
1042 (org-odt-format-tags
1043 draw-frame-pair href "OrgGraphicsParagraphContent" "paragraph" 2
1044 (concat (org-odt-image-attrs-from-size width height) extra)))
1045 (org-odt-format-entity-caption label caption)))
1046 height)
1047 "OrgFrame" "paragraph" 1
1048 (org-odt-image-attrs-from-size width))
1050 ;; (when par-open (org-odt-open-par))
1051 ))))))
1053 ;; xml files generated on-the-fly
1054 (defconst org-export-odt-save-list
1055 '("META-INF/manifest.xml" "content.xml" "meta.xml" "styles.xml"))
1057 ;; xml files that are copied
1058 (defconst org-export-odt-nosave-list '())
1060 ;; xml files that contribute to the final odt file
1061 (defvar org-export-odt-file-list nil)
1063 (defconst org-export-odt-manifest-lines
1064 '(("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
1065 "<manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"1.2\">"
1066 "<manifest:file-entry manifest:media-type=\"application/vnd.oasis.opendocument.text\" manifest:version=\"1.2\" manifest:full-path=\"/\"/>"
1067 "<manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"content.xml\"/>"
1068 "<manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"styles.xml\"/>"
1069 "<manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"meta.xml\"/>"
1070 "<manifest:file-entry manifest:media-type=\"\" manifest:full-path=\"Pictures/\"/>") . ("</manifest:manifest>")))
1072 (defconst org-export-odt-meta-lines
1073 '(("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
1074 "<office:document-meta"
1075 " xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\""
1076 " xmlns:xlink=\"http://www.w3.org/1999/xlink\""
1077 " xmlns:dc=\"http://purl.org/dc/elements/1.1/\""
1078 " xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\""
1079 " xmlns:ooo=\"http://openoffice.org/2004/office\" "
1080 " office:version=\"1.2\">"
1081 " <office:meta>") . (" </office:meta>" "</office:document-meta>")))
1083 (defun org-odt-copy-image-file (path &optional target-file)
1084 "Returns the internal name of the file"
1085 (let* ((image-type (file-name-extension path))
1086 (media-type (format "image/%s" image-type))
1087 (src-file (expand-file-name
1088 path (file-name-directory org-current-export-file)))
1089 (target-file (or target-file (org-odt-get-image-name src-file)))
1090 ;; FIXME
1091 (body-only nil))
1093 (when (not org-lparse-to-buffer)
1094 (message "Embedding %s as %s ..."
1095 (substring-no-properties path) target-file)
1096 (copy-file src-file target-file 'overwrite)
1097 (org-odt-update-manifest-file media-type target-file)
1098 (push target-file org-export-odt-file-list)) target-file))
1100 (defun org-odt-image-attrs-from-size (&optional width height)
1101 (concat
1102 (when width (format "svg:width=\"%0.2fcm\"" width))
1104 (when height (format "svg:height=\"%0.2fcm\"" height))))
1106 (defvar org-export-odt-image-size-probe-method
1107 '(emacs imagemagick force)
1108 "Ordered list of methods by for determining size of an embedded
1109 image.")
1111 (defvar org-export-odt-default-image-sizes-alist
1112 '(("character" . (5 . 0.4))
1113 ("paragraph" . (5 . 5)))
1114 "Hardcoded image dimensions one for each of the anchor
1115 methods.")
1117 (defun org-odt-do-image-size (probe-method file &optional dpi anchor-type)
1118 (setq dpi (or dpi org-export-odt-pixels-per-inch))
1119 (setq anchor-type (or anchor-type "paragraph"))
1120 (flet ((size-in-cms (size-in-pixels)
1121 (flet ((pixels-to-cms (pixels)
1122 (let* ((cms-per-inch 2.54)
1123 (inches (/ pixels dpi)))
1124 (* cms-per-inch inches))))
1125 (and size-in-pixels
1126 (cons (pixels-to-cms (car size-in-pixels))
1127 (pixels-to-cms (cdr size-in-pixels)))))))
1128 (case probe-method
1129 (emacs
1130 (size-in-cms (ignore-errors (image-size (create-image file) 'pixels))))
1131 (imagemagick
1132 (size-in-cms
1133 (let ((dim (shell-command-to-string
1134 (format "identify -format \"%%w:%%h\" \"%s\"" file))))
1135 (when (string-match "\\([0-9]+\\):\\([0-9]+\\)" dim)
1136 (cons (string-to-number (match-string 1 dim))
1137 (string-to-number (match-string 2 dim)))))))
1139 (cdr (assoc-string anchor-type
1140 org-export-odt-default-image-sizes-alist))))))
1142 (defun org-odt-image-size-from-file (file &optional user-width
1143 user-height scale dpi embed-as)
1144 (unless (file-name-absolute-p file)
1145 (setq file (expand-file-name
1146 file (file-name-directory org-current-export-file))))
1147 (let* (size width height)
1148 (unless (and user-height user-width)
1149 (loop for probe-method in org-export-odt-image-size-probe-method
1150 until size
1151 do (setq size (org-odt-do-image-size
1152 probe-method file dpi embed-as)))
1153 (or size (error "Cannot determine Image size. Aborting ..."))
1154 (setq width (car size) height (cdr size)))
1155 (cond
1156 (scale
1157 (setq width (* width scale) height (* height scale)))
1158 ((and user-height user-width)
1159 (setq width user-width height user-height))
1160 (user-height
1161 (setq width (* user-height (/ width height)) height user-height))
1162 (user-width
1163 (setq height (* user-width (/ height width)) width user-width))
1164 (t (ignore)))
1165 (cons width height)))
1167 (defvar org-odt-default-entity "Illustration")
1168 (defun org-odt-format-entity-caption (label caption &optional default-entity)
1169 (if (not label) (or caption "")
1170 (let* ((label-components (org-odt-parse-label label))
1171 (entity (car label-components))
1172 (seqno (cdr label-components))
1173 (caption (and caption (concat ": " caption))))
1174 (unless seqno
1175 (setq seqno label
1176 entity (or default-entity org-odt-default-entity)))
1177 (concat
1178 entity " "
1179 (org-odt-format-tags
1180 '("<text:sequence text:ref-name=\"%s\" text:name=\"%s\" text:formula=\"ooow:%s+1\" style:num-format=\"1\">" . "</text:sequence>")
1181 seqno label entity entity)
1182 caption))))
1184 (defun org-odt-format-tags (tag text &rest args)
1185 (let ((prefix (when org-lparse-encode-pending "@"))
1186 (suffix (when org-lparse-encode-pending "@")))
1187 (apply 'org-lparse-format-tags tag text prefix suffix args)))
1189 (defun org-odt-init-outfile (filename)
1190 (let* ((outdir (make-temp-file org-export-odt-tmpdir-prefix t))
1191 (mimetype-file (expand-file-name "mimetype" outdir))
1192 (content-file (expand-file-name "content.xml" outdir))
1193 (manifest-file (expand-file-name "META-INF/manifest.xml" outdir))
1194 (meta-file (expand-file-name "meta.xml" outdir))
1195 (styles-file (expand-file-name "styles.xml" outdir))
1196 (pictures-dir (expand-file-name "Pictures" outdir))
1197 (body-only nil))
1199 ;; content file
1200 (with-current-buffer (find-file-noselect content-file t)
1201 (erase-buffer))
1203 ;; FIXME: How to factor in body-only here
1204 (unless body-only
1205 ;; manifest file
1206 (make-directory (file-name-directory manifest-file))
1207 (with-current-buffer (find-file-noselect manifest-file t)
1208 (erase-buffer)
1209 (insert (mapconcat 'identity (car org-export-odt-manifest-lines) "\n"))
1210 (insert "\n")
1211 (save-excursion
1212 (insert (mapconcat 'identity (cdr org-export-odt-manifest-lines) "\n"))))
1214 ;; meta file
1215 (with-current-buffer (find-file-noselect meta-file t)
1216 (erase-buffer)
1217 (insert (mapconcat 'identity (car org-export-odt-meta-lines) "\n"))
1218 (insert "\n")
1219 (save-excursion
1220 (insert (mapconcat 'identity (cdr org-export-odt-meta-lines) "\n"))))
1222 ;; styles file
1223 ;; (copy-file org-export-odt-styles-file styles-file t)
1225 ;; Pictures dir
1226 (make-directory pictures-dir)
1228 ;; initialize list of files that contribute to the odt file
1229 (setq org-export-odt-file-list
1230 (append org-export-odt-save-list org-export-odt-nosave-list)))
1231 content-file))
1233 (defconst org-export-odt-mimetype-lines
1234 '("application/vnd.oasis.opendocument.text"))
1236 (defconst org-odt-manifest-file-entry-tag
1237 "<manifest:file-entry manifest:media-type=\"%s\" manifest:full-path=\"%s\"/>")
1239 (defun org-odt-save-as-outfile (target opt-plist)
1240 ;; write meta file
1241 (org-odt-update-meta-file opt-plist)
1243 ;; write styles file
1244 (org-odt-copy-styles-file)
1246 ;; Update styles.xml - take care of outline numbering
1247 (with-current-buffer
1248 (find-file-noselect (expand-file-name "styles.xml") t)
1249 ;; Don't make automatic backup of styles.xml file. This setting
1250 ;; prevents the backedup styles.xml file from being zipped in to
1251 ;; odt file. This is more of a hackish fix. Better alternative
1252 ;; would be to fix the zip command so that the output odt file
1253 ;; includes only the needed files and excludes any auto-generated
1254 ;; extra files like backups and auto-saves etc etc. Note that
1255 ;; currently the zip command zips up the entire temp directory so
1256 ;; that any auto-generated files created under the hood ends up in
1257 ;; the resulting odt file.
1258 (set (make-local-variable 'backup-inhibited) t)
1260 ;; Import local setting of `org-export-with-section-numbers'
1261 (org-lparse-bind-local-variables opt-plist)
1262 (org-odt-configure-outline-numbering
1263 (if org-export-with-section-numbers org-export-headline-levels 0)))
1265 (let ((zipdir default-directory))
1266 (message "Switching to directory %s" (expand-file-name zipdir))
1268 ;; save all xml files
1269 (mapc (lambda (file)
1270 (with-current-buffer
1271 (find-file-noselect (expand-file-name file) t)
1272 ;; prettify output
1273 (indent-region (point-min) (point-max))
1274 (save-buffer)))
1275 org-export-odt-save-list)
1277 (let* ((target-name (file-name-nondirectory target))
1278 (target-dir (file-name-directory target))
1279 (cmd (format "zip -rmTq %s %s" target-name ".")))
1280 (when (file-exists-p target)
1281 ;; FIXME: If the file is locked this throws a cryptic error
1282 (delete-file target))
1284 (let ((coding-system-for-write 'no-conversion) exitcode)
1285 (message "Creating odt file using \"%s\"" cmd)
1286 (setq exitcode
1287 (apply 'call-process
1288 "zip"
1292 (append (list "-rmTq") (list target-name "."))))
1294 (or (zerop exitcode)
1295 (error "Unable to create odt file (%S)" exitcode)))
1297 ;; move the file from outdir to target-dir
1298 (rename-file target-name target-dir)
1300 ;; kill all xml buffers
1301 (mapc (lambda (file)
1302 (kill-buffer
1303 (find-file-noselect (expand-file-name file zipdir) t)))
1304 org-export-odt-save-list)
1306 (delete-directory zipdir)))
1308 (message "Created %s" target)
1309 (set-buffer (find-file-noselect target t)))
1311 (defun org-odt-update-meta-file (opt-plist)
1312 (with-current-buffer
1313 (find-file-noselect (expand-file-name "meta.xml") t)
1314 (let ((date (or (plist-get opt-plist :effective-date) ""))
1315 (author (or (plist-get opt-plist :author) ""))
1316 (email (plist-get opt-plist :email))
1317 (keywords (plist-get opt-plist :keywords))
1318 (description (plist-get opt-plist :description))
1319 (title (plist-get opt-plist :title)))
1321 (insert
1322 "\n"
1323 (org-odt-format-tags '("<dc:creator>" . "</dc:creator>") author)
1324 (org-odt-format-tags
1325 '("\n<meta:initial-creator>" . "</meta:initial-creator>") author)
1326 (org-odt-format-tags '("\n<dc:date>" . "</dc:date>") date)
1327 (org-odt-format-tags
1328 '("\n<meta:creation-date>" . "</meta:creation-date>") date)
1329 (org-odt-format-tags '("\n<meta:generator>" . "</meta:generator>")
1330 (when org-export-creator-info
1331 (format "Org-%s/Emacs-%s"
1332 org-version emacs-version)))
1333 (org-odt-format-tags '("\n<meta:keyword>" . "</meta:keyword>") keywords)
1334 (org-odt-format-tags '("\n<dc:subject>" . "</dc:subject>") description)
1335 (org-odt-format-tags '("\n<dc:title>" . "</dc:title>") title)
1336 "\n"))))
1338 (defun org-odt-update-manifest-file (media-type full-path)
1339 (with-current-buffer
1340 (find-file-noselect (expand-file-name "META-INF/manifest.xml") t)
1341 (insert (format org-odt-manifest-file-entry-tag media-type full-path))))
1343 (defun org-odt-finalize-outfile ()
1344 (message "org-newodt: Finalizing outfile")
1345 (org-odt-delete-empty-paragraphs))
1347 (defun org-odt-delete-empty-paragraphs ()
1348 (goto-char (point-min))
1349 (let ((open "<text:p[^>]*>")
1350 (close "</text:p>"))
1351 (while (re-search-forward (format "%s[ \r\n\t]*%s" open close) nil t)
1352 (replace-match ""))))
1354 (defun org-odt-get (what &optional opt-plist)
1355 (case what
1356 (BACKEND 'odt)
1357 (EXPORT-DIR (org-export-directory :html opt-plist))
1358 (FILE-NAME-EXTENSION "odt")
1359 (EXPORT-BUFFER-NAME "*Org ODT Export*")
1360 (ENTITY-CONTROL org-odt-entity-control-callbacks-alist)
1361 (ENTITY-FORMAT org-odt-entity-format-callbacks-alist)
1362 (INIT-METHOD 'org-odt-init-outfile)
1363 (FINAL-METHOD 'org-odt-finalize-outfile)
1364 (SAVE-METHOD 'org-odt-save-as-outfile)
1365 (OTHER-BACKENDS
1366 '("bib" "doc" "doc6" "doc95" "html" "xhtml" "latex" "odt" "ott" "pdf" "rtf"
1367 "sdw" "sdw3" "sdw4" "stw " "sxw" "mediawiki" "text" "txt" "uot" "vor"
1368 "vor3" "vor4" "docbook" "ooxml" "ppt" "odp"))
1369 (CONVERT-METHOD org-export-convert-process)
1370 (TOPLEVEL-HLEVEL 1)
1371 (SPECIAL-STRING-REGEXPS org-export-odt-special-string-regexps)
1372 (INLINE-IMAGES 'maybe)
1373 (INLINE-IMAGE-EXTENSIONS '("png" "jpeg" "jpg" "gif" "svg"))
1374 (PLAIN-TEXT-MAP '(("&" . "&amp;") ("<" . "&lt;") (">" . "&gt;")))
1375 (TABLE-FIRST-COLUMN-AS-LABELS nil)
1376 (FOOTNOTE-SEPARATOR (org-lparse-format 'FONTIFY "," 'superscript))
1377 (t (error "Unknown property: %s" what))))
1379 (defun org-odt-parse-label (label)
1380 (save-match-data
1381 (if (not (string-match "\\`[a-zA-Z]+:\\(.+\\)" label))
1382 (cons label nil)
1383 (cons
1384 (capitalize (substring label 0 (1- (match-beginning 1))))
1385 (substring label (match-beginning 1))))))
1387 (defvar org-lparse-latex-fragment-fallback) ; set by org-do-lparse
1388 (defun org-export-odt-preprocess (parameters)
1389 "Convert LaTeX fragments to images."
1390 (when (and org-current-export-file
1391 (plist-get parameters :LaTeX-fragments))
1392 (org-format-latex
1393 (concat "ltxpng/" (file-name-sans-extension
1394 (file-name-nondirectory
1395 org-current-export-file)))
1396 org-current-export-dir nil "Creating LaTeX image %s"
1397 nil nil
1398 (cond
1399 ((eq (plist-get parameters :LaTeX-fragments) 'verbatim) 'verbatim)
1400 ;; Investigate MathToWeb for converting TeX equations to MathML
1401 ;; See http://lists.gnu.org/archive/html/emacs-orgmode/2011-03/msg01755.html
1402 ((or (eq (plist-get parameters :LaTeX-fragments) 'mathjax )
1403 (eq (plist-get parameters :LaTeX-fragments) t ))
1404 (org-lparse-warn
1405 (concat
1406 "Use of MathJax is incompatible with ODT exporter. "
1407 (format "Using %S instead." org-lparse-latex-fragment-fallback)))
1408 org-lparse-latex-fragment-fallback)
1409 ((eq (plist-get parameters :LaTeX-fragments) 'dvipng ) 'dvipng)
1410 (t nil))))
1411 (goto-char (point-min))
1412 (let (label label-components category value pretty-label)
1413 (while (re-search-forward "\\\\ref{\\([^{}\n]+\\)}" nil t)
1414 (org-if-unprotected-at (match-beginning 1)
1415 (setq label (match-string 1)
1416 label-components (org-odt-parse-label label)
1417 category (car label-components)
1418 value (cdr label-components)
1419 pretty-label (if value (concat category " " value) label))
1420 (replace-match
1421 (let ((org-lparse-encode-pending t))
1422 (org-odt-format-tags
1423 '("<text:sequence-ref text:reference-format=\"category-and-value\" text:ref-name=\"%s\">"
1424 . "</text:sequence-ref>") pretty-label label)) t t)))))
1426 (declare-function archive-zip-extract "arc-mode.el" (archive name))
1427 (defun org-odt-zip-extract-one (archive member &optional target)
1428 (require 'arc-mode)
1429 (let* ((target (or target default-directory))
1430 (archive (expand-file-name archive))
1431 (archive-zip-extract
1432 (list "unzip" "-qq" "-o" "-d" target))
1433 exit-code command-output)
1434 (setq command-output
1435 (with-temp-buffer
1436 (setq exit-code (archive-zip-extract archive member))
1437 (buffer-string)))
1438 (unless (zerop exit-code)
1439 (message command-output)
1440 (error "Extraction failed"))))
1442 (defun org-odt-zip-extract (archive members &optional target)
1443 (when (atom members) (setq members (list members)))
1444 (mapc (lambda (member)
1445 (org-odt-zip-extract-one archive member target))
1446 members))
1448 (defun org-odt-copy-styles-file (&optional styles-file)
1449 ;; Non-availability of styles.xml is not a critical error. For now
1450 ;; throw an error purely for aesthetic reasons.
1451 (setq styles-file (or styles-file
1452 org-export-odt-styles-file
1453 (expand-file-name "OrgOdtStyles.xml" org-odt-data-dir)
1454 (error "org-odt: Missing styles file?")))
1455 (cond
1456 ((listp styles-file)
1457 (let ((archive (nth 0 styles-file))
1458 (members (nth 1 styles-file)))
1459 (org-odt-zip-extract archive members)
1460 (mapc
1461 (lambda (member)
1462 (when (org-file-image-p member)
1463 (let* ((image-type (file-name-extension member))
1464 (media-type (format "image/%s" image-type)))
1465 (org-odt-update-manifest-file media-type member))))
1466 members)))
1467 ((and (stringp styles-file) (file-exists-p styles-file))
1468 (let ((styles-file-type (file-name-extension styles-file)))
1469 (cond
1470 ((string= styles-file-type "xml")
1471 (copy-file styles-file "styles.xml" t))
1472 ((member styles-file-type '("odt" "ott"))
1473 (org-odt-zip-extract styles-file "styles.xml")))))
1475 (error (format "Invalid specification of styles.xml file: %S"
1476 org-export-odt-styles-file)))))
1478 (defvar org-export-odt-factory-settings
1479 "d4328fb9d1b6cb211d4320ff546829f26700dc5e"
1480 "SHA1 hash of OrgOdtStyles.xml.")
1482 (defun org-odt-configure-outline-numbering (level)
1483 "Outline numbering is retained only upto LEVEL.
1484 To disable outline numbering pass a LEVEL of 0."
1485 (if (not (string= org-export-odt-factory-settings (sha1 (current-buffer))))
1486 (org-lparse-warn
1487 "org-odt: Using custom styles file? Consider tweaking styles.xml for better output. To suppress this warning update `org-export-odt-factory-settings'")
1488 (goto-char (point-min))
1489 (let ((regex
1490 "<text:outline-level-style\\(.*\\)text:level=\"\\(.*\\)\"\\(.*\\)>")
1491 (replacement
1492 "<text:outline-level-style\\1text:level=\"\\2\" style:num-format=\"\">"))
1493 (while (re-search-forward regex nil t)
1494 (when (> (string-to-number (match-string 1)) level)
1495 (replace-match replacement t nil))))
1496 (save-buffer 0)))
1498 ;;;###autoload
1499 (defun org-odt-unit-test (&optional linger)
1500 "Automatically visit the Unit Test file and export it."
1501 (interactive "P")
1502 (with-current-buffer
1503 (find-file (expand-file-name "tests/test.org" org-odt-data-dir))
1504 (unless linger
1505 (call-interactively 'org-export-as-odt-and-open))))
1507 (provide 'org-odt)
1509 ;;; org-odt.el ends here