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