Merge branch 'maint'
[org-mode.git] / lisp / org-odt.el
blob822e62fd9b5863d84d2eb521a1e61bb7e29ecdf3
1 ;;; org-odt.el --- OpenDocumentText export for Org-mode
3 ;; Copyright (C) 2010-2012 Free Software Foundation, Inc.
5 ;; Author: Jambunathan K <kjambunathan at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;;; Code:
27 (eval-when-compile
28 (require 'cl))
29 (require 'org-lparse)
31 (defgroup org-export-odt nil
32 "Options specific for ODT export of Org-mode files."
33 :tag "Org Export ODT"
34 :group 'org-export)
36 (defvar org-lparse-dyn-first-heading-pos) ; let bound during org-do-lparse
37 (defun org-odt-insert-toc ()
38 (goto-char (point-min))
39 (cond
40 ((re-search-forward
41 "\\(<text:p [^>]*>\\)?\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*\\(</text:p>\\)?"
42 nil t)
43 (replace-match ""))
45 (goto-char org-lparse-dyn-first-heading-pos)))
46 (insert (org-odt-format-toc)))
48 (defun org-odt-end-export ()
49 (org-odt-insert-toc)
50 (org-odt-fixup-label-references)
52 ;; remove empty paragraphs
53 (goto-char (point-min))
54 (while (re-search-forward
55 "<text:p\\( text:style-name=\"Text_20_body\"\\)?>[ \r\n\t]*</text:p>"
56 nil t)
57 (replace-match ""))
58 (goto-char (point-min))
60 ;; Convert whitespace place holders
61 (goto-char (point-min))
62 (let (beg end n)
63 (while (setq beg (next-single-property-change (point) 'org-whitespace))
64 (setq n (get-text-property beg 'org-whitespace)
65 end (next-single-property-change beg 'org-whitespace))
66 (goto-char beg)
67 (delete-region beg end)
68 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
69 (make-string n ?x)))))
71 ;; Remove empty lines at the beginning of the file.
72 (goto-char (point-min))
73 (when (looking-at "\\s-+\n") (replace-match ""))
75 ;; Remove display properties
76 (remove-text-properties (point-min) (point-max) '(display t)))
78 (defvar org-odt-suppress-xref nil)
79 (defconst org-export-odt-special-string-regexps
80 '(("\\\\-" . "&#x00ad;\\1") ; shy
81 ("---\\([^-]\\)" . "&#x2014;\\1") ; mdash
82 ("--\\([^-]\\)" . "&#x2013;\\1") ; ndash
83 ("\\.\\.\\." . "&#x2026;")) ; hellip
84 "Regular expressions for special string conversion.")
86 (defconst org-odt-lib-dir (file-name-directory load-file-name)
87 "Location of ODT exporter.
88 Use this to infer values of `org-odt-styles-dir' and
89 `org-export-odt-schema-dir'.")
91 (defvar org-odt-data-dir nil
92 "Data directory for ODT exporter.
93 Use this to infer values of `org-odt-styles-dir' and
94 `org-export-odt-schema-dir'.")
96 (defconst org-odt-schema-dir-list
97 (list
98 (and org-odt-data-dir
99 (expand-file-name "./schema/" org-odt-data-dir)) ; bail out
100 (eval-when-compile
101 (and (boundp 'org-odt-data-dir) org-odt-data-dir ; see make install
102 (expand-file-name "./schema/" org-odt-data-dir)))
103 (expand-file-name "../contrib/odt/etc/schema/" org-odt-lib-dir) ; git
105 "List of directories to search for OpenDocument schema files.
106 Use this list to set the default value of
107 `org-export-odt-schema-dir'. The entries in this list are
108 populated heuristically based on the values of `org-odt-lib-dir'
109 and `org-odt-data-dir'.")
111 (defcustom org-export-odt-schema-dir
112 (let* ((schema-dir
113 (catch 'schema-dir
114 (message "Debug (org-odt): Searching for OpenDocument schema files...")
115 (mapc
116 (lambda (schema-dir)
117 (when schema-dir
118 (message "Debug (org-odt): Trying %s..." schema-dir)
119 (when (and (file-readable-p
120 (expand-file-name "od-manifest-schema-v1.2-cs01.rnc"
121 schema-dir))
122 (file-readable-p
123 (expand-file-name "od-schema-v1.2-cs01.rnc"
124 schema-dir))
125 (file-readable-p
126 (expand-file-name "schemas.xml" schema-dir)))
127 (message "Debug (org-odt): Using schema files under %s"
128 schema-dir)
129 (throw 'schema-dir schema-dir))))
130 org-odt-schema-dir-list)
131 (message "Debug (org-odt): No OpenDocument schema files installed")
132 nil)))
133 schema-dir)
134 "Directory that contains OpenDocument schema files.
136 This directory contains:
137 1. rnc files for OpenDocument schema
138 2. a \"schemas.xml\" file that specifies locating rules needed
139 for auto validation of OpenDocument XML files.
141 Use the customize interface to set this variable. This ensures
142 that `rng-schema-locating-files' is updated and auto-validation
143 of OpenDocument XML takes place based on the value
144 `rng-nxml-auto-validate-flag'.
146 The default value of this variable varies depending on the
147 version of org in use and is initialized from
148 `org-odt-schema-dir-list'. The OASIS schema files are available
149 only in the org's private git repository. It is *not* bundled
150 with GNU ELPA tar or standard Emacs distribution."
151 :type '(choice
152 (const :tag "Not set" nil)
153 (directory :tag "Schema directory"))
154 :group 'org-export-odt
155 :set
156 (lambda (var value)
157 "Set `org-export-odt-schema-dir'.
158 Also add it to `rng-schema-locating-files'."
159 (let ((schema-dir value))
160 (set var
161 (if (and
162 (file-readable-p
163 (expand-file-name "od-manifest-schema-v1.2-cs01.rnc" schema-dir))
164 (file-readable-p
165 (expand-file-name "od-schema-v1.2-cs01.rnc" schema-dir))
166 (file-readable-p
167 (expand-file-name "schemas.xml" schema-dir)))
168 schema-dir
169 (when value
170 (message "Error (org-odt): %s has no OpenDocument schema files"
171 value))
172 nil)))
173 (when org-export-odt-schema-dir
174 (eval-after-load 'rng-loc
175 '(add-to-list 'rng-schema-locating-files
176 (expand-file-name "schemas.xml"
177 org-export-odt-schema-dir))))))
179 (defconst org-odt-styles-dir-list
180 (list
181 (and org-odt-data-dir
182 (expand-file-name "./styles/" org-odt-data-dir)) ; bail out
183 (eval-when-compile
184 (and (boundp 'org-odt-data-dir) org-odt-data-dir ; see make install
185 (expand-file-name "./styles/" org-odt-data-dir)))
186 (expand-file-name "../etc/styles/" org-odt-lib-dir) ; git
187 (expand-file-name "./etc/styles/" org-odt-lib-dir) ; elpa
188 (expand-file-name "./org/" data-directory) ; system
190 "List of directories to search for OpenDocument styles files.
191 See `org-odt-styles-dir'. The entries in this list are populated
192 heuristically based on the values of `org-odt-lib-dir' and
193 `org-odt-data-dir'.")
195 (defconst org-odt-styles-dir
196 (let* ((styles-dir
197 (catch 'styles-dir
198 (message "Debug (org-odt): Searching for OpenDocument styles files...")
199 (mapc (lambda (styles-dir)
200 (when styles-dir
201 (message "Debug (org-odt): Trying %s..." styles-dir)
202 (when (and (file-readable-p
203 (expand-file-name
204 "OrgOdtContentTemplate.xml" styles-dir))
205 (file-readable-p
206 (expand-file-name
207 "OrgOdtStyles.xml" styles-dir)))
208 (message "Debug (org-odt): Using styles under %s"
209 styles-dir)
210 (throw 'styles-dir styles-dir))))
211 org-odt-styles-dir-list)
212 nil)))
213 (unless styles-dir
214 (error "Error (org-odt): Cannot find factory styles files. Aborting."))
215 styles-dir)
216 "Directory that holds auxiliary XML files used by the ODT exporter.
218 This directory contains the following XML files -
219 \"OrgOdtStyles.xml\" and \"OrgOdtContentTemplate.xml\". These
220 XML files are used as the default values of
221 `org-export-odt-styles-file' and
222 `org-export-odt-content-template-file'.
224 The default value of this variable varies depending on the
225 version of org in use and is initialized from
226 `org-odt-styles-dir-list'. Note that the user could be using org
227 from one of: org's own private git repository, GNU ELPA tar or
228 standard Emacs.")
230 (defvar org-odt-file-extensions
231 '(("odt" . "OpenDocument Text")
232 ("ott" . "OpenDocument Text Template")
233 ("odm" . "OpenDocument Master Document")
234 ("ods" . "OpenDocument Spreadsheet")
235 ("ots" . "OpenDocument Spreadsheet Template")
236 ("odg" . "OpenDocument Drawing (Graphics)")
237 ("otg" . "OpenDocument Drawing Template")
238 ("odp" . "OpenDocument Presentation")
239 ("otp" . "OpenDocument Presentation Template")
240 ("odi" . "OpenDocument Image")
241 ("odf" . "OpenDocument Formula")
242 ("odc" . "OpenDocument Chart")))
244 (mapc
245 (lambda (desc)
246 ;; Let Org open all OpenDocument files using system-registered app
247 (add-to-list 'org-file-apps
248 (cons (concat "\\." (car desc) "\\'") 'system))
249 ;; Let Emacs open all OpenDocument files in archive mode
250 (add-to-list 'auto-mode-alist
251 (cons (concat "\\." (car desc) "\\'") 'archive-mode)))
252 org-odt-file-extensions)
254 ;; register the odt exporter with the pre-processor
255 (add-to-list 'org-export-backends 'odt)
257 ;; register the odt exporter with org-lparse library
258 (org-lparse-register-backend 'odt)
260 (defun org-odt-unload-function ()
261 (org-lparse-unregister-backend 'odt)
262 (remove-hook 'org-export-preprocess-after-blockquote-hook
263 'org-export-odt-preprocess-latex-fragments)
264 nil)
266 (defcustom org-export-odt-content-template-file nil
267 "Template file for \"content.xml\".
268 The exporter embeds the exported content just before
269 \"</office:text>\" element.
271 If unspecified, the file named \"OrgOdtContentTemplate.xml\"
272 under `org-odt-styles-dir' is used."
273 :type 'file
274 :group 'org-export-odt)
276 (defcustom org-export-odt-styles-file nil
277 "Default styles file for use with ODT export.
278 Valid values are one of:
279 1. nil
280 2. path to a styles.xml file
281 3. path to a *.odt or a *.ott file
282 4. list of the form (ODT-OR-OTT-FILE (FILE-MEMBER-1 FILE-MEMBER-2
283 ...))
285 In case of option 1, an in-built styles.xml is used. See
286 `org-odt-styles-dir' for more information.
288 In case of option 3, the specified file is unzipped and the
289 styles.xml embedded therein is used.
291 In case of option 4, the specified ODT-OR-OTT-FILE is unzipped
292 and FILE-MEMBER-1, FILE-MEMBER-2 etc are copied in to the
293 generated odt file. Use relative path for specifying the
294 FILE-MEMBERS. styles.xml must be specified as one of the
295 FILE-MEMBERS.
297 Use options 1, 2 or 3 only if styles.xml alone suffices for
298 achieving the desired formatting. Use option 4, if the styles.xml
299 references additional files like header and footer images for
300 achieving the desired formatting.
302 Use \"#+ODT_STYLES_FILE: ...\" directive to set this variable on
303 a per-file basis. For example,
305 #+ODT_STYLES_FILE: \"/path/to/styles.xml\" or
306 #+ODT_STYLES_FILE: (\"/path/to/file.ott\" (\"styles.xml\" \"image/hdr.png\"))."
307 :group 'org-export-odt
308 :type
309 '(choice
310 (const :tag "Factory settings" nil)
311 (file :must-match t :tag "styles.xml")
312 (file :must-match t :tag "ODT or OTT file")
313 (list :tag "ODT or OTT file + Members"
314 (file :must-match t :tag "ODF Text or Text Template file")
315 (cons :tag "Members"
316 (file :tag " Member" "styles.xml")
317 (repeat (file :tag "Member"))))))
319 (eval-after-load 'org-exp
320 '(add-to-list 'org-export-inbuffer-options-extra
321 '("ODT_STYLES_FILE" :odt-styles-file)))
323 (defconst org-export-odt-tmpdir-prefix "%s-")
324 (defconst org-export-odt-bookmark-prefix "OrgXref.")
326 (defvar org-export-odt-embed-images t
327 "Should the images be copied in to the odt file or just linked?")
329 (defvar org-export-odt-inline-images 'maybe) ; counterpart of
330 ; `org-export-html-inline-images'
332 (defcustom org-export-odt-inline-image-extensions
333 '("png" "jpeg" "jpg" "gif")
334 "Extensions of image files that can be inlined into HTML."
335 :type '(repeat (string :tag "Extension"))
336 :group 'org-export-odt)
338 (defcustom org-export-odt-pixels-per-inch display-pixels-per-inch
339 ;; FIXME add docstring
341 :type 'float
342 :group 'org-export-odt)
344 (defcustom org-export-odt-create-custom-styles-for-srcblocks t
345 "Whether custom styles for colorized source blocks be automatically created.
346 When this option is turned on, the exporter creates custom styles
347 for source blocks based on the advice of `htmlfontify'. Creation
348 of custom styles happen as part of `org-odt-hfy-face-to-css'.
350 When this option is turned off exporter does not create such
351 styles.
353 Use the latter option if you do not want the custom styles to be
354 based on your current display settings. It is necessary that the
355 styles.xml already contains needed styles for colorizing to work.
357 This variable is effective only if
358 `org-export-odt-fontify-srcblocks' is turned on."
359 :group 'org-export-odt
360 :type 'boolean)
362 (defvar org-export-odt-default-org-styles-alist
363 '((paragraph . ((default . "Text_20_body")
364 (fixedwidth . "OrgFixedWidthBlock")
365 (verse . "OrgVerse")
366 (quote . "Quotations")
367 (blockquote . "Quotations")
368 (center . "OrgCenter")
369 (left . "OrgLeft")
370 (right . "OrgRight")
371 (title . "OrgTitle")
372 (subtitle . "OrgSubtitle")
373 (footnote . "Footnote")
374 (src . "OrgSrcBlock")
375 (illustration . "Illustration")
376 (table . "Table")
377 (definition-term . "Text_20_body_20_bold")
378 (horizontal-line . "Horizontal_20_Line")))
379 (character . ((bold . "Bold")
380 (emphasis . "Emphasis")
381 (code . "OrgCode")
382 (verbatim . "OrgCode")
383 (strike . "Strikethrough")
384 (underline . "Underline")
385 (subscript . "OrgSubscript")
386 (superscript . "OrgSuperscript")))
387 (list . ((ordered . "OrgNumberedList")
388 (unordered . "OrgBulletedList")
389 (description . "OrgDescriptionList"))))
390 "Default styles for various entities.")
392 (defvar org-export-odt-org-styles-alist org-export-odt-default-org-styles-alist)
393 (defun org-odt-get-style-name-for-entity (category &optional entity)
394 (let ((entity (or entity 'default)))
396 (cdr (assoc entity (cdr (assoc category
397 org-export-odt-org-styles-alist))))
398 (cdr (assoc entity (cdr (assoc category
399 org-export-odt-default-org-styles-alist))))
400 (error "Cannot determine style name for entity %s of type %s"
401 entity category))))
403 (defcustom org-export-odt-preferred-output-format nil
404 "Automatically post-process to this format after exporting to \"odt\".
405 Interactive commands `org-export-as-odt' and
406 `org-export-as-odt-and-open' export first to \"odt\" format and
407 then use `org-export-odt-convert-process' to convert the
408 resulting document to this format. During customization of this
409 variable, the list of valid values are populated based on
410 `org-export-odt-convert-capabilities'."
411 :group 'org-export-odt
412 :type '(choice :convert-widget
413 (lambda (w)
414 (apply 'widget-convert (widget-type w)
415 (eval (car (widget-get w :args)))))
416 `((const :tag "None" nil)
417 ,@(mapcar (lambda (c)
418 `(const :tag ,c ,c))
419 (org-lparse-reachable-formats "odt")))))
421 ;;;###autoload
422 (defun org-export-as-odt-and-open (arg)
423 "Export the outline as ODT and immediately open it with a browser.
424 If there is an active region, export only the region.
425 The prefix ARG specifies how many levels of the outline should become
426 headlines. The default is 3. Lower levels will become bulleted lists."
427 (interactive "P")
428 (org-lparse-and-open
429 (or org-export-odt-preferred-output-format "odt") "odt" arg))
431 ;;;###autoload
432 (defun org-export-as-odt-batch ()
433 "Call the function `org-lparse-batch'.
434 This function can be used in batch processing as:
435 emacs --batch
436 --load=$HOME/lib/emacs/org.el
437 --eval \"(setq org-export-headline-levels 2)\"
438 --visit=MyFile --funcall org-export-as-odt-batch"
439 (org-lparse-batch "odt"))
441 ;;;###autoload
442 (defun org-export-as-odt-to-buffer (arg)
443 "Call `org-lparse-odt` with output to a temporary buffer.
444 No file is created. The prefix ARG is passed through to `org-lparse-to-buffer'."
445 (interactive "P")
446 (org-lparse-to-buffer "odt" arg))
448 ;;;###autoload
449 (defun org-replace-region-by-odt (beg end)
450 "Assume the current region has org-mode syntax, and convert it to ODT.
451 This can be used in any buffer. For example, you could write an
452 itemized list in org-mode syntax in an ODT buffer and then use this
453 command to convert it."
454 (interactive "r")
455 (org-replace-region-by "odt" beg end))
457 ;;;###autoload
458 (defun org-export-region-as-odt (beg end &optional body-only buffer)
459 "Convert region from BEG to END in org-mode buffer to ODT.
460 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
461 contents, and only produce the region of converted text, useful for
462 cut-and-paste operations.
463 If BUFFER is a buffer or a string, use/create that buffer as a target
464 of the converted ODT. If BUFFER is the symbol `string', return the
465 produced ODT as a string and leave not buffer behind. For example,
466 a Lisp program could call this function in the following way:
468 (setq odt (org-export-region-as-odt beg end t 'string))
470 When called interactively, the output buffer is selected, and shown
471 in a window. A non-interactive call will only return the buffer."
472 (interactive "r\nP")
473 (org-lparse-region "odt" beg end body-only buffer))
475 ;;; org-export-as-odt
476 ;;;###autoload
477 (defun org-export-as-odt (arg &optional hidden ext-plist
478 to-buffer body-only pub-dir)
479 "Export the outline as a OpenDocumentText file.
480 If there is an active region, export only the region. The prefix
481 ARG specifies how many levels of the outline should become
482 headlines. The default is 3. Lower levels will become bulleted
483 lists. HIDDEN is obsolete and does nothing.
484 EXT-PLIST is a property list with external parameters overriding
485 org-mode's default settings, but still inferior to file-local
486 settings. When TO-BUFFER is non-nil, create a buffer with that
487 name and export to that buffer. If TO-BUFFER is the symbol
488 `string', don't leave any buffer behind but just return the
489 resulting XML as a string. When BODY-ONLY is set, don't produce
490 the file header and footer, simply return the content of
491 <body>...</body>, without even the body tags themselves. When
492 PUB-DIR is set, use this as the publishing directory."
493 (interactive "P")
494 (org-lparse (or org-export-odt-preferred-output-format "odt")
495 "odt" arg hidden ext-plist to-buffer body-only pub-dir))
497 (defvar org-odt-entity-control-callbacks-alist
498 `((EXPORT
499 . (org-odt-begin-export org-odt-end-export))
500 (DOCUMENT-CONTENT
501 . (org-odt-begin-document-content org-odt-end-document-content))
502 (DOCUMENT-BODY
503 . (org-odt-begin-document-body org-odt-end-document-body))
504 (TOC
505 . (org-odt-begin-toc org-odt-end-toc))
506 (ENVIRONMENT
507 . (org-odt-begin-environment org-odt-end-environment))
508 (FOOTNOTE-DEFINITION
509 . (org-odt-begin-footnote-definition org-odt-end-footnote-definition))
510 (TABLE
511 . (org-odt-begin-table org-odt-end-table))
512 (TABLE-ROWGROUP
513 . (org-odt-begin-table-rowgroup org-odt-end-table-rowgroup))
514 (LIST
515 . (org-odt-begin-list org-odt-end-list))
516 (LIST-ITEM
517 . (org-odt-begin-list-item org-odt-end-list-item))
518 (OUTLINE
519 . (org-odt-begin-outline org-odt-end-outline))
520 (OUTLINE-TEXT
521 . (org-odt-begin-outline-text org-odt-end-outline-text))
522 (PARAGRAPH
523 . (org-odt-begin-paragraph org-odt-end-paragraph)))
526 (defvar org-odt-entity-format-callbacks-alist
527 `((EXTRA-TARGETS . org-lparse-format-extra-targets)
528 (ORG-TAGS . org-lparse-format-org-tags)
529 (SECTION-NUMBER . org-lparse-format-section-number)
530 (HEADLINE . org-odt-format-headline)
531 (TOC-ENTRY . org-odt-format-toc-entry)
532 (TOC-ITEM . org-odt-format-toc-item)
533 (TAGS . org-odt-format-tags)
534 (SPACES . org-odt-format-spaces)
535 (TABS . org-odt-format-tabs)
536 (LINE-BREAK . org-odt-format-line-break)
537 (FONTIFY . org-odt-format-fontify)
538 (TODO . org-lparse-format-todo)
539 (LINK . org-odt-format-link)
540 (INLINE-IMAGE . org-odt-format-inline-image)
541 (ORG-LINK . org-odt-format-org-link)
542 (HEADING . org-odt-format-heading)
543 (ANCHOR . org-odt-format-anchor)
544 (TABLE . org-lparse-format-table)
545 (TABLE-ROW . org-odt-format-table-row)
546 (TABLE-CELL . org-odt-format-table-cell)
547 (FOOTNOTES-SECTION . ignore)
548 (FOOTNOTE-REFERENCE . org-odt-format-footnote-reference)
549 (HORIZONTAL-LINE . org-odt-format-horizontal-line)
550 (COMMENT . org-odt-format-comment)
551 (LINE . org-odt-format-line)
552 (ORG-ENTITY . org-odt-format-org-entity))
555 ;;;_. callbacks
556 ;;;_. control callbacks
557 ;;;_ , document body
558 (defun org-odt-begin-office-body ()
559 ;; automatic styles
560 (insert-file-contents
561 (or org-export-odt-content-template-file
562 (expand-file-name "OrgOdtContentTemplate.xml"
563 org-odt-styles-dir)))
564 (goto-char (point-min))
565 (re-search-forward "</office:text>" nil nil)
566 (delete-region (match-beginning 0) (point-max)))
568 ;; Following variable is let bound when `org-do-lparse' is in
569 ;; progress. See org-html.el.
570 (defvar org-lparse-toc)
571 (defun org-odt-format-toc ()
572 (if (not org-lparse-toc) "" (concat "\n" org-lparse-toc "\n")))
574 (defun org-odt-format-preamble (opt-plist)
575 (let* ((title (plist-get opt-plist :title))
576 (author (plist-get opt-plist :author))
577 (date (plist-get opt-plist :date))
578 (iso-date (org-odt-format-date date))
579 (date (org-odt-format-date date "%d %b %Y"))
580 (email (plist-get opt-plist :email))
581 ;; switch on or off above vars based on user settings
582 (author (and (plist-get opt-plist :author-info) (or author email)))
583 (email (and (plist-get opt-plist :email-info) email))
584 (date (and (plist-get opt-plist :time-stamp-file) date)))
585 (concat
586 ;; title
587 (when title
588 (concat
589 (org-odt-format-stylized-paragraph
590 'title (org-odt-format-tags
591 '("<text:title>" . "</text:title>") title))
592 ;; separator
593 "<text:p text:style-name=\"OrgTitle\"/>"))
594 (cond
595 ((and author (not email))
596 ;; author only
597 (concat
598 (org-odt-format-stylized-paragraph
599 'subtitle
600 (org-odt-format-tags
601 '("<text:initial-creator>" . "</text:initial-creator>")
602 author))
603 ;; separator
604 "<text:p text:style-name=\"OrgSubtitle\"/>"))
605 ((and author email)
606 ;; author and email
607 (concat
608 (org-odt-format-stylized-paragraph
609 'subtitle
610 (org-odt-format-link
611 (org-odt-format-tags
612 '("<text:initial-creator>" . "</text:initial-creator>")
613 author) (concat "mailto:" email)))
614 ;; separator
615 "<text:p text:style-name=\"OrgSubtitle\"/>")))
616 ;; date
617 (when date
618 (concat
619 (org-odt-format-stylized-paragraph
620 'subtitle
621 (org-odt-format-tags
622 '("<text:date style:data-style-name=\"%s\" text:date-value=\"%s\">"
623 . "</text:date>") date "N75" iso-date))
624 ;; separator
625 "<text:p text:style-name=\"OrgSubtitle\"/>")))))
627 (defun org-odt-begin-document-body (opt-plist)
628 (org-odt-begin-office-body)
629 (insert (org-odt-format-preamble opt-plist))
630 (setq org-lparse-dyn-first-heading-pos (point)))
632 (defvar org-lparse-body-only) ; let bound during org-do-lparse
633 (defvar org-lparse-to-buffer) ; let bound during org-do-lparse
634 (defun org-odt-end-document-body (opt-plist)
635 (unless org-lparse-body-only
636 (org-lparse-insert-tag "</office:text>")
637 (org-lparse-insert-tag "</office:body>")))
639 (defun org-odt-begin-document-content (opt-plist)
640 (ignore))
642 (defun org-odt-end-document-content ()
643 (org-lparse-insert-tag "</office:document-content>"))
645 (defun org-odt-begin-outline (level1 snumber title tags
646 target extra-targets class)
647 (org-lparse-insert
648 'HEADING (org-lparse-format
649 'HEADLINE title extra-targets tags snumber level1)
650 level1 target))
652 (defun org-odt-end-outline ()
653 (ignore))
655 (defun org-odt-begin-outline-text (level1 snumber class)
656 (ignore))
658 (defun org-odt-end-outline-text ()
659 (ignore))
661 (defun org-odt-begin-section (style &optional name)
662 (let ((default-name (car (org-odt-add-automatic-style "Section"))))
663 (org-lparse-insert-tag
664 "<text:section text:style-name=\"%s\" text:name=\"%s\">"
665 style (or name default-name))))
667 (defun org-odt-end-section ()
668 (org-lparse-insert-tag "</text:section>"))
670 (defun org-odt-begin-paragraph (&optional style)
671 (org-lparse-insert-tag
672 "<text:p%s>" (org-odt-get-extra-attrs-for-paragraph-style style)))
674 (defun org-odt-end-paragraph ()
675 (org-lparse-insert-tag "</text:p>"))
677 (defun org-odt-get-extra-attrs-for-paragraph-style (style)
678 (let (style-name)
679 (setq style-name
680 (cond
681 ((stringp style) style)
682 ((symbolp style) (org-odt-get-style-name-for-entity
683 'paragraph style))))
684 (unless style-name
685 (error "Don't know how to handle paragraph style %s" style))
686 (format " text:style-name=\"%s\"" style-name)))
688 (defun org-odt-format-stylized-paragraph (style text)
689 (org-odt-format-tags
690 '("<text:p%s>" . "</text:p>") text
691 (org-odt-get-extra-attrs-for-paragraph-style style)))
693 (defvar org-lparse-opt-plist) ; bound during org-do-lparse
694 (defun org-odt-format-author (&optional author)
695 (when (setq author (or author (plist-get org-lparse-opt-plist :author)))
696 (org-odt-format-tags '("<dc:creator>" . "</dc:creator>") author)))
698 (defun org-odt-format-date (&optional org-ts fmt)
699 (save-match-data
700 (let* ((time
701 (and (stringp org-ts)
702 (string-match org-ts-regexp0 org-ts)
703 (apply 'encode-time
704 (org-fix-decoded-time
705 (org-parse-time-string (match-string 0 org-ts) t)))))
706 date)
707 (cond
708 (fmt (format-time-string fmt time))
709 (t (setq date (format-time-string "%Y-%m-%dT%H:%M:%S%z" time))
710 (format "%s:%s" (substring date 0 -2) (substring date -2)))))))
712 (defun org-odt-begin-annotation (&optional author date)
713 (org-lparse-insert-tag "<office:annotation>")
714 (when (setq author (org-odt-format-author author))
715 (insert author))
716 (insert (org-odt-format-tags
717 '("<dc:date>" . "</dc:date>")
718 (org-odt-format-date
719 (or date (plist-get org-lparse-opt-plist :date)))))
720 (org-lparse-begin-paragraph))
722 (defun org-odt-end-annotation ()
723 (org-lparse-insert-tag "</office:annotation>"))
725 (defun org-odt-begin-environment (style env-options-plist)
726 (case style
727 (annotation
728 (org-lparse-stash-save-paragraph-state)
729 (org-odt-begin-annotation (plist-get env-options-plist 'author)
730 (plist-get env-options-plist 'date)))
731 ((blockquote verse center quote)
732 (org-lparse-begin-paragraph style)
733 (list))
734 ((fixedwidth native)
735 (org-lparse-end-paragraph)
736 (list))
737 (t (error "Unknown environment %s" style))))
739 (defun org-odt-end-environment (style env-options-plist)
740 (case style
741 (annotation
742 (org-lparse-end-paragraph)
743 (org-odt-end-annotation)
744 (org-lparse-stash-pop-paragraph-state))
745 ((blockquote verse center quote)
746 (org-lparse-end-paragraph)
747 (list))
748 ((fixedwidth native)
749 (org-lparse-begin-paragraph)
750 (list))
751 (t (error "Unknown environment %s" style))))
753 (defvar org-lparse-list-stack) ; dynamically bound in org-do-lparse
754 (defvar org-odt-list-stack-stashed)
755 (defun org-odt-begin-list (ltype)
756 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
757 ltype))
758 (let* ((style-name (org-odt-get-style-name-for-entity 'list ltype))
759 (extra (concat (if (or org-lparse-list-table-p
760 (and (= 1 (length org-lparse-list-stack))
761 (null org-odt-list-stack-stashed)))
762 " text:continue-numbering=\"false\""
763 " text:continue-numbering=\"true\"")
764 (when style-name
765 (format " text:style-name=\"%s\"" style-name)))))
766 (case ltype
767 ((ordered unordered description)
768 (org-lparse-end-paragraph)
769 (org-lparse-insert-tag "<text:list%s>" extra))
770 (t (error "Unknown list type: %s" ltype)))))
772 (defun org-odt-end-list (ltype)
773 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
774 ltype))
775 (if ltype
776 (org-lparse-insert-tag "</text:list>")
777 (error "Unknown list type: %s" ltype)))
779 (defun org-odt-begin-list-item (ltype &optional arg headline)
780 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
781 ltype))
782 (case ltype
783 (ordered
784 (assert (not headline) t)
785 (let* ((counter arg) (extra ""))
786 (org-lparse-insert-tag (if (= (length org-lparse-list-stack)
787 (length org-odt-list-stack-stashed))
788 "<text:list-header>" "<text:list-item>"))
789 (org-lparse-begin-paragraph)))
790 (unordered
791 (let* ((id arg) (extra ""))
792 (org-lparse-insert-tag (if (= (length org-lparse-list-stack)
793 (length org-odt-list-stack-stashed))
794 "<text:list-header>" "<text:list-item>"))
795 (org-lparse-begin-paragraph)
796 (insert (if headline (org-odt-format-target headline id)
797 (org-odt-format-bookmark "" id)))))
798 (description
799 (assert (not headline) t)
800 (let ((term (or arg "(no term)")))
801 (insert
802 (org-odt-format-tags
803 '("<text:list-item>" . "</text:list-item>")
804 (org-odt-format-stylized-paragraph 'definition-term term)))
805 (org-lparse-begin-list-item 'unordered)
806 (org-lparse-begin-list 'description)
807 (org-lparse-begin-list-item 'unordered)))
808 (t (error "Unknown list type"))))
810 (defun org-odt-end-list-item (ltype)
811 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
812 ltype))
813 (case ltype
814 ((ordered unordered)
815 (org-lparse-insert-tag (if (= (length org-lparse-list-stack)
816 (length org-odt-list-stack-stashed))
817 (prog1 "</text:list-header>"
818 (setq org-odt-list-stack-stashed nil))
819 "</text:list-item>")))
820 (description
821 (org-lparse-end-list-item-1)
822 (org-lparse-end-list 'description)
823 (org-lparse-end-list-item-1))
824 (t (error "Unknown list type"))))
826 (defun org-odt-discontinue-list ()
827 (let ((stashed-stack org-lparse-list-stack))
828 (loop for list-type in stashed-stack
829 do (org-lparse-end-list-item-1 list-type)
830 (org-lparse-end-list list-type))
831 (setq org-odt-list-stack-stashed stashed-stack)))
833 (defun org-odt-continue-list ()
834 (setq org-odt-list-stack-stashed (nreverse org-odt-list-stack-stashed))
835 (loop for list-type in org-odt-list-stack-stashed
836 do (org-lparse-begin-list list-type)
837 (org-lparse-begin-list-item list-type)))
839 ;; Following variables are let bound when table emission is in
840 ;; progress. See org-lparse.el.
841 (defvar org-lparse-table-begin-marker)
842 (defvar org-lparse-table-ncols)
843 (defvar org-lparse-table-rowgrp-open)
844 (defvar org-lparse-table-rownum)
845 (defvar org-lparse-table-cur-rowgrp-is-hdr)
846 (defvar org-lparse-table-is-styled)
847 (defvar org-lparse-table-rowgrp-info)
848 (defvar org-lparse-table-colalign-vector)
850 (defvar org-odt-table-style nil
851 "Table style specified by \"#+ATTR_ODT: <style-name>\" line.
852 This is set during `org-odt-begin-table'.")
854 (defvar org-odt-table-style-spec nil
855 "Entry for `org-odt-table-style' in `org-export-odt-table-styles'.")
857 (defcustom org-export-odt-table-styles
858 '(("OrgEquation" "OrgEquation"
859 ((use-first-column-styles . t)
860 (use-last-column-styles . t))))
861 "Specify how Table Styles should be derived from a Table Template.
862 This is a list where each element is of the
863 form (TABLE-STYLE-NAME TABLE-TEMPLATE-NAME TABLE-CELL-OPTIONS).
865 TABLE-STYLE-NAME is the style associated with the table through
866 `org-odt-table-style'.
868 TABLE-TEMPLATE-NAME is a set of - upto 9 - automatic
869 TABLE-CELL-STYLE-NAMEs and PARAGRAPH-STYLE-NAMEs (as defined
870 below) that is included in
871 `org-export-odt-content-template-file'.
873 TABLE-CELL-STYLE-NAME := TABLE-TEMPLATE-NAME + TABLE-CELL-TYPE +
874 \"TableCell\"
875 PARAGRAPH-STYLE-NAME := TABLE-TEMPLATE-NAME + TABLE-CELL-TYPE +
876 \"TableParagraph\"
877 TABLE-CELL-TYPE := \"FirstRow\" | \"LastColumn\" |
878 \"FirstRow\" | \"LastRow\" |
879 \"EvenRow\" | \"OddRow\" |
880 \"EvenColumn\" | \"OddColumn\" | \"\"
881 where \"+\" above denotes string concatenation.
883 TABLE-CELL-OPTIONS is an alist where each element is of the
884 form (TABLE-CELL-STYLE-SELECTOR . ON-OR-OFF).
885 TABLE-CELL-STYLE-SELECTOR := `use-first-row-styles' |
886 `use-last-row-styles' |
887 `use-first-column-styles' |
888 `use-last-column-styles' |
889 `use-banding-rows-styles' |
890 `use-banding-columns-styles' |
891 `use-first-row-styles'
892 ON-OR-OFF := `t' | `nil'
894 For example, with the following configuration
896 \(setq org-export-odt-table-styles
897 '\(\(\"TableWithHeaderRowsAndColumns\" \"Custom\"
898 \(\(use-first-row-styles . t\)
899 \(use-first-column-styles . t\)\)\)
900 \(\"TableWithHeaderColumns\" \"Custom\"
901 \(\(use-first-column-styles . t\)\)\)\)\)
903 1. A table associated with \"TableWithHeaderRowsAndColumns\"
904 style will use the following table-cell styles -
905 \"CustomFirstRowTableCell\", \"CustomFirstColumnTableCell\",
906 \"CustomTableCell\" and the following paragraph styles
907 \"CustomFirstRowTableParagraph\",
908 \"CustomFirstColumnTableParagraph\", \"CustomTableParagraph\"
909 as appropriate.
911 2. A table associated with \"TableWithHeaderColumns\" style will
912 use the following table-cell styles -
913 \"CustomFirstColumnTableCell\", \"CustomTableCell\" and the
914 following paragraph styles
915 \"CustomFirstColumnTableParagraph\", \"CustomTableParagraph\"
916 as appropriate..
918 Note that TABLE-TEMPLATE-NAME corresponds to the
919 \"<table:table-template>\" elements contained within
920 \"<office:styles>\". The entries (TABLE-STYLE-NAME
921 TABLE-TEMPLATE-NAME TABLE-CELL-OPTIONS) correspond to
922 \"table:template-name\" and \"table:use-first-row-styles\" etc
923 attributes of \"<table:table>\" element. Refer ODF-1.2
924 specification for more information. Also consult the
925 implementation filed under `org-odt-get-table-cell-styles'.
927 The TABLE-STYLE-NAME \"OrgEquation\" is used internally for
928 formatting of numbered display equations. Do not delete this
929 style from the list."
930 :group 'org-export-odt
931 :type '(choice
932 (const :tag "None" nil)
933 (repeat :tag "Table Styles"
934 (list :tag "Table Style Specification"
935 (string :tag "Table Style Name")
936 (string :tag "Table Template Name")
937 (alist :options (use-first-row-styles
938 use-last-row-styles
939 use-first-column-styles
940 use-last-column-styles
941 use-banding-rows-styles
942 use-banding-columns-styles)
943 :key-type symbol
944 :value-type (const :tag "True" t))))))
946 (defvar org-odt-table-style-format
948 <style:style style:name=\"%s\" style:family=\"table\">
949 <style:table-properties style:rel-width=\"%d%%\" fo:margin-top=\"0cm\" fo:margin-bottom=\"0.20cm\" table:align=\"center\"/>
950 </style:style>
952 "Template for auto-generated Table styles.")
954 (defvar org-odt-automatic-styles '()
955 "Registry of automatic styles for various OBJECT-TYPEs.
956 The variable has the following form:
957 \(\(OBJECT-TYPE-A
958 \(\(OBJECT-NAME-A.1 OBJECT-PROPS-A.1\)
959 \(OBJECT-NAME-A.2 OBJECT-PROPS-A.2\) ...\)\)
960 \(OBJECT-TYPE-B
961 \(\(OBJECT-NAME-B.1 OBJECT-PROPS-B.1\)
962 \(OBJECT-NAME-B.2 OBJECT-PROPS-B.2\) ...\)\)
963 ...\).
965 OBJECT-TYPEs could be \"Section\", \"Table\", \"Figure\" etc.
966 OBJECT-PROPS is (typically) a plist created by passing
967 \"#+ATTR_ODT: \" option to `org-lparse-get-block-params'.
969 Use `org-odt-add-automatic-style' to add update this variable.'")
971 (defvar org-odt-object-counters nil
972 "Running counters for various OBJECT-TYPEs.
973 Use this to generate automatic names and style-names. See
974 `org-odt-add-automatic-style'.")
976 (defun org-odt-write-automatic-styles ()
977 "Write automatic styles to \"content.xml\"."
978 (with-current-buffer
979 (find-file-noselect (expand-file-name "content.xml") t)
980 ;; position the cursor
981 (goto-char (point-min))
982 (re-search-forward " </office:automatic-styles>" nil t)
983 (goto-char (match-beginning 0))
984 ;; write automatic table styles
985 (loop for (style-name props) in
986 (plist-get org-odt-automatic-styles 'Table) do
987 (when (setq props (or (plist-get props :rel-width) 96))
988 (insert (format org-odt-table-style-format style-name props))))))
990 (defun org-odt-add-automatic-style (object-type &optional object-props)
991 "Create an automatic style of type OBJECT-TYPE with param OBJECT-PROPS.
992 OBJECT-PROPS is (typically) a plist created by passing
993 \"#+ATTR_ODT: \" option of the object in question to
994 `org-lparse-get-block-params'.
996 Use `org-odt-object-counters' to generate an automatic
997 OBJECT-NAME and STYLE-NAME. If OBJECT-PROPS is non-nil, add a
998 new entry in `org-odt-automatic-styles'. Return (OBJECT-NAME
999 . STYLE-NAME)."
1000 (assert (stringp object-type))
1001 (let* ((object (intern object-type))
1002 (seqvar object)
1003 (seqno (1+ (or (plist-get org-odt-object-counters seqvar) 0)))
1004 (object-name (format "%s%d" object-type seqno)) style-name)
1005 (setq org-odt-object-counters
1006 (plist-put org-odt-object-counters seqvar seqno))
1007 (when object-props
1008 (setq style-name (format "Org%s" object-name))
1009 (setq org-odt-automatic-styles
1010 (plist-put org-odt-automatic-styles object
1011 (append (list (list style-name object-props))
1012 (plist-get org-odt-automatic-styles object)))))
1013 (cons object-name style-name)))
1015 (defvar org-odt-table-indentedp nil)
1016 (defun org-odt-begin-table (caption label attributes)
1017 (setq org-odt-table-indentedp (not (null org-lparse-list-stack)))
1018 (when org-odt-table-indentedp
1019 ;; Within the Org file, the table is appearing within a list item.
1020 ;; OpenDocument doesn't allow table to appear within list items.
1021 ;; Temporarily terminate the list, emit the table and then
1022 ;; re-continue the list.
1023 (org-odt-discontinue-list)
1024 ;; Put the Table in an indented section.
1025 (let ((level (length org-odt-list-stack-stashed)))
1026 (org-odt-begin-section (format "OrgIndentedSection-Level-%d" level))))
1027 (setq attributes (org-lparse-get-block-params attributes))
1028 (setq org-odt-table-style (plist-get attributes :style))
1029 (setq org-odt-table-style-spec
1030 (assoc org-odt-table-style org-export-odt-table-styles))
1031 (insert
1032 (org-odt-format-stylized-paragraph
1033 'table (org-odt-format-entity-caption label caption "__Table__")))
1034 (let ((name-and-style (org-odt-add-automatic-style "Table" attributes)))
1035 (org-lparse-insert-tag
1036 "<table:table table:name=\"%s\" table:style-name=\"%s\">"
1037 (car name-and-style) (or (nth 1 org-odt-table-style-spec)
1038 (cdr name-and-style) "OrgTable")))
1039 (setq org-lparse-table-begin-marker (point)))
1041 (defvar org-lparse-table-colalign-info)
1042 (defun org-odt-end-table ()
1043 (goto-char org-lparse-table-begin-marker)
1044 (loop for level from 0 below org-lparse-table-ncols
1045 do (let* ((col-cookie (and org-lparse-table-is-styled
1046 (cdr (assoc (1+ level)
1047 org-lparse-table-colalign-info))))
1048 (extra-columns (or (nth 1 col-cookie) 0)))
1049 (dotimes (i (1+ extra-columns))
1050 (insert
1051 (org-odt-format-tags
1052 "<table:table-column table:style-name=\"%sColumn\"/>"
1053 "" (or (nth 1 org-odt-table-style-spec) "OrgTable"))))
1054 (insert "\n")))
1055 ;; fill style attributes for table cells
1056 (when org-lparse-table-is-styled
1057 (while (re-search-forward "@@\\(table-cell:p\\|table-cell:style-name\\)@@\\([0-9]+\\)@@\\([0-9]+\\)@@" nil t)
1058 (let* ((spec (match-string 1))
1059 (r (string-to-number (match-string 2)))
1060 (c (string-to-number (match-string 3)))
1061 (cell-styles (org-odt-get-table-cell-styles
1062 r c org-odt-table-style-spec))
1063 (table-cell-style (car cell-styles))
1064 (table-cell-paragraph-style (cdr cell-styles)))
1065 (cond
1066 ((equal spec "table-cell:p")
1067 (replace-match table-cell-paragraph-style t t))
1068 ((equal spec "table-cell:style-name")
1069 (replace-match table-cell-style t t))))))
1070 (goto-char (point-max))
1071 (org-lparse-insert-tag "</table:table>")
1072 (when org-odt-table-indentedp
1073 (org-odt-end-section)
1074 (org-odt-continue-list)))
1076 (defun org-odt-begin-table-rowgroup (&optional is-header-row)
1077 (when org-lparse-table-rowgrp-open
1078 (org-lparse-end 'TABLE-ROWGROUP))
1079 (org-lparse-insert-tag (if is-header-row
1080 "<table:table-header-rows>"
1081 "<table:table-rows>"))
1082 (setq org-lparse-table-rowgrp-open t)
1083 (setq org-lparse-table-cur-rowgrp-is-hdr is-header-row))
1085 (defun org-odt-end-table-rowgroup ()
1086 (when org-lparse-table-rowgrp-open
1087 (setq org-lparse-table-rowgrp-open nil)
1088 (org-lparse-insert-tag
1089 (if org-lparse-table-cur-rowgrp-is-hdr
1090 "</table:table-header-rows>" "</table:table-rows>"))))
1092 (defun org-odt-format-table-row (row)
1093 (org-odt-format-tags
1094 '("<table:table-row>" . "</table:table-row>") row))
1096 (defun org-odt-get-table-cell-styles (r c &optional style-spec)
1097 "Retrieve styles applicable to a table cell.
1098 R and C are (zero-based) row and column numbers of the table
1099 cell. STYLE-SPEC is an entry in `org-export-odt-table-styles'
1100 applicable to the current table. It is `nil' if the table is not
1101 associated with any style attributes.
1103 Return a cons of (TABLE-CELL-STYLE-NAME . PARAGRAPH-STYLE-NAME).
1105 When STYLE-SPEC is nil, style the table cell the conventional way
1106 - choose cell borders based on row and column groupings and
1107 choose paragraph alignment based on `org-col-cookies' text
1108 property. See also
1109 `org-odt-get-paragraph-style-cookie-for-table-cell'.
1111 When STYLE-SPEC is non-nil, ignore the above cookie and return
1112 styles congruent with the ODF-1.2 specification."
1113 (cond
1114 (style-spec
1116 ;; LibreOffice - particularly the Writer - honors neither table
1117 ;; templates nor custom table-cell styles. Inorder to retain
1118 ;; inter-operability with LibreOffice, only automatic styles are
1119 ;; used for styling of table-cells. The current implementation is
1120 ;; congruent with ODF-1.2 specification and hence is
1121 ;; future-compatible.
1123 ;; Additional Note: LibreOffice's AutoFormat facility for tables -
1124 ;; which recognizes as many as 16 different cell types - is much
1125 ;; richer. Unfortunately it is NOT amenable to easy configuration
1126 ;; by hand.
1128 (let* ((template-name (nth 1 style-spec))
1129 (cell-style-selectors (nth 2 style-spec))
1130 (cell-type
1131 (cond
1132 ((and (cdr (assoc 'use-first-column-styles cell-style-selectors))
1133 (= c 0)) "FirstColumn")
1134 ((and (cdr (assoc 'use-last-column-styles cell-style-selectors))
1135 (= c (1- org-lparse-table-ncols))) "LastColumn")
1136 ((and (cdr (assoc 'use-first-row-styles cell-style-selectors))
1137 (= r 0)) "FirstRow")
1138 ((and (cdr (assoc 'use-last-row-styles cell-style-selectors))
1139 (= r org-lparse-table-rownum))
1140 "LastRow")
1141 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
1142 (= (% r 2) 1)) "EvenRow")
1143 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
1144 (= (% r 2) 0)) "OddRow")
1145 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
1146 (= (% c 2) 1)) "EvenColumn")
1147 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
1148 (= (% c 2) 0)) "OddColumn")
1149 (t ""))))
1150 (cons
1151 (concat template-name cell-type "TableCell")
1152 (concat template-name cell-type "TableParagraph"))))
1154 (cons
1155 (concat
1156 "OrgTblCell"
1157 (cond
1158 ((= r 0) "T")
1159 ((eq (cdr (assoc r org-lparse-table-rowgrp-info)) :start) "T")
1160 (t ""))
1161 (when (= r org-lparse-table-rownum) "B")
1162 (cond
1163 ((= c 0) "")
1164 ((or (memq (nth c org-table-colgroup-info) '(:start :startend))
1165 (memq (nth (1- c) org-table-colgroup-info) '(:end :startend))) "L")
1166 (t "")))
1167 (capitalize (aref org-lparse-table-colalign-vector c))))))
1169 (defun org-odt-get-paragraph-style-cookie-for-table-cell (r c)
1170 (concat
1171 (and (not org-odt-table-style-spec)
1172 (cond
1173 (org-lparse-table-cur-rowgrp-is-hdr "OrgTableHeading")
1174 ((and (= c 0) (org-lparse-get 'TABLE-FIRST-COLUMN-AS-LABELS))
1175 "OrgTableHeading")
1176 (t "OrgTableContents")))
1177 (and org-lparse-table-is-styled
1178 (format "@@table-cell:p@@%03d@@%03d@@" r c))))
1180 (defun org-odt-get-style-name-cookie-for-table-cell (r c)
1181 (when org-lparse-table-is-styled
1182 (format "@@table-cell:style-name@@%03d@@%03d@@" r c)))
1184 (defun org-odt-format-table-cell (data r c horiz-span)
1185 (concat
1186 (let* ((paragraph-style-cookie
1187 (org-odt-get-paragraph-style-cookie-for-table-cell r c))
1188 (style-name-cookie
1189 (org-odt-get-style-name-cookie-for-table-cell r c))
1190 (extra (and style-name-cookie
1191 (format " table:style-name=\"%s\"" style-name-cookie)))
1192 (extra (concat extra
1193 (and (> horiz-span 0)
1194 (format " table:number-columns-spanned=\"%d\""
1195 (1+ horiz-span))))))
1196 (org-odt-format-tags
1197 '("<table:table-cell%s>" . "</table:table-cell>")
1198 (if org-lparse-list-table-p data
1199 (org-odt-format-stylized-paragraph paragraph-style-cookie data)) extra))
1200 (let (s)
1201 (dotimes (i horiz-span)
1202 (setq s (concat s "\n<table:covered-table-cell/>"))) s)
1203 "\n"))
1205 (defun org-odt-begin-footnote-definition (n)
1206 (org-lparse-begin-paragraph 'footnote))
1208 (defun org-odt-end-footnote-definition (n)
1209 (org-lparse-end-paragraph))
1211 (defun org-odt-begin-toc (lang-specific-heading max-level)
1212 (insert
1213 (format "
1214 <text:table-of-content text:style-name=\"Sect2\" text:protected=\"true\" text:name=\"Table of Contents1\">
1215 <text:table-of-content-source text:outline-level=\"%d\">
1216 <text:index-title-template text:style-name=\"Contents_20_Heading\">%s</text:index-title-template>
1217 " max-level lang-specific-heading))
1218 (loop for level from 1 upto 10
1219 do (insert (format
1221 <text:table-of-content-entry-template text:outline-level=\"%d\" text:style-name=\"Contents_20_%d\">
1222 <text:index-entry-link-start text:style-name=\"Internet_20_link\"/>
1223 <text:index-entry-chapter/>
1224 <text:index-entry-text/>
1225 <text:index-entry-link-end/>
1226 </text:table-of-content-entry-template>
1227 " level level)))
1229 (insert
1230 (format "
1231 </text:table-of-content-source>
1233 <text:index-body>
1234 <text:index-title text:style-name=\"Sect1\" text:name=\"Table of Contents1_Head\">
1235 <text:p text:style-name=\"Contents_20_Heading\">%s</text:p>
1236 </text:index-title>
1237 " lang-specific-heading)))
1239 (defun org-odt-end-toc ()
1240 (insert "
1241 </text:index-body>
1242 </text:table-of-content>
1245 (defun org-odt-format-toc-entry (snumber todo headline tags href)
1246 (setq headline (concat
1247 (and org-export-with-section-numbers
1248 (concat snumber ". "))
1249 headline
1250 (and tags
1251 (concat
1252 (org-lparse-format 'SPACES 3)
1253 (org-lparse-format 'FONTIFY tags "tag")))))
1254 (when todo
1255 (setq headline (org-lparse-format 'FONTIFY headline "todo")))
1257 (let ((org-odt-suppress-xref t))
1258 (org-odt-format-link headline (concat "#" href))))
1260 (defun org-odt-format-toc-item (toc-entry level org-last-level)
1261 (let ((style (format "Contents_20_%d"
1262 (+ level (or (org-lparse-get 'TOPLEVEL-HLEVEL) 1) -1))))
1263 (insert "\n" (org-odt-format-stylized-paragraph style toc-entry) "\n")))
1265 ;; Following variable is let bound during 'ORG-LINK callback. See
1266 ;; org-html.el
1267 (defvar org-lparse-link-description-is-image nil)
1268 (defun org-odt-format-link (desc href &optional attr)
1269 (cond
1270 ((and (= (string-to-char href) ?#) (not org-odt-suppress-xref))
1271 (setq href (concat org-export-odt-bookmark-prefix (substring href 1)))
1272 (let ((xref-format "text"))
1273 (when (numberp desc)
1274 (setq desc (format "%d" desc) xref-format "number"))
1275 (org-odt-format-tags
1276 '("<text:bookmark-ref text:reference-format=\"%s\" text:ref-name=\"%s\">" .
1277 "</text:bookmark-ref>")
1278 desc xref-format href)))
1279 (org-lparse-link-description-is-image
1280 (org-odt-format-tags
1281 '("<draw:a xlink:type=\"simple\" xlink:href=\"%s\" %s>" . "</draw:a>")
1282 desc href (or attr "")))
1284 (org-odt-format-tags
1285 '("<text:a xlink:type=\"simple\" xlink:href=\"%s\" %s>" . "</text:a>")
1286 desc href (or attr "")))))
1288 (defun org-odt-format-spaces (n)
1289 (cond
1290 ((= n 1) " ")
1291 ((> n 1) (concat
1292 " " (org-odt-format-tags "<text:s text:c=\"%d\"/>" "" (1- n))))
1293 (t "")))
1295 (defun org-odt-format-tabs (&optional n)
1296 (let ((tab "<text:tab/>")
1297 (n (or n 1)))
1298 (insert tab)))
1300 (defun org-odt-format-line-break ()
1301 (org-odt-format-tags "<text:line-break/>" ""))
1303 (defun org-odt-format-horizontal-line ()
1304 (org-odt-format-stylized-paragraph 'horizontal-line ""))
1306 (defun org-odt-encode-plain-text (line &optional no-whitespace-filling)
1307 (setq line (org-xml-encode-plain-text line))
1308 (if no-whitespace-filling line
1309 (org-odt-fill-tabs-and-spaces line)))
1311 (defun org-odt-format-line (line)
1312 (case org-lparse-dyn-current-environment
1313 (fixedwidth (concat
1314 (org-odt-format-stylized-paragraph
1315 'fixedwidth (org-odt-encode-plain-text line)) "\n"))
1316 (t (concat line "\n"))))
1318 (defun org-odt-format-comment (fmt &rest args)
1319 (let ((comment (apply 'format fmt args)))
1320 (format "\n<!-- %s -->\n" comment)))
1322 (defun org-odt-format-org-entity (wd)
1323 (org-entity-get-representation wd 'utf8))
1325 (defun org-odt-fill-tabs-and-spaces (line)
1326 (replace-regexp-in-string
1327 "\\([\t]\\|\\([ ]+\\)\\)" (lambda (s)
1328 (cond
1329 ((string= s "\t") (org-odt-format-tabs))
1330 (t (org-odt-format-spaces (length s))))) line))
1332 (defcustom org-export-odt-fontify-srcblocks t
1333 "Specify whether or not source blocks need to be fontified.
1334 Turn this option on if you want to colorize the source code
1335 blocks in the exported file. For colorization to work, you need
1336 to make available an enhanced version of `htmlfontify' library."
1337 :type 'boolean
1338 :group 'org-export-odt)
1340 (defun org-odt-format-source-line-with-line-number-and-label
1341 (line rpllbl num fontifier par-style)
1343 (let ((keep-label (not (numberp rpllbl)))
1344 (ref (org-find-text-property-in-string 'org-coderef line)))
1345 (setq line (concat line (and keep-label ref (format "(%s)" ref))))
1346 (setq line (funcall fontifier line))
1347 (when ref
1348 (setq line (org-odt-format-target line (concat "coderef-" ref))))
1349 (setq line (org-odt-format-stylized-paragraph par-style line))
1350 (if (not num) line
1351 (org-odt-format-tags '("<text:list-item>" . "</text:list-item>") line))))
1353 (defun org-odt-format-source-code-or-example-plain
1354 (lines lang caption textareap cols rows num cont rpllbl fmt)
1355 "Format source or example blocks much like fixedwidth blocks.
1356 Use this when `org-export-odt-fontify-srcblocks' option is turned
1357 off."
1358 (let* ((lines (org-split-string lines "[\r\n]"))
1359 (line-count (length lines))
1360 (i 0))
1361 (mapconcat
1362 (lambda (line)
1363 (incf i)
1364 (org-odt-format-source-line-with-line-number-and-label
1365 line rpllbl num 'org-odt-encode-plain-text
1366 (if (= i line-count) "OrgFixedWidthBlockLastLine"
1367 "OrgFixedWidthBlock")))
1368 lines "\n")))
1370 (defvar org-src-block-paragraph-format
1371 "<style:style style:name=\"OrgSrcBlock\" style:family=\"paragraph\" style:parent-style-name=\"Preformatted_20_Text\">
1372 <style:paragraph-properties fo:background-color=\"%s\" fo:padding=\"0.049cm\" fo:border=\"0.51pt solid #000000\" style:shadow=\"none\">
1373 <style:background-image/>
1374 </style:paragraph-properties>
1375 <style:text-properties fo:color=\"%s\"/>
1376 </style:style>"
1377 "Custom paragraph style for colorized source and example blocks.
1378 This style is much the same as that of \"OrgFixedWidthBlock\"
1379 except that the foreground and background colors are set
1380 according to the default face identified by the `htmlfontify'.")
1382 (defvar hfy-optimisations)
1383 (declare-function hfy-face-to-style "htmlfontify" (fn))
1384 (declare-function hfy-face-or-def-to-name "htmlfontify" (fn))
1386 (defun org-odt-hfy-face-to-css (fn)
1387 "Create custom style for face FN.
1388 When FN is the default face, use it's foreground and background
1389 properties to create \"OrgSrcBlock\" paragraph style. Otherwise
1390 use it's color attribute to create a character style whose name
1391 is obtained from FN. Currently all attributes of FN other than
1392 color are ignored.
1394 The style name for a face FN is derived using the following
1395 operations on the face name in that order - de-dash, CamelCase
1396 and prefix with \"OrgSrc\". For example,
1397 `font-lock-function-name-face' is associated with
1398 \"OrgSrcFontLockFunctionNameFace\"."
1399 (let* ((css-list (hfy-face-to-style fn))
1400 (style-name ((lambda (fn)
1401 (concat "OrgSrc"
1402 (mapconcat
1403 'capitalize (split-string
1404 (hfy-face-or-def-to-name fn) "-")
1405 ""))) fn))
1406 (color-val (cdr (assoc "color" css-list)))
1407 (background-color-val (cdr (assoc "background" css-list)))
1408 (style (and org-export-odt-create-custom-styles-for-srcblocks
1409 (cond
1410 ((eq fn 'default)
1411 (format org-src-block-paragraph-format
1412 background-color-val color-val))
1414 (format
1416 <style:style style:name=\"%s\" style:family=\"text\">
1417 <style:text-properties fo:color=\"%s\"/>
1418 </style:style>" style-name color-val))))))
1419 (cons style-name style)))
1421 (defun org-odt-insert-custom-styles-for-srcblocks (styles)
1422 "Save STYLES used for colorizing of source blocks.
1423 Update styles.xml with styles that were collected as part of
1424 `org-odt-hfy-face-to-css' callbacks."
1425 (when styles
1426 (with-current-buffer
1427 (find-file-noselect (expand-file-name "styles.xml") t)
1428 (goto-char (point-min))
1429 (when (re-search-forward "</office:styles>" nil t)
1430 (goto-char (match-beginning 0))
1431 (insert "\n<!-- Org Htmlfontify Styles -->\n" styles "\n")))))
1433 (defun org-odt-format-source-code-or-example-colored
1434 (lines lang caption textareap cols rows num cont rpllbl fmt)
1435 "Format source or example blocks using `htmlfontify-string'.
1436 Use this routine when `org-export-odt-fontify-srcblocks' option
1437 is turned on."
1438 (let* ((lang-m (and lang (or (cdr (assoc lang org-src-lang-modes)) lang)))
1439 (mode (and lang-m (intern (concat (if (symbolp lang-m)
1440 (symbol-name lang-m)
1441 lang-m) "-mode"))))
1442 (org-inhibit-startup t)
1443 (org-startup-folded nil)
1444 (lines (with-temp-buffer
1445 (insert lines)
1446 (if (functionp mode) (funcall mode) (fundamental-mode))
1447 (font-lock-fontify-buffer)
1448 (buffer-string)))
1449 (hfy-html-quote-regex "\\([<\"&> ]\\)")
1450 (hfy-html-quote-map '(("\"" "&quot;")
1451 ("<" "&lt;")
1452 ("&" "&amp;")
1453 (">" "&gt;")
1454 (" " "<text:s/>")
1455 (" " "<text:tab/>")))
1456 (hfy-face-to-css 'org-odt-hfy-face-to-css)
1457 (hfy-optimisations-1 (copy-seq hfy-optimisations))
1458 (hfy-optimisations (add-to-list 'hfy-optimisations-1
1459 'body-text-only))
1460 (hfy-begin-span-handler
1461 (lambda (style text-block text-id text-begins-block-p)
1462 (insert (format "<text:span text:style-name=\"%s\">" style))))
1463 (hfy-end-span-handler (lambda nil (insert "</text:span>"))))
1464 (when (fboundp 'htmlfontify-string)
1465 (let* ((lines (org-split-string lines "[\r\n]"))
1466 (line-count (length lines))
1467 (i 0))
1468 (mapconcat
1469 (lambda (line)
1470 (incf i)
1471 (org-odt-format-source-line-with-line-number-and-label
1472 line rpllbl num 'htmlfontify-string
1473 (if (= i line-count) "OrgSrcBlockLastLine" "OrgSrcBlock")))
1474 lines "\n")))))
1476 (defun org-odt-format-source-code-or-example (lines lang caption textareap
1477 cols rows num cont
1478 rpllbl fmt)
1479 "Format source or example blocks for export.
1480 Use `org-odt-format-source-code-or-example-plain' or
1481 `org-odt-format-source-code-or-example-colored' depending on the
1482 value of `org-export-odt-fontify-srcblocks."
1483 (setq lines (org-export-number-lines
1484 lines 0 0 num cont rpllbl fmt 'preprocess)
1485 lines (funcall
1486 (or (and org-export-odt-fontify-srcblocks
1487 (or (featurep 'htmlfontify)
1488 ;; htmlfontify.el was introduced in Emacs 23.2
1489 ;; So load it with some caution
1490 (require 'htmlfontify nil t))
1491 (fboundp 'htmlfontify-string)
1492 'org-odt-format-source-code-or-example-colored)
1493 'org-odt-format-source-code-or-example-plain)
1494 lines lang caption textareap cols rows num cont rpllbl fmt))
1495 (if (not num) lines
1496 (let ((extra (format " text:continue-numbering=\"%s\""
1497 (if cont "true" "false"))))
1498 (org-odt-format-tags
1499 '("<text:list text:style-name=\"OrgSrcBlockNumberedLine\"%s>"
1500 . "</text:list>") lines extra))))
1502 (defun org-odt-remap-stylenames (style-name)
1504 (cdr (assoc style-name '(("timestamp-wrapper" . "OrgTimestampWrapper")
1505 ("timestamp" . "OrgTimestamp")
1506 ("timestamp-kwd" . "OrgTimestampKeyword")
1507 ("tag" . "OrgTag")
1508 ("todo" . "OrgTodo")
1509 ("done" . "OrgDone")
1510 ("target" . "OrgTarget"))))
1511 style-name))
1513 (defun org-odt-format-fontify (text style &optional id)
1514 (let* ((style-name
1515 (cond
1516 ((stringp style)
1517 (org-odt-remap-stylenames style))
1518 ((symbolp style)
1519 (org-odt-get-style-name-for-entity 'character style))
1520 ((listp style)
1521 (assert (< 1 (length style)))
1522 (let ((parent-style (pop style)))
1523 (mapconcat (lambda (s)
1524 ;; (assert (stringp s) t)
1525 (org-odt-remap-stylenames s)) style "")
1526 (org-odt-remap-stylenames parent-style)))
1527 (t (error "Don't how to handle style %s" style)))))
1528 (org-odt-format-tags
1529 '("<text:span text:style-name=\"%s\">" . "</text:span>")
1530 text style-name)))
1532 (defun org-odt-relocate-relative-path (path dir)
1533 (if (file-name-absolute-p path) path
1534 (file-relative-name (expand-file-name path dir)
1535 (expand-file-name "eyecandy" dir))))
1537 (defun org-odt-format-inline-image (thefile)
1538 (let* ((thelink (if (file-name-absolute-p thefile) thefile
1539 (org-xml-format-href
1540 (org-odt-relocate-relative-path
1541 thefile org-current-export-file))))
1542 (href
1543 (org-odt-format-tags
1544 "<draw:image xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>" ""
1545 (if org-export-odt-embed-images
1546 (org-odt-copy-image-file thefile) thelink))))
1547 (org-export-odt-format-image thefile href)))
1549 (defun org-export-odt-format-formula (src href)
1550 (save-match-data
1551 (let* ((caption (org-find-text-property-in-string 'org-caption src))
1552 (caption (and caption (org-xml-format-desc caption)))
1553 (label (org-find-text-property-in-string 'org-label src))
1554 (latex-frag (org-find-text-property-in-string 'org-latex-src src))
1555 (embed-as (or (and latex-frag
1556 (org-find-text-property-in-string
1557 'org-latex-src-embed-type src))
1558 (if (or caption label) 'paragraph 'character)))
1559 width height)
1560 (when latex-frag
1561 (setq href (org-propertize href :title "LaTeX Fragment"
1562 :description latex-frag)))
1563 (cond
1564 ((eq embed-as 'character)
1565 (org-odt-format-entity "InlineFormula" href width height))
1567 (org-lparse-end-paragraph)
1568 (org-lparse-insert-list-table
1569 `((,(org-odt-format-entity
1570 (if caption "CaptionedDisplayFormula" "DisplayFormula")
1571 href width height :caption caption :label nil)
1572 ,(if (not label) ""
1573 (org-odt-format-entity-caption label nil "__MathFormula__"))))
1574 nil nil nil ":style \"OrgEquation\"" nil '((1 "c" 8) (2 "c" 1)))
1575 (throw 'nextline nil))))))
1577 (defvar org-odt-embedded-formulas-count 0)
1578 (defun org-odt-copy-formula-file (path)
1579 "Returns the internal name of the file"
1580 (let* ((src-file (expand-file-name
1581 path (file-name-directory org-current-export-file)))
1582 (target-dir (format "Formula-%04d/"
1583 (incf org-odt-embedded-formulas-count)))
1584 (target-file (concat target-dir "content.xml")))
1585 (when (not org-lparse-to-buffer)
1586 (message "Embedding %s as %s ..."
1587 (substring-no-properties path) target-file)
1589 (make-directory target-dir)
1590 (org-odt-create-manifest-file-entry
1591 "application/vnd.oasis.opendocument.formula" target-dir "1.2")
1593 (case (org-odt-is-formula-link-p src-file)
1594 (mathml
1595 (copy-file src-file target-file 'overwrite))
1596 (odf
1597 (org-odt-zip-extract-one src-file "content.xml" target-dir))
1599 (error "%s is not a formula file" src-file)))
1601 (org-odt-create-manifest-file-entry "text/xml" target-file))
1602 target-file))
1604 (defun org-odt-format-inline-formula (thefile)
1605 (let* ((thelink (if (file-name-absolute-p thefile) thefile
1606 (org-xml-format-href
1607 (org-odt-relocate-relative-path
1608 thefile org-current-export-file))))
1609 (href
1610 (org-odt-format-tags
1611 "<draw:object xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>" ""
1612 (file-name-directory (org-odt-copy-formula-file thefile)))))
1613 (org-export-odt-format-formula thefile href)))
1615 (defun org-odt-is-formula-link-p (file)
1616 (let ((case-fold-search nil))
1617 (cond
1618 ((string-match "\\.\\(mathml\\|mml\\)\\'" file)
1619 'mathml)
1620 ((string-match "\\.odf\\'" file)
1621 'odf))))
1623 (defun org-odt-format-org-link (opt-plist type-1 path fragment desc attr
1624 descp)
1625 "Make a OpenDocument link.
1626 OPT-PLIST is an options list.
1627 TYPE-1 is the device-type of the link (THIS://foo.html).
1628 PATH is the path of the link (http://THIS#location).
1629 FRAGMENT is the fragment part of the link, if any (foo.html#THIS).
1630 DESC is the link description, if any.
1631 ATTR is a string of other attributes of the a element."
1632 (declare (special org-lparse-par-open))
1633 (save-match-data
1634 (let* ((may-inline-p
1635 (and (member type-1 '("http" "https" "file"))
1636 (org-lparse-should-inline-p path descp)
1637 (not fragment)))
1638 (type (if (equal type-1 "id") "file" type-1))
1639 (filename path)
1640 (thefile path))
1641 (cond
1642 ;; check for inlined images
1643 ((and (member type '("file"))
1644 (not fragment)
1645 (org-file-image-p
1646 filename org-export-odt-inline-image-extensions)
1647 (or (eq t org-export-odt-inline-images)
1648 (and org-export-odt-inline-images (not descp))))
1649 (org-odt-format-inline-image thefile))
1650 ;; check for embedded formulas
1651 ((and (member type '("file"))
1652 (not fragment)
1653 (org-odt-is-formula-link-p filename)
1654 (or (not descp)))
1655 (org-odt-format-inline-formula thefile))
1656 ((string= type "coderef")
1657 (let* ((ref fragment)
1658 (lineno-or-ref (cdr (assoc ref org-export-code-refs)))
1659 (desc (and descp desc))
1660 (org-odt-suppress-xref nil)
1661 (href (org-xml-format-href (concat "#coderef-" ref))))
1662 (cond
1663 ((and (numberp lineno-or-ref) (not desc))
1664 (org-odt-format-link lineno-or-ref href))
1665 ((and (numberp lineno-or-ref) desc
1666 (string-match (regexp-quote (concat "(" ref ")")) desc))
1667 (format (replace-match "%s" t t desc)
1668 (org-odt-format-link lineno-or-ref href)))
1670 (setq desc (format
1671 (if (and desc (string-match
1672 (regexp-quote (concat "(" ref ")"))
1673 desc))
1674 (replace-match "%s" t t desc)
1675 (or desc "%s"))
1676 lineno-or-ref))
1677 (org-odt-format-link (org-xml-format-desc desc) href)))))
1679 (when (string= type "file")
1680 (setq thefile
1681 (cond
1682 ((file-name-absolute-p path)
1683 (concat "file://" (expand-file-name path)))
1684 (t (org-odt-relocate-relative-path
1685 thefile org-current-export-file)))))
1687 (when (and (member type '("" "http" "https" "file")) fragment)
1688 (setq thefile (concat thefile "#" fragment)))
1690 (setq thefile (org-xml-format-href thefile))
1692 (when (not (member type '("" "file")))
1693 (setq thefile (concat type ":" thefile)))
1695 (let ((org-odt-suppress-xref nil))
1696 (org-odt-format-link
1697 (org-xml-format-desc desc) thefile attr)))))))
1699 (defun org-odt-format-heading (text level &optional id)
1700 (let* ((text (if id (org-odt-format-target text id) text)))
1701 (org-odt-format-tags
1702 '("<text:h text:style-name=\"Heading_20_%s\" text:outline-level=\"%s\">" .
1703 "</text:h>") text level level)))
1705 (defun org-odt-format-headline (title extra-targets tags
1706 &optional snumber level)
1707 (concat
1708 (org-lparse-format 'EXTRA-TARGETS extra-targets)
1710 ;; No need to generate section numbers. They are auto-generated by
1711 ;; the application
1713 ;; (concat (org-lparse-format 'SECTION-NUMBER snumber level) " ")
1714 title
1715 (and tags (concat (org-lparse-format 'SPACES 3)
1716 (org-lparse-format 'ORG-TAGS tags)))))
1718 (defun org-odt-format-anchor (text name &optional class)
1719 (org-odt-format-target text name))
1721 (defun org-odt-format-bookmark (text id)
1722 (if id
1723 (org-odt-format-tags "<text:bookmark text:name=\"%s\"/>" text id)
1724 text))
1726 (defun org-odt-format-target (text id)
1727 (let ((name (concat org-export-odt-bookmark-prefix id)))
1728 (concat
1729 (and id (org-odt-format-tags
1730 "<text:bookmark-start text:name=\"%s\"/>" "" name))
1731 (org-odt-format-bookmark text id)
1732 (and id (org-odt-format-tags
1733 "<text:bookmark-end text:name=\"%s\"/>" "" name)))))
1735 (defun org-odt-format-footnote (n def)
1736 (let ((id (concat "fn" n))
1737 (note-class "footnote")
1738 (par-style "Footnote"))
1739 (org-odt-format-tags
1740 '("<text:note text:id=\"%s\" text:note-class=\"%s\">" .
1741 "</text:note>")
1742 (concat
1743 (org-odt-format-tags
1744 '("<text:note-citation>" . "</text:note-citation>")
1746 (org-odt-format-tags
1747 '("<text:note-body>" . "</text:note-body>")
1748 def))
1749 id note-class)))
1751 (defun org-odt-format-footnote-reference (n def refcnt)
1752 (if (= refcnt 1)
1753 (org-odt-format-footnote n def)
1754 (org-odt-format-footnote-ref n)))
1756 (defun org-odt-format-footnote-ref (n)
1757 (let ((note-class "footnote")
1758 (ref-format "text")
1759 (ref-name (concat "fn" n)))
1760 (org-odt-format-tags
1761 '("<text:span text:style-name=\"%s\">" . "</text:span>")
1762 (org-odt-format-tags
1763 '("<text:note-ref text:note-class=\"%s\" text:reference-format=\"%s\" text:ref-name=\"%s\">" . "</text:note-ref>")
1764 n note-class ref-format ref-name)
1765 "OrgSuperscript")))
1767 (defun org-odt-get-image-name (file-name)
1768 (require 'sha1)
1769 (file-relative-name
1770 (expand-file-name
1771 (concat (sha1 file-name) "." (file-name-extension file-name)) "Pictures")))
1773 (defun org-export-odt-format-image (src href)
1774 "Create image tag with source and attributes."
1775 (save-match-data
1776 (let* ((caption (org-find-text-property-in-string 'org-caption src))
1777 (caption (and caption (org-xml-format-desc caption)))
1778 (attr (org-find-text-property-in-string 'org-attributes src))
1779 (label (org-find-text-property-in-string 'org-label src))
1780 (latex-frag (org-find-text-property-in-string
1781 'org-latex-src src))
1782 (category (and latex-frag "__DvipngImage__"))
1783 (attr-plist (org-lparse-get-block-params attr))
1784 (user-frame-anchor
1785 (car (assoc-string (plist-get attr-plist :anchor)
1786 '(("as-char") ("paragraph") ("page")) t)))
1787 (user-frame-style
1788 (and user-frame-anchor (plist-get attr-plist :style)))
1789 (user-frame-attrs
1790 (and user-frame-anchor (plist-get attr-plist :attributes)))
1791 (user-frame-params
1792 (list user-frame-style user-frame-attrs user-frame-anchor))
1793 (embed-as (cond
1794 (latex-frag
1795 (symbol-name
1796 (case (org-find-text-property-in-string
1797 'org-latex-src-embed-type src)
1798 (paragraph 'paragraph)
1799 (t 'as-char))))
1800 (user-frame-anchor)
1801 (t "paragraph")))
1802 (size (org-odt-image-size-from-file
1803 src (plist-get attr-plist :width)
1804 (plist-get attr-plist :height)
1805 (plist-get attr-plist :scale) nil embed-as))
1806 (width (car size)) (height (cdr size)))
1807 (when latex-frag
1808 (setq href (org-propertize href :title "LaTeX Fragment"
1809 :description latex-frag)))
1810 (let ((frame-style-handle (concat (and (or caption label) "Captioned")
1811 embed-as "Image")))
1812 (org-odt-format-entity
1813 frame-style-handle href width height
1814 :caption caption :label label :category category
1815 :user-frame-params user-frame-params)))))
1817 (defun org-odt-format-object-description (title description)
1818 (concat (and title (org-odt-format-tags
1819 '("<svg:title>" . "</svg:title>")
1820 (org-odt-encode-plain-text title t)))
1821 (and description (org-odt-format-tags
1822 '("<svg:desc>" . "</svg:desc>")
1823 (org-odt-encode-plain-text description t)))))
1825 (defun org-odt-format-frame (text width height style &optional
1826 extra anchor-type)
1827 (let ((frame-attrs
1828 (concat
1829 (if width (format " svg:width=\"%0.2fcm\"" width) "")
1830 (if height (format " svg:height=\"%0.2fcm\"" height) "")
1831 extra
1832 (format " text:anchor-type=\"%s\"" (or anchor-type "paragraph")))))
1833 (org-odt-format-tags
1834 '("<draw:frame draw:style-name=\"%s\"%s>" . "</draw:frame>")
1835 (concat text (org-odt-format-object-description
1836 (get-text-property 0 :title text)
1837 (get-text-property 0 :description text)))
1838 style frame-attrs)))
1840 (defun org-odt-format-textbox (text width height style &optional
1841 extra anchor-type)
1842 (org-odt-format-frame
1843 (org-odt-format-tags
1844 '("<draw:text-box %s>" . "</draw:text-box>")
1845 text (concat (format " fo:min-height=\"%0.2fcm\"" (or height .2))
1846 (unless width
1847 (format " fo:min-width=\"%0.2fcm\"" (or width .2)))))
1848 width nil style extra anchor-type))
1850 (defun org-odt-format-inlinetask (heading content
1851 &optional todo priority tags)
1852 (org-odt-format-stylized-paragraph
1853 nil (org-odt-format-textbox
1854 (concat (org-odt-format-stylized-paragraph
1855 "OrgInlineTaskHeading"
1856 (org-lparse-format
1857 'HEADLINE (concat (org-lparse-format-todo todo) " " heading)
1858 nil tags))
1859 content) nil nil "OrgInlineTaskFrame" " style:rel-width=\"100%\"")))
1861 (defvar org-odt-entity-frame-styles
1862 '(("As-CharImage" "__Figure__" ("OrgInlineImage" nil "as-char"))
1863 ("ParagraphImage" "__Figure__" ("OrgDisplayImage" nil "paragraph"))
1864 ("PageImage" "__Figure__" ("OrgPageImage" nil "page"))
1865 ("CaptionedAs-CharImage" "__Figure__"
1866 ("OrgCaptionedImage"
1867 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
1868 ("OrgInlineImage" nil "as-char"))
1869 ("CaptionedParagraphImage" "__Figure__"
1870 ("OrgCaptionedImage"
1871 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
1872 ("OrgImageCaptionFrame" nil "paragraph"))
1873 ("CaptionedPageImage" "__Figure__"
1874 ("OrgCaptionedImage"
1875 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
1876 ("OrgPageImageCaptionFrame" nil "page"))
1877 ("InlineFormula" "__MathFormula__" ("OrgInlineFormula" nil "as-char"))
1878 ("DisplayFormula" "__MathFormula__" ("OrgDisplayFormula" nil "as-char"))
1879 ("CaptionedDisplayFormula" "__MathFormula__"
1880 ("OrgCaptionedFormula" nil "paragraph")
1881 ("OrgFormulaCaptionFrame" nil "as-char"))))
1883 (defun org-odt-merge-frame-params(default-frame-params user-frame-params)
1884 (if (not user-frame-params) default-frame-params
1885 (assert (= (length default-frame-params) 3))
1886 (assert (= (length user-frame-params) 3))
1887 (loop for user-frame-param in user-frame-params
1888 for default-frame-param in default-frame-params
1889 collect (or user-frame-param default-frame-param))))
1891 (defun* org-odt-format-entity (entity href width height
1892 &key caption label category
1893 user-frame-params)
1894 (let* ((entity-style (assoc-string entity org-odt-entity-frame-styles t))
1895 default-frame-params frame-params)
1896 (cond
1897 ((not (or caption label))
1898 (setq default-frame-params (nth 2 entity-style))
1899 (setq frame-params (org-odt-merge-frame-params
1900 default-frame-params user-frame-params))
1901 (apply 'org-odt-format-frame href width height frame-params))
1903 (setq default-frame-params (nth 3 entity-style))
1904 (setq frame-params (org-odt-merge-frame-params
1905 default-frame-params user-frame-params))
1906 (apply 'org-odt-format-textbox
1907 (org-odt-format-stylized-paragraph
1908 'illustration
1909 (concat
1910 (apply 'org-odt-format-frame href width height
1911 (nth 2 entity-style))
1912 (org-odt-format-entity-caption
1913 label caption (or category (nth 1 entity-style)))))
1914 width height frame-params)))))
1916 (defvar org-odt-embedded-images-count 0)
1917 (defun org-odt-copy-image-file (path)
1918 "Returns the internal name of the file"
1919 (let* ((image-type (file-name-extension path))
1920 (media-type (format "image/%s" image-type))
1921 (src-file (expand-file-name
1922 path (file-name-directory org-current-export-file)))
1923 (target-dir "Images/")
1924 (target-file
1925 (format "%s%04d.%s" target-dir
1926 (incf org-odt-embedded-images-count) image-type)))
1927 (when (not org-lparse-to-buffer)
1928 (message "Embedding %s as %s ..."
1929 (substring-no-properties path) target-file)
1931 (when (= 1 org-odt-embedded-images-count)
1932 (make-directory target-dir)
1933 (org-odt-create-manifest-file-entry "" target-dir))
1935 (copy-file src-file target-file 'overwrite)
1936 (org-odt-create-manifest-file-entry media-type target-file))
1937 target-file))
1939 (defvar org-export-odt-image-size-probe-method
1940 '(emacs imagemagick force)
1941 "Ordered list of methods by for determining size of an embedded
1942 image.")
1944 (defvar org-export-odt-default-image-sizes-alist
1945 '(("as-char" . (5 . 0.4))
1946 ("paragraph" . (5 . 5)))
1947 "Hardcoded image dimensions one for each of the anchor
1948 methods.")
1950 ;; A4 page size is 21.0 by 29.7 cms
1951 ;; The default page settings has 2cm margin on each of the sides. So
1952 ;; the effective text area is 17.0 by 25.7 cm
1953 (defvar org-export-odt-max-image-size '(17.0 . 20.0)
1954 "Limiting dimensions for an embedded image.")
1956 (defun org-odt-do-image-size (probe-method file &optional dpi anchor-type)
1957 (setq dpi (or dpi org-export-odt-pixels-per-inch))
1958 (setq anchor-type (or anchor-type "paragraph"))
1959 (flet ((size-in-cms (size-in-pixels)
1960 (flet ((pixels-to-cms (pixels)
1961 (let* ((cms-per-inch 2.54)
1962 (inches (/ pixels dpi)))
1963 (* cms-per-inch inches))))
1964 (and size-in-pixels
1965 (cons (pixels-to-cms (car size-in-pixels))
1966 (pixels-to-cms (cdr size-in-pixels)))))))
1967 (case probe-method
1968 (emacs
1969 (size-in-cms (ignore-errors (image-size (create-image file) 'pixels))))
1970 (imagemagick
1971 (size-in-cms
1972 (let ((dim (shell-command-to-string
1973 (format "identify -format \"%%w:%%h\" \"%s\"" file))))
1974 (when (string-match "\\([0-9]+\\):\\([0-9]+\\)" dim)
1975 (cons (string-to-number (match-string 1 dim))
1976 (string-to-number (match-string 2 dim)))))))
1978 (cdr (assoc-string anchor-type
1979 org-export-odt-default-image-sizes-alist))))))
1981 (defun org-odt-image-size-from-file (file &optional user-width
1982 user-height scale dpi embed-as)
1983 (unless (file-name-absolute-p file)
1984 (setq file (expand-file-name
1985 file (file-name-directory org-current-export-file))))
1986 (let* (size width height)
1987 (unless (and user-height user-width)
1988 (loop for probe-method in org-export-odt-image-size-probe-method
1989 until size
1990 do (setq size (org-odt-do-image-size
1991 probe-method file dpi embed-as)))
1992 (or size (error "Cannot determine Image size. Aborting ..."))
1993 (setq width (car size) height (cdr size)))
1994 (cond
1995 (scale
1996 (setq width (* width scale) height (* height scale)))
1997 ((and user-height user-width)
1998 (setq width user-width height user-height))
1999 (user-height
2000 (setq width (* user-height (/ width height)) height user-height))
2001 (user-width
2002 (setq height (* user-width (/ height width)) width user-width))
2003 (t (ignore)))
2004 ;; ensure that an embedded image fits comfortably within a page
2005 (let ((max-width (car org-export-odt-max-image-size))
2006 (max-height (cdr org-export-odt-max-image-size)))
2007 (when (or (> width max-width) (> height max-height))
2008 (let* ((scale1 (/ max-width width))
2009 (scale2 (/ max-height height))
2010 (scale (min scale1 scale2)))
2011 (setq width (* scale width) height (* scale height)))))
2012 (cons width height)))
2014 (defvar org-odt-entity-labels-alist nil
2015 "Associate Labels with the Labeled entities.
2016 Each element of the alist is of the form (LABEL-NAME
2017 CATEGORY-NAME SEQNO LABEL-STYLE-NAME). LABEL-NAME is same as
2018 that specified by \"#+LABEL: ...\" line. CATEGORY-NAME is the
2019 type of the entity that LABEL-NAME is attached to. CATEGORY-NAME
2020 can be one of \"Table\", \"Figure\" or \"Equation\". SEQNO is
2021 the unique number assigned to the referenced entity on a
2022 per-CATEGORY basis. It is generated sequentially and is 1-based.
2023 LABEL-STYLE-NAME is a key `org-odt-label-styles'.
2025 See `org-odt-add-label-definition' and
2026 `org-odt-fixup-label-references'.")
2028 (defvar org-odt-entity-counts-plist nil
2029 "Plist of running counters of SEQNOs for each of the CATEGORY-NAMEs.
2030 See `org-odt-entity-labels-alist' for known CATEGORY-NAMEs.")
2032 (defvar org-odt-label-styles
2033 '(("text" "(%n)" "text" "(%n)")
2034 ("category-and-value" "%e %n%c" "category-and-value" "%e %n")
2035 ("value" "%e %n%c" "value" "%n"))
2036 "Specify how labels are applied and referenced.
2037 This is an alist where each element is of the
2038 form (LABEL-STYLE-NAME LABEL-ATTACH-FMT LABEL-REF-MODE
2039 LABEL-REF-FMT).
2041 LABEL-ATTACH-FMT controls how labels and captions are attached to
2042 an entity. It may contain following specifiers - %e, %n and %c.
2043 %e is replaced with the CATEGORY-NAME. %n is replaced with
2044 \"<text:sequence ...> SEQNO </text:sequence>\". %c is replaced
2045 with CAPTION. See `org-odt-format-label-definition'.
2047 LABEL-REF-MODE and LABEL-REF-FMT controls how label references
2048 are generated. The following XML is generated for a label
2049 reference - \"<text:sequence-ref
2050 text:reference-format=\"LABEL-REF-MODE\" ...> LABEL-REF-FMT
2051 </text:sequence-ref>\". LABEL-REF-FMT may contain following
2052 specifiers - %e and %n. %e is replaced with the CATEGORY-NAME.
2053 %n is replaced with SEQNO. See
2054 `org-odt-format-label-reference'.")
2056 (defvar org-odt-category-map-alist
2057 '(("__Table__" "Table" "value")
2058 ("__Figure__" "Figure" "value")
2059 ("__MathFormula__" "Equation" "text")
2060 ("__DvipngImage__" "Equation" "value")
2061 ;; ("__Table__" "Table" "category-and-value")
2062 ;; ("__Figure__" "Figure" "category-and-value")
2063 ;; ("__DvipngImage__" "Equation" "category-and-value")
2065 "Map a CATEGORY-HANDLE to CATEGORY-NAME and LABEL-STYLE.
2066 This is an alist where each element is of the form
2067 \\(CATEGORY-HANDLE CATEGORY-NAME LABEL-STYLE\\). CATEGORY_HANDLE
2068 could either be one of the internal handles (as seen above) or be
2069 derived from the \"#+LABEL:<label-name>\" specification. See
2070 `org-export-odt-get-category-from-label'. CATEGORY-NAME and
2071 LABEL-STYLE are used for generating ODT labels. See
2072 `org-odt-label-styles'.")
2074 (defvar org-export-odt-user-categories
2075 '("Illustration" "Table" "Text" "Drawing" "Equation" "Figure"))
2077 (defvar org-export-odt-get-category-from-label nil
2078 "Should category of label be inferred from label itself.
2079 When this option is non-nil, a label is parsed in to two
2080 component parts delimited by a \":\" (colon) as shown here -
2081 #+LABEL:[CATEGORY-HANDLE:]EXTRA. The CATEGORY-HANDLE is mapped
2082 to a CATEGORY-NAME and LABEL-STYLE using
2083 `org-odt-category-map-alist'. (If no such map is provided and
2084 CATEGORY-NAME is set to CATEGORY-HANDLE and LABEL-STYLE is set to
2085 \"category-and-value\"). If CATEGORY-NAME so obtained is listed
2086 under `org-export-odt-user-categories' then the user specified
2087 styles are used. Otherwise styles as determined by the internal
2088 CATEGORY-HANDLE is used. See
2089 `org-odt-get-label-category-and-style' for details.")
2091 (defun org-odt-get-label-category-and-style (label default-category)
2092 "See `org-export-odt-get-category-from-label'."
2093 (let ((default-category-map
2094 (assoc default-category org-odt-category-map-alist))
2095 user-category user-category-map category)
2096 (cond
2097 ((not org-export-odt-get-category-from-label)
2098 default-category-map)
2099 ((not (setq user-category
2100 (save-match-data
2101 (and (string-match "\\`\\(.*\\):.+" label)
2102 (match-string 1 label)))))
2103 default-category-map)
2105 (setq user-category-map
2106 (or (assoc user-category org-odt-category-map-alist)
2107 (list nil user-category "category-and-value"))
2108 category (nth 1 user-category-map))
2109 (if (member category org-export-odt-user-categories)
2110 user-category-map
2111 default-category-map)))))
2113 (defun org-odt-add-label-definition (label default-category)
2114 "Create an entry in `org-odt-entity-labels-alist' and return it."
2115 (setq label (substring-no-properties label))
2116 (let* ((label-props (org-odt-get-label-category-and-style
2117 label default-category))
2118 (category (nth 1 label-props))
2119 (counter category)
2120 (label-style (nth 2 label-props))
2121 (sequence-var (intern (mapconcat
2122 'downcase
2123 (org-split-string counter) "-")))
2124 (seqno (1+ (or (plist-get org-odt-entity-counts-plist sequence-var)
2125 0)))
2126 (label-props (list label category seqno label-style)))
2127 (setq org-odt-entity-counts-plist
2128 (plist-put org-odt-entity-counts-plist sequence-var seqno))
2129 (push label-props org-odt-entity-labels-alist)
2130 label-props))
2132 (defun org-odt-format-label-definition (caption label category seqno label-style)
2133 (assert label)
2134 (format-spec
2135 (cadr (assoc-string label-style org-odt-label-styles t))
2136 `((?e . ,category)
2137 (?n . ,(org-odt-format-tags
2138 '("<text:sequence text:ref-name=\"%s\" text:name=\"%s\" text:formula=\"ooow:%s+1\" style:num-format=\"1\">" . "</text:sequence>")
2139 (format "%d" seqno) label category category))
2140 (?c . ,(or (and caption (concat ": " caption)) "")))))
2142 (defun org-odt-format-label-reference (label category seqno label-style)
2143 (assert label)
2144 (save-match-data
2145 (let* ((fmt (cddr (assoc-string label-style org-odt-label-styles t)))
2146 (fmt1 (car fmt))
2147 (fmt2 (cadr fmt)))
2148 (org-odt-format-tags
2149 '("<text:sequence-ref text:reference-format=\"%s\" text:ref-name=\"%s\">"
2150 . "</text:sequence-ref>")
2151 (format-spec fmt2 `((?e . ,category)
2152 (?n . ,(format "%d" seqno)))) fmt1 label))))
2154 (defun org-odt-fixup-label-references ()
2155 (goto-char (point-min))
2156 (while (re-search-forward
2157 "<text:sequence-ref text:ref-name=\"\\([^\"]+\\)\">[ \t\n]*</text:sequence-ref>"
2158 nil t)
2159 (let* ((label (match-string 1))
2160 (label-def (assoc label org-odt-entity-labels-alist))
2161 (rpl (and label-def
2162 (apply 'org-odt-format-label-reference label-def))))
2163 (if rpl (replace-match rpl t t)
2164 (org-lparse-warn
2165 (format "Unable to resolve reference to label \"%s\"" label))))))
2167 (defun org-odt-format-entity-caption (label caption category)
2168 (or (and label
2169 (apply 'org-odt-format-label-definition
2170 caption (org-odt-add-label-definition label category)))
2171 caption ""))
2173 (defun org-odt-format-tags (tag text &rest args)
2174 (let ((prefix (when org-lparse-encode-pending "@"))
2175 (suffix (when org-lparse-encode-pending "@")))
2176 (apply 'org-lparse-format-tags tag text prefix suffix args)))
2178 (defvar org-odt-manifest-file-entries nil)
2179 (defun org-odt-init-outfile (filename)
2180 (unless (executable-find "zip")
2181 ;; Not at all OSes ship with zip by default
2182 (error "Executable \"zip\" needed for creating OpenDocument files"))
2184 (let* ((outdir (make-temp-file
2185 (format org-export-odt-tmpdir-prefix org-lparse-backend) t))
2186 (content-file (expand-file-name "content.xml" outdir)))
2188 ;; init conten.xml
2189 (with-current-buffer (find-file-noselect content-file t))
2191 ;; reset variables
2192 (setq org-odt-manifest-file-entries nil
2193 org-odt-embedded-images-count 0
2194 org-odt-embedded-formulas-count 0
2195 org-odt-entity-labels-alist nil
2196 org-odt-list-stack-stashed nil
2197 org-odt-automatic-styles nil
2198 org-odt-object-counters nil
2199 org-odt-entity-counts-plist nil)
2200 content-file))
2202 (defcustom org-export-odt-prettify-xml nil
2203 "Specify whether or not the xml output should be prettified.
2204 When this option is turned on, `indent-region' is run on all
2205 component xml buffers before they are saved. Turn this off for
2206 regular use. Turn this on if you need to examine the xml
2207 visually."
2208 :group 'org-export-odt
2209 :type 'boolean)
2211 (defvar hfy-user-sheet-assoc) ; bound during org-do-lparse
2212 (defun org-odt-save-as-outfile (target opt-plist)
2213 ;; write automatic styles
2214 (org-odt-write-automatic-styles)
2216 ;; write meta file
2217 (org-odt-update-meta-file opt-plist)
2219 ;; write styles file
2220 (when (equal org-lparse-backend 'odt)
2221 (org-odt-update-styles-file opt-plist))
2223 ;; create mimetype file
2224 (let ((mimetype (org-odt-write-mimetype-file org-lparse-backend)))
2225 (org-odt-create-manifest-file-entry mimetype "/" "1.2"))
2227 ;; create a manifest entry for content.xml
2228 (org-odt-create-manifest-file-entry "text/xml" "content.xml")
2230 ;; write out the manifest entries before zipping
2231 (org-odt-write-manifest-file)
2233 (let ((xml-files '("mimetype" "META-INF/manifest.xml" "content.xml"
2234 "meta.xml"))
2235 (zipdir default-directory))
2236 (when (equal org-lparse-backend 'odt)
2237 (push "styles.xml" xml-files))
2238 (message "Switching to directory %s" (expand-file-name zipdir))
2240 ;; save all xml files
2241 (mapc (lambda (file)
2242 (with-current-buffer
2243 (find-file-noselect (expand-file-name file) t)
2244 ;; prettify output if needed
2245 (when org-export-odt-prettify-xml
2246 (indent-region (point-min) (point-max)))
2247 (save-buffer 0)))
2248 xml-files)
2250 (let* ((target-name (file-name-nondirectory target))
2251 (target-dir (file-name-directory target))
2252 (cmds `(("zip" "-mX0" ,target-name "mimetype")
2253 ("zip" "-rmTq" ,target-name "."))))
2254 (when (file-exists-p target)
2255 ;; FIXME: If the file is locked this throws a cryptic error
2256 (delete-file target))
2258 (let ((coding-system-for-write 'no-conversion) exitcode err-string)
2259 (message "Creating odt file...")
2260 (mapc
2261 (lambda (cmd)
2262 (message "Running %s" (mapconcat 'identity cmd " "))
2263 (setq err-string
2264 (with-output-to-string
2265 (setq exitcode
2266 (apply 'call-process (car cmd)
2267 nil standard-output nil (cdr cmd)))))
2268 (or (zerop exitcode)
2269 (ignore (message "%s" err-string))
2270 (error "Unable to create odt file (%S)" exitcode)))
2271 cmds))
2273 ;; move the file from outdir to target-dir
2274 (rename-file target-name target-dir)
2276 ;; kill all xml buffers
2277 (mapc (lambda (file)
2278 (kill-buffer
2279 (find-file-noselect (expand-file-name file zipdir) t)))
2280 xml-files)
2282 (delete-directory zipdir)))
2283 (message "Created %s" target)
2284 (set-buffer (find-file-noselect target t)))
2286 (defconst org-odt-manifest-file-entry-tag
2288 <manifest:file-entry manifest:media-type=\"%s\" manifest:full-path=\"%s\"%s/>")
2290 (defun org-odt-create-manifest-file-entry (&rest args)
2291 (push args org-odt-manifest-file-entries))
2293 (defun org-odt-write-manifest-file ()
2294 (make-directory "META-INF")
2295 (let ((manifest-file (expand-file-name "META-INF/manifest.xml")))
2296 (with-current-buffer
2297 (find-file-noselect manifest-file t)
2298 (insert
2299 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
2300 <manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"1.2\">\n")
2301 (mapc
2302 (lambda (file-entry)
2303 (let* ((version (nth 2 file-entry))
2304 (extra (if version
2305 (format " manifest:version=\"%s\"" version)
2306 "")))
2307 (insert
2308 (format org-odt-manifest-file-entry-tag
2309 (nth 0 file-entry) (nth 1 file-entry) extra))))
2310 org-odt-manifest-file-entries)
2311 (insert "\n</manifest:manifest>"))))
2313 (defun org-odt-update-meta-file (opt-plist)
2314 (let ((date (org-odt-format-date (plist-get opt-plist :date)))
2315 (author (or (plist-get opt-plist :author) ""))
2316 (email (plist-get opt-plist :email))
2317 (keywords (plist-get opt-plist :keywords))
2318 (description (plist-get opt-plist :description))
2319 (title (plist-get opt-plist :title)))
2320 (write-region
2321 (concat
2322 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
2323 <office:document-meta
2324 xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"
2325 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2326 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2327 xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"
2328 xmlns:ooo=\"http://openoffice.org/2004/office\"
2329 office:version=\"1.2\">
2330 <office:meta>" "\n"
2331 (org-odt-format-author)
2332 (org-odt-format-tags
2333 '("\n<meta:initial-creator>" . "</meta:initial-creator>") author)
2334 (org-odt-format-tags '("\n<dc:date>" . "</dc:date>") date)
2335 (org-odt-format-tags
2336 '("\n<meta:creation-date>" . "</meta:creation-date>") date)
2337 (org-odt-format-tags '("\n<meta:generator>" . "</meta:generator>")
2338 (when org-export-creator-info
2339 (format "Org-%s/Emacs-%s"
2340 org-version emacs-version)))
2341 (org-odt-format-tags '("\n<meta:keyword>" . "</meta:keyword>") keywords)
2342 (org-odt-format-tags '("\n<dc:subject>" . "</dc:subject>") description)
2343 (org-odt-format-tags '("\n<dc:title>" . "</dc:title>") title)
2344 "\n"
2345 " </office:meta>" "</office:document-meta>")
2346 nil (expand-file-name "meta.xml")))
2348 ;; create a manifest entry for meta.xml
2349 (org-odt-create-manifest-file-entry "text/xml" "meta.xml"))
2351 (defun org-odt-update-styles-file (opt-plist)
2352 ;; write styles file
2353 (let ((styles-file (plist-get opt-plist :odt-styles-file)))
2354 (org-odt-copy-styles-file (and styles-file
2355 (read (org-trim styles-file)))))
2357 ;; Update styles.xml - take care of outline numbering
2358 (with-current-buffer
2359 (find-file-noselect (expand-file-name "styles.xml") t)
2360 ;; Don't make automatic backup of styles.xml file. This setting
2361 ;; prevents the backed-up styles.xml file from being zipped in to
2362 ;; odt file. This is more of a hackish fix. Better alternative
2363 ;; would be to fix the zip command so that the output odt file
2364 ;; includes only the needed files and excludes any auto-generated
2365 ;; extra files like backups and auto-saves etc etc. Note that
2366 ;; currently the zip command zips up the entire temp directory so
2367 ;; that any auto-generated files created under the hood ends up in
2368 ;; the resulting odt file.
2369 (set (make-local-variable 'backup-inhibited) t)
2371 ;; Import local setting of `org-export-with-section-numbers'
2372 (org-lparse-bind-local-variables opt-plist)
2373 (org-odt-configure-outline-numbering
2374 (if org-export-with-section-numbers org-export-headline-levels 0)))
2376 ;; Write custom styles for source blocks
2377 (org-odt-insert-custom-styles-for-srcblocks
2378 (mapconcat
2379 (lambda (style)
2380 (format " %s\n" (cddr style)))
2381 hfy-user-sheet-assoc "")))
2383 (defun org-odt-write-mimetype-file (format)
2384 ;; create mimetype file
2385 (let ((mimetype
2386 (case format
2387 (odt "application/vnd.oasis.opendocument.text")
2388 (odf "application/vnd.oasis.opendocument.formula")
2389 (t (error "Unknown OpenDocument backend %S" org-lparse-backend)))))
2390 (write-region mimetype nil (expand-file-name "mimetype"))
2391 mimetype))
2393 (defun org-odt-finalize-outfile ()
2394 (org-odt-delete-empty-paragraphs))
2396 (defun org-odt-delete-empty-paragraphs ()
2397 (goto-char (point-min))
2398 (let ((open "<text:p[^>]*>")
2399 (close "</text:p>"))
2400 (while (re-search-forward (format "%s[ \r\n\t]*%s" open close) nil t)
2401 (replace-match ""))))
2403 (defcustom org-export-odt-convert-processes
2404 '(("BasicODConverter"
2405 ("soffice" "-norestore" "-invisible" "-headless"
2406 "\"macro:///BasicODConverter.Main.Convert(%I,%f,%O)\""))
2407 ("unoconv"
2408 ("unoconv" "-f" "%f" "-o" "%d" "%i")))
2409 "Specify a list of document converters and their usage.
2410 The converters in this list are offered as choices while
2411 customizing `org-export-odt-convert-process'.
2413 This variable is an alist where each element is of the
2414 form (CONVERTER-NAME CONVERTER-PROCESS). CONVERTER-NAME is name
2415 of the converter. CONVERTER-PROCESS specifies the command-line
2416 syntax of the converter and is of the form (CONVERTER-PROGRAM
2417 ARG1 ARG2 ...). CONVERTER-PROGRAM is the name of the executable.
2418 ARG1, ARG2 etc are command line options that are passed to
2419 CONVERTER-PROGRAM. Format specifiers can be used in the ARGs and
2420 they are interpreted as below:
2422 %i input file name in full
2423 %I input file name as a URL
2424 %f format of the output file
2425 %o output file name in full
2426 %O output file name as a URL
2427 %d output dir in full
2428 %D output dir as a URL."
2429 :group 'org-export-odt
2430 :type
2431 '(choice
2432 (const :tag "None" nil)
2433 (alist :tag "Converters"
2434 :key-type (string :tag "Converter Name")
2435 :value-type (group (cons (string :tag "Executable")
2436 (repeat (string :tag "Command line args")))))))
2438 (defcustom org-export-odt-convert-process nil
2439 "Use this converter to convert from \"odt\" format to other formats.
2440 During customization, the list of converter names are populated
2441 from `org-export-odt-convert-processes'."
2442 :group 'org-export-odt
2443 :type '(choice :convert-widget
2444 (lambda (w)
2445 (apply 'widget-convert (widget-type w)
2446 (eval (car (widget-get w :args)))))
2447 `((const :tag "None" nil)
2448 ,@(mapcar (lambda (c)
2449 `(const :tag ,(car c) ,(car c)))
2450 org-export-odt-convert-processes))))
2452 (defcustom org-export-odt-convert-capabilities
2453 '(("Text"
2454 ("odt" "ott" "doc" "rtf")
2455 (("pdf" "pdf") ("odt" "odt") ("xhtml" "html") ("rtf" "rtf")
2456 ("ott" "ott") ("doc" "doc") ("ooxml" "xml") ("html" "html")))
2457 ("Web"
2458 ("html" "xhtml") (("pdf" "pdf") ("odt" "txt") ("html" "html")))
2459 ("Spreadsheet"
2460 ("ods" "ots" "xls" "csv")
2461 (("pdf" "pdf") ("ots" "ots") ("html" "html") ("csv" "csv")
2462 ("ods" "ods") ("xls" "xls") ("xhtml" "xhtml") ("ooxml" "xml")))
2463 ("Presentation"
2464 ("odp" "otp" "ppt")
2465 (("pdf" "pdf") ("swf" "swf") ("odp" "odp") ("xhtml" "xml")
2466 ("otp" "otp") ("ppt" "ppt") ("odg" "odg") ("html" "html"))))
2467 "Specify input and output formats of `org-export-odt-convert-process'.
2468 More correctly, specify the set of input and output formats that
2469 the user is actually interested in.
2471 This variable is an alist where each element is of the
2472 form (DOCUMENT-CLASS INPUT-FMT-LIST OUTPUT-FMT-ALIST).
2473 INPUT-FMT-LIST is a list of INPUT-FMTs. OUTPUT-FMT-ALIST is an
2474 alist where each element is of the form (OUTPUT-FMT
2475 OUTPUT-FILE-EXTENSION).
2477 The variable is interpreted as follows:
2478 `org-export-odt-convert-process' can take any document that is in
2479 INPUT-FMT-LIST and produce any document that is in the
2480 OUTPUT-FMT-LIST. A document converted to OUTPUT-FMT will have
2481 OUTPUT-FILE-EXTENSION as the file name extension. OUTPUT-FMT
2482 serves dual purposes:
2483 - It is used for populating completion candidates during
2484 `org-export-odt-convert' commands.
2485 - It is used as the value of \"%f\" specifier in
2486 `org-export-odt-convert-process'.
2488 DOCUMENT-CLASS is used to group a set of file formats in
2489 INPUT-FMT-LIST in to a single class.
2491 Note that this variable inherently captures how LibreOffice based
2492 converters work. LibreOffice maps documents of various formats
2493 to classes like Text, Web, Spreadsheet, Presentation etc and
2494 allow document of a given class (irrespective of it's source
2495 format) to be converted to any of the export formats associated
2496 with that class.
2498 See default setting of this variable for an typical
2499 configuration."
2500 :group 'org-export-odt
2501 :type
2502 '(choice
2503 (const :tag "None" nil)
2504 (alist :key-type (string :tag "Document Class")
2505 :value-type
2506 (group (repeat :tag "Input formats" (string :tag "Input format"))
2507 (alist :tag "Output formats"
2508 :key-type (string :tag "Output format")
2509 :value-type
2510 (group (string :tag "Output file extension")))))))
2512 (declare-function org-create-math-formula "org"
2513 (latex-frag &optional mathml-file))
2515 ;;;###autoload
2516 (defun org-export-odt-convert (&optional in-file out-fmt prefix-arg)
2517 "Convert IN-FILE to format OUT-FMT using a command line converter.
2518 IN-FILE is the file to be converted. If unspecified, it defaults
2519 to variable `buffer-file-name'. OUT-FMT is the desired output
2520 format. Use `org-export-odt-convert-process' as the converter.
2521 If PREFIX-ARG is non-nil then the newly converted file is opened
2522 using `org-open-file'."
2523 (interactive
2524 (append (org-lparse-convert-read-params) current-prefix-arg))
2525 (org-lparse-do-convert in-file out-fmt prefix-arg))
2527 (defun org-odt-get (what &optional opt-plist)
2528 (case what
2529 (BACKEND 'odt)
2530 (EXPORT-DIR (org-export-directory :html opt-plist))
2531 (FILE-NAME-EXTENSION "odt")
2532 (EXPORT-BUFFER-NAME "*Org ODT Export*")
2533 (ENTITY-CONTROL org-odt-entity-control-callbacks-alist)
2534 (ENTITY-FORMAT org-odt-entity-format-callbacks-alist)
2535 (INIT-METHOD 'org-odt-init-outfile)
2536 (FINAL-METHOD 'org-odt-finalize-outfile)
2537 (SAVE-METHOD 'org-odt-save-as-outfile)
2538 (CONVERT-METHOD
2539 (and org-export-odt-convert-process
2540 (cadr (assoc-string org-export-odt-convert-process
2541 org-export-odt-convert-processes t))))
2542 (CONVERT-CAPABILITIES
2543 (and org-export-odt-convert-process
2544 (cadr (assoc-string org-export-odt-convert-process
2545 org-export-odt-convert-processes t))
2546 org-export-odt-convert-capabilities))
2547 (TOPLEVEL-HLEVEL 1)
2548 (SPECIAL-STRING-REGEXPS org-export-odt-special-string-regexps)
2549 (INLINE-IMAGES 'maybe)
2550 (INLINE-IMAGE-EXTENSIONS '("png" "jpeg" "jpg" "gif" "svg"))
2551 (PLAIN-TEXT-MAP '(("&" . "&amp;") ("<" . "&lt;") (">" . "&gt;")))
2552 (TABLE-FIRST-COLUMN-AS-LABELS nil)
2553 (FOOTNOTE-SEPARATOR (org-lparse-format 'FONTIFY "," 'superscript))
2554 (CODING-SYSTEM-FOR-WRITE 'utf-8)
2555 (CODING-SYSTEM-FOR-SAVE 'utf-8)
2556 (t (error "Unknown property: %s" what))))
2558 (defvar org-lparse-latex-fragment-fallback) ; set by org-do-lparse
2559 (defun org-export-odt-do-preprocess-latex-fragments ()
2560 "Convert LaTeX fragments to images."
2561 (let* ((latex-frag-opt (plist-get org-lparse-opt-plist :LaTeX-fragments))
2562 (latex-frag-opt ; massage the options
2563 (or (and (member latex-frag-opt '(mathjax t))
2564 (not (and (fboundp 'org-format-latex-mathml-available-p)
2565 (org-format-latex-mathml-available-p)))
2566 (prog1 org-lparse-latex-fragment-fallback
2567 (org-lparse-warn
2568 (concat
2569 "LaTeX to MathML converter not available. "
2570 (format "Using %S instead."
2571 org-lparse-latex-fragment-fallback)))))
2572 latex-frag-opt))
2573 cache-dir display-msg)
2574 (cond
2575 ((eq latex-frag-opt 'dvipng)
2576 (setq cache-dir "ltxpng/")
2577 (setq display-msg "Creating LaTeX image %s"))
2578 ((member latex-frag-opt '(mathjax t))
2579 (setq latex-frag-opt 'mathml)
2580 (setq cache-dir "ltxmathml/")
2581 (setq display-msg "Creating MathML formula %s")))
2582 (when (and org-current-export-file)
2583 (org-format-latex
2584 (concat cache-dir (file-name-sans-extension
2585 (file-name-nondirectory org-current-export-file)))
2586 org-current-export-dir nil display-msg
2587 nil nil latex-frag-opt))))
2589 (defadvice org-format-latex-as-mathml
2590 (after org-odt-protect-latex-fragment activate)
2591 "Encode LaTeX fragment as XML.
2592 Do this when translation to MathML fails."
2593 (when (or (not (> (length ad-return-value) 0))
2594 (get-text-property 0 'org-protected ad-return-value))
2595 (setq ad-return-value
2596 (org-propertize (org-odt-encode-plain-text (ad-get-arg 0))
2597 'org-protected t))))
2599 (defun org-export-odt-preprocess-latex-fragments ()
2600 (when (equal org-export-current-backend 'odt)
2601 (org-export-odt-do-preprocess-latex-fragments)))
2603 (defun org-export-odt-preprocess-label-references ()
2604 (goto-char (point-min))
2605 (let (label label-components category value pretty-label)
2606 (while (re-search-forward "\\\\ref{\\([^{}\n]+\\)}" nil t)
2607 (org-if-unprotected-at (match-beginning 1)
2608 (replace-match
2609 (let ((org-lparse-encode-pending t)
2610 (label (match-string 1)))
2611 ;; markup generated below is mostly an eye-candy. At
2612 ;; pre-processing stage, there is no information on which
2613 ;; entity a label reference points to. The actual markup
2614 ;; is generated as part of `org-odt-fixup-label-references'
2615 ;; which gets called at the fag end of export. By this
2616 ;; time we would have seen and collected all the label
2617 ;; definitions in `org-odt-entity-labels-alist'.
2618 (org-odt-format-tags
2619 '("<text:sequence-ref text:ref-name=\"%s\">" .
2620 "</text:sequence-ref>")
2621 "" (org-add-props label '(org-protected t)))) t t)))))
2623 ;; process latex fragments as part of
2624 ;; `org-export-preprocess-after-blockquote-hook'. Note that this hook
2625 ;; is the one that is closest and well before the call to
2626 ;; `org-export-attach-captions-and-attributes' in
2627 ;; `org-export-preprocess-string'. The above arrangement permits
2628 ;; captions, labels and attributes to be attached to png images
2629 ;; generated out of latex equations.
2630 (add-hook 'org-export-preprocess-after-blockquote-hook
2631 'org-export-odt-preprocess-latex-fragments)
2633 (defun org-export-odt-preprocess (parameters)
2634 (org-export-odt-preprocess-label-references))
2636 (declare-function archive-zip-extract "arc-mode.el" (archive name))
2637 (defun org-odt-zip-extract-one (archive member &optional target)
2638 (require 'arc-mode)
2639 (let* ((target (or target default-directory))
2640 (archive (expand-file-name archive))
2641 (archive-zip-extract
2642 (list "unzip" "-qq" "-o" "-d" target))
2643 exit-code command-output)
2644 (setq command-output
2645 (with-temp-buffer
2646 (setq exit-code (archive-zip-extract archive member))
2647 (buffer-string)))
2648 (unless (zerop exit-code)
2649 (message command-output)
2650 (error "Extraction failed"))))
2652 (defun org-odt-zip-extract (archive members &optional target)
2653 (when (atom members) (setq members (list members)))
2654 (mapc (lambda (member)
2655 (org-odt-zip-extract-one archive member target))
2656 members))
2658 (defun org-odt-copy-styles-file (&optional styles-file)
2659 ;; Non-availability of styles.xml is not a critical error. For now
2660 ;; throw an error purely for aesthetic reasons.
2661 (setq styles-file (or styles-file
2662 org-export-odt-styles-file
2663 (expand-file-name "OrgOdtStyles.xml"
2664 org-odt-styles-dir)
2665 (error "org-odt: Missing styles file?")))
2666 (cond
2667 ((listp styles-file)
2668 (let ((archive (nth 0 styles-file))
2669 (members (nth 1 styles-file)))
2670 (org-odt-zip-extract archive members)
2671 (mapc
2672 (lambda (member)
2673 (when (org-file-image-p member)
2674 (let* ((image-type (file-name-extension member))
2675 (media-type (format "image/%s" image-type)))
2676 (org-odt-create-manifest-file-entry media-type member))))
2677 members)))
2678 ((and (stringp styles-file) (file-exists-p styles-file))
2679 (let ((styles-file-type (file-name-extension styles-file)))
2680 (cond
2681 ((string= styles-file-type "xml")
2682 (copy-file styles-file "styles.xml" t))
2683 ((member styles-file-type '("odt" "ott"))
2684 (org-odt-zip-extract styles-file "styles.xml")))))
2686 (error (format "Invalid specification of styles.xml file: %S"
2687 org-export-odt-styles-file))))
2689 ;; create a manifest entry for styles.xml
2690 (org-odt-create-manifest-file-entry "text/xml" "styles.xml"))
2692 (defvar org-export-odt-factory-settings
2693 "d4328fb9d1b6cb211d4320ff546829f26700dc5e"
2694 "SHA1 hash of OrgOdtStyles.xml.")
2696 (defun org-odt-configure-outline-numbering (level)
2697 "Outline numbering is retained only upto LEVEL.
2698 To disable outline numbering pass a LEVEL of 0."
2699 (goto-char (point-min))
2700 (let ((regex
2701 "<text:outline-level-style\\([^>]*\\)text:level=\"\\([^\"]*\\)\"\\([^>]*\\)>")
2702 (replacement
2703 "<text:outline-level-style\\1text:level=\"\\2\" style:num-format=\"\">"))
2704 (while (re-search-forward regex nil t)
2705 (when (> (string-to-number (match-string 2)) level)
2706 (replace-match replacement t nil))))
2707 (save-buffer 0))
2709 ;;;###autoload
2710 (defun org-export-as-odf (latex-frag &optional odf-file)
2711 "Export LATEX-FRAG as OpenDocument formula file ODF-FILE.
2712 Use `org-create-math-formula' to convert LATEX-FRAG first to
2713 MathML. When invoked as an interactive command, use
2714 `org-latex-regexps' to infer LATEX-FRAG from currently active
2715 region. If no LaTeX fragments are found, prompt for it. Push
2716 MathML source to kill ring, if `org-export-copy-to-kill-ring' is
2717 non-nil."
2718 (interactive
2719 `(,(let (frag)
2720 (setq frag (and (setq frag (and (region-active-p)
2721 (buffer-substring (region-beginning)
2722 (region-end))))
2723 (loop for e in org-latex-regexps
2724 thereis (when (string-match (nth 1 e) frag)
2725 (match-string (nth 2 e) frag)))))
2726 (read-string "LaTeX Fragment: " frag nil frag))
2727 ,(let ((odf-filename (expand-file-name
2728 (concat
2729 (file-name-sans-extension
2730 (or (file-name-nondirectory buffer-file-name)))
2731 "." "odf")
2732 (file-name-directory buffer-file-name))))
2733 (read-file-name "ODF filename: " nil odf-filename nil
2734 (file-name-nondirectory odf-filename)))))
2735 (let* ((org-lparse-backend 'odf)
2736 org-lparse-opt-plist
2737 (filename (or odf-file
2738 (expand-file-name
2739 (concat
2740 (file-name-sans-extension
2741 (or (file-name-nondirectory buffer-file-name)))
2742 "." "odf")
2743 (file-name-directory buffer-file-name))))
2744 (buffer (find-file-noselect (org-odt-init-outfile filename)))
2745 (coding-system-for-write 'utf-8)
2746 (save-buffer-coding-system 'utf-8))
2747 (set-buffer buffer)
2748 (set-buffer-file-coding-system coding-system-for-write)
2749 (let ((mathml (org-create-math-formula latex-frag)))
2750 (unless mathml (error "No Math formula created"))
2751 (insert mathml)
2752 (or (org-export-push-to-kill-ring
2753 (upcase (symbol-name org-lparse-backend)))
2754 (message "Exporting... done")))
2755 (org-odt-save-as-outfile filename nil)))
2757 ;;;###autoload
2758 (defun org-export-as-odf-and-open ()
2759 "Export LaTeX fragment as OpenDocument formula and immediately open it.
2760 Use `org-export-as-odf' to read LaTeX fragment and OpenDocument
2761 formula file."
2762 (interactive)
2763 (org-lparse-and-open
2764 nil nil nil (call-interactively 'org-export-as-odf)))
2766 (provide 'org-odt)
2768 ;;; org-odt.el ends here