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