org-element: Correctly parse inlinetasks before first headline
[org-mode.git] / lisp / org-odt.el
blobad94a50829bbc41873bcd8c957a2858eb53e47b7
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 (defvar org-odt-section-count 0)
650 (defun org-odt-begin-section (style &optional name)
651 (setq name (or name (format "Section-%d" (incf org-odt-section-count))))
652 (org-lparse-insert-tag
653 "<text:section text:style-name=\"%s\" text:name=\"%s\">" style name))
655 (defun org-odt-end-section ()
656 (org-lparse-insert-tag "</text:section>"))
658 (defun org-odt-begin-paragraph (&optional style)
659 (org-lparse-insert-tag
660 "<text:p%s>" (org-odt-get-extra-attrs-for-paragraph-style style)))
662 (defun org-odt-end-paragraph ()
663 (org-lparse-insert-tag "</text:p>"))
665 (defun org-odt-get-extra-attrs-for-paragraph-style (style)
666 (let (style-name)
667 (setq style-name
668 (cond
669 ((stringp style) style)
670 ((symbolp style) (org-odt-get-style-name-for-entity
671 'paragraph style))))
672 (unless style-name
673 (error "Don't know how to handle paragraph style %s" style))
674 (format " text:style-name=\"%s\"" style-name)))
676 (defun org-odt-format-stylized-paragraph (style text)
677 (org-odt-format-tags
678 '("<text:p%s>" . "</text:p>") text
679 (org-odt-get-extra-attrs-for-paragraph-style style)))
681 (defvar org-lparse-opt-plist) ; bound during org-do-lparse
682 (defun org-odt-format-author (&optional author)
683 (when (setq author (or author (plist-get org-lparse-opt-plist :author)))
684 (org-odt-format-tags '("<dc:creator>" . "</dc:creator>") author)))
686 (defun org-odt-format-date (&optional org-ts fmt)
687 (save-match-data
688 (let* ((time
689 (and (stringp org-ts)
690 (string-match org-ts-regexp0 org-ts)
691 (apply 'encode-time
692 (org-fix-decoded-time
693 (org-parse-time-string (match-string 0 org-ts) t)))))
694 date)
695 (cond
696 (fmt (format-time-string fmt time))
697 (t (setq date (format-time-string "%Y-%m-%dT%H:%M:%S%z" time))
698 (format "%s:%s" (substring date 0 -2) (substring date -2)))))))
700 (defun org-odt-begin-annotation (&optional author date)
701 (org-lparse-insert-tag "<office:annotation>")
702 (when (setq author (org-odt-format-author author))
703 (insert author))
704 (insert (org-odt-format-tags
705 '("<dc:date>" . "</dc:date>")
706 (org-odt-format-date
707 (or date (plist-get org-lparse-opt-plist :date)))))
708 (org-lparse-begin-paragraph))
710 (defun org-odt-end-annotation ()
711 (org-lparse-insert-tag "</office:annotation>"))
713 (defun org-odt-begin-environment (style env-options-plist)
714 (case style
715 (annotation
716 (org-lparse-stash-save-paragraph-state)
717 (org-odt-begin-annotation (plist-get env-options-plist 'author)
718 (plist-get env-options-plist 'date)))
719 ((blockquote verse center quote)
720 (org-lparse-begin-paragraph style)
721 (list))
722 ((fixedwidth native)
723 (org-lparse-end-paragraph)
724 (list))
725 (t (error "Unknown environment %s" style))))
727 (defun org-odt-end-environment (style env-options-plist)
728 (case style
729 (annotation
730 (org-lparse-end-paragraph)
731 (org-odt-end-annotation)
732 (org-lparse-stash-pop-paragraph-state))
733 ((blockquote verse center quote)
734 (org-lparse-end-paragraph)
735 (list))
736 ((fixedwidth native)
737 (org-lparse-begin-paragraph)
738 (list))
739 (t (error "Unknown environment %s" style))))
741 (defvar org-lparse-list-stack) ; dynamically bound in org-do-lparse
742 (defvar org-odt-list-stack-stashed)
743 (defun org-odt-begin-list (ltype)
744 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
745 ltype))
746 (let* ((style-name (org-odt-get-style-name-for-entity 'list ltype))
747 (extra (concat (if (or org-lparse-list-table-p
748 (and (= 1 (length org-lparse-list-stack))
749 (null org-odt-list-stack-stashed)))
750 " text:continue-numbering=\"false\""
751 " text:continue-numbering=\"true\"")
752 (when style-name
753 (format " text:style-name=\"%s\"" style-name)))))
754 (case ltype
755 ((ordered unordered description)
756 (org-lparse-end-paragraph)
757 (org-lparse-insert-tag "<text:list%s>" extra))
758 (t (error "Unknown list type: %s" ltype)))))
760 (defun org-odt-end-list (ltype)
761 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
762 ltype))
763 (if ltype
764 (org-lparse-insert-tag "</text:list>")
765 (error "Unknown list type: %s" ltype)))
767 (defun org-odt-begin-list-item (ltype &optional arg headline)
768 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
769 ltype))
770 (case ltype
771 (ordered
772 (assert (not headline) t)
773 (let* ((counter arg) (extra ""))
774 (org-lparse-insert-tag (if (= (length org-lparse-list-stack)
775 (length org-odt-list-stack-stashed))
776 "<text:list-header>" "<text:list-item>"))
777 (org-lparse-begin-paragraph)))
778 (unordered
779 (let* ((id arg) (extra ""))
780 (org-lparse-insert-tag (if (= (length org-lparse-list-stack)
781 (length org-odt-list-stack-stashed))
782 "<text:list-header>" "<text:list-item>"))
783 (org-lparse-begin-paragraph)
784 (insert (if headline (org-odt-format-target headline id)
785 (org-odt-format-bookmark "" id)))))
786 (description
787 (assert (not headline) t)
788 (let ((term (or arg "(no term)")))
789 (insert
790 (org-odt-format-tags
791 '("<text:list-item>" . "</text:list-item>")
792 (org-odt-format-stylized-paragraph 'definition-term term)))
793 (org-lparse-begin-list-item 'unordered)
794 (org-lparse-begin-list 'description)
795 (org-lparse-begin-list-item 'unordered)))
796 (t (error "Unknown list type"))))
798 (defun org-odt-end-list-item (ltype)
799 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
800 ltype))
801 (case ltype
802 ((ordered unordered)
803 (org-lparse-insert-tag (if (= (length org-lparse-list-stack)
804 (length org-odt-list-stack-stashed))
805 (prog1 "</text:list-header>"
806 (setq org-odt-list-stack-stashed nil))
807 "</text:list-item>")))
808 (description
809 (org-lparse-end-list-item-1)
810 (org-lparse-end-list 'description)
811 (org-lparse-end-list-item-1))
812 (t (error "Unknown list type"))))
814 (defun org-odt-discontinue-list ()
815 (let ((stashed-stack org-lparse-list-stack))
816 (loop for list-type in stashed-stack
817 do (org-lparse-end-list-item-1 list-type)
818 (org-lparse-end-list list-type))
819 (setq org-odt-list-stack-stashed stashed-stack)))
821 (defun org-odt-continue-list ()
822 (setq org-odt-list-stack-stashed (nreverse org-odt-list-stack-stashed))
823 (loop for list-type in org-odt-list-stack-stashed
824 do (org-lparse-begin-list list-type)
825 (org-lparse-begin-list-item list-type)))
827 ;; Following variables are let bound when table emission is in
828 ;; progress. See org-lparse.el.
829 (defvar org-lparse-table-begin-marker)
830 (defvar org-lparse-table-ncols)
831 (defvar org-lparse-table-rowgrp-open)
832 (defvar org-lparse-table-rownum)
833 (defvar org-lparse-table-cur-rowgrp-is-hdr)
834 (defvar org-lparse-table-is-styled)
835 (defvar org-lparse-table-rowgrp-info)
836 (defvar org-lparse-table-colalign-vector)
838 (defvar org-odt-table-style nil
839 "Table style specified by \"#+ATTR_ODT: <style-name>\" line.
840 This is set during `org-odt-begin-table'.")
842 (defvar org-odt-table-style-spec nil
843 "Entry for `org-odt-table-style' in `org-export-odt-table-styles'.")
845 (defcustom org-export-odt-table-styles
846 '(("OrgEquation" "OrgEquation"
847 ((use-first-column-styles . t)
848 (use-last-column-styles . t))))
849 "Specify how Table Styles should be derived from a Table Template.
850 This is a list where each element is of the
851 form (TABLE-STYLE-NAME TABLE-TEMPLATE-NAME TABLE-CELL-OPTIONS).
853 TABLE-STYLE-NAME is the style associated with the table through
854 `org-odt-table-style'.
856 TABLE-TEMPLATE-NAME is a set of - upto 9 - automatic
857 TABLE-CELL-STYLE-NAMEs and PARAGRAPH-STYLE-NAMEs (as defined
858 below) that is included in
859 `org-export-odt-content-template-file'.
861 TABLE-CELL-STYLE-NAME := TABLE-TEMPLATE-NAME + TABLE-CELL-TYPE +
862 \"TableCell\"
863 PARAGRAPH-STYLE-NAME := TABLE-TEMPLATE-NAME + TABLE-CELL-TYPE +
864 \"TableParagraph\"
865 TABLE-CELL-TYPE := \"FirstRow\" | \"LastColumn\" |
866 \"FirstRow\" | \"LastRow\" |
867 \"EvenRow\" | \"OddRow\" |
868 \"EvenColumn\" | \"OddColumn\" | \"\"
869 where \"+\" above denotes string concatenation.
871 TABLE-CELL-OPTIONS is an alist where each element is of the
872 form (TABLE-CELL-STYLE-SELECTOR . ON-OR-OFF).
873 TABLE-CELL-STYLE-SELECTOR := `use-first-row-styles' |
874 `use-last-row-styles' |
875 `use-first-column-styles' |
876 `use-last-column-styles' |
877 `use-banding-rows-styles' |
878 `use-banding-columns-styles' |
879 `use-first-row-styles'
880 ON-OR-OFF := `t' | `nil'
882 For example, with the following configuration
884 \(setq org-export-odt-table-styles
885 '\(\(\"TableWithHeaderRowsAndColumns\" \"Custom\"
886 \(\(use-first-row-styles . t\)
887 \(use-first-column-styles . t\)\)\)
888 \(\"TableWithHeaderColumns\" \"Custom\"
889 \(\(use-first-column-styles . t\)\)\)\)\)
891 1. A table associated with \"TableWithHeaderRowsAndColumns\"
892 style will use the following table-cell styles -
893 \"CustomFirstRowTableCell\", \"CustomFirstColumnTableCell\",
894 \"CustomTableCell\" and the following paragraph styles
895 \"CustomFirstRowTableParagraph\",
896 \"CustomFirstColumnTableParagraph\", \"CustomTableParagraph\"
897 as appropriate.
899 2. A table associated with \"TableWithHeaderColumns\" style will
900 use the following table-cell styles -
901 \"CustomFirstColumnTableCell\", \"CustomTableCell\" and the
902 following paragraph styles
903 \"CustomFirstColumnTableParagraph\", \"CustomTableParagraph\"
904 as appropriate..
906 Note that TABLE-TEMPLATE-NAME corresponds to the
907 \"<table:table-template>\" elements contained within
908 \"<office:styles>\". The entries (TABLE-STYLE-NAME
909 TABLE-TEMPLATE-NAME TABLE-CELL-OPTIONS) correspond to
910 \"table:template-name\" and \"table:use-first-row-styles\" etc
911 attributes of \"<table:table>\" element. Refer ODF-1.2
912 specification for more information. Also consult the
913 implementation filed under `org-odt-get-table-cell-styles'.
915 The TABLE-STYLE-NAME \"OrgEquation\" is used internally for
916 formatting of numbered display equations. Do not delete this
917 style from the list."
918 :group 'org-export-odt
919 :type '(choice
920 (const :tag "None" nil)
921 (repeat :tag "Table Styles"
922 (list :tag "Table Style Specification"
923 (string :tag "Table Style Name")
924 (string :tag "Table Template Name")
925 (alist :options (use-first-row-styles
926 use-last-row-styles
927 use-first-column-styles
928 use-last-column-styles
929 use-banding-rows-styles
930 use-banding-columns-styles)
931 :key-type symbol
932 :value-type (const :tag "True" t))))))
934 (defvar org-odt-table-indentedp nil)
935 (defun org-odt-begin-table (caption label attributes)
936 (setq org-odt-table-indentedp (not (null org-lparse-list-stack)))
937 (when org-odt-table-indentedp
938 ;; Within the Org file, the table is appearing within a list item.
939 ;; OpenDocument doesn't allow table to appear within list items.
940 ;; Temporarily terminate the list, emit the table and then
941 ;; re-continue the list.
942 (org-odt-discontinue-list)
943 ;; Put the Table in an indented section.
944 (let ((level (length org-odt-list-stack-stashed)))
945 (org-odt-begin-section (format "OrgIndentedSection-Level-%d" level))))
947 (setq org-odt-table-style attributes)
948 (setq org-odt-table-style-spec
949 (assoc org-odt-table-style org-export-odt-table-styles))
950 (when label
951 (insert
952 (org-odt-format-stylized-paragraph
953 'table (org-odt-format-entity-caption label caption "__Table__"))))
954 (org-lparse-insert-tag
955 "<table:table table:name=\"%s\" table:style-name=\"%s\">"
956 (or label "") (or (nth 1 org-odt-table-style-spec) "OrgTable"))
957 (setq org-lparse-table-begin-marker (point)))
959 (defvar org-lparse-table-colalign-info)
960 (defun org-odt-end-table ()
961 (goto-char org-lparse-table-begin-marker)
962 (loop for level from 0 below org-lparse-table-ncols
963 do (let* ((col-cookie (and org-lparse-table-is-styled
964 (cdr (assoc (1+ level)
965 org-lparse-table-colalign-info))))
966 (extra-columns (or (nth 1 col-cookie) 0)))
967 (dotimes (i (1+ extra-columns))
968 (insert
969 (org-odt-format-tags
970 "<table:table-column table:style-name=\"%sColumn\"/>"
971 "" (or (nth 1 org-odt-table-style-spec) "OrgTable"))))
972 (insert "\n")))
973 ;; fill style attributes for table cells
974 (when org-lparse-table-is-styled
975 (while (re-search-forward "@@\\(table-cell:p\\|table-cell:style-name\\)@@\\([0-9]+\\)@@\\([0-9]+\\)@@" nil t)
976 (let* ((spec (match-string 1))
977 (r (string-to-number (match-string 2)))
978 (c (string-to-number (match-string 3)))
979 (cell-styles (org-odt-get-table-cell-styles
980 r c org-odt-table-style-spec))
981 (table-cell-style (car cell-styles))
982 (table-cell-paragraph-style (cdr cell-styles)))
983 (cond
984 ((equal spec "table-cell:p")
985 (replace-match table-cell-paragraph-style t t))
986 ((equal spec "table-cell:style-name")
987 (replace-match table-cell-style t t))))))
988 (goto-char (point-max))
989 (org-lparse-insert-tag "</table:table>")
990 (when org-odt-table-indentedp
991 (org-odt-end-section)
992 (org-odt-continue-list)))
994 (defun org-odt-begin-table-rowgroup (&optional is-header-row)
995 (when org-lparse-table-rowgrp-open
996 (org-lparse-end 'TABLE-ROWGROUP))
997 (org-lparse-insert-tag (if is-header-row
998 "<table:table-header-rows>"
999 "<table:table-rows>"))
1000 (setq org-lparse-table-rowgrp-open t)
1001 (setq org-lparse-table-cur-rowgrp-is-hdr is-header-row))
1003 (defun org-odt-end-table-rowgroup ()
1004 (when org-lparse-table-rowgrp-open
1005 (setq org-lparse-table-rowgrp-open nil)
1006 (org-lparse-insert-tag
1007 (if org-lparse-table-cur-rowgrp-is-hdr
1008 "</table:table-header-rows>" "</table:table-rows>"))))
1010 (defun org-odt-format-table-row (row)
1011 (org-odt-format-tags
1012 '("<table:table-row>" . "</table:table-row>") row))
1014 (defun org-odt-get-table-cell-styles (r c &optional style-spec)
1015 "Retrieve styles applicable to a table cell.
1016 R and C are (zero-based) row and column numbers of the table
1017 cell. STYLE-SPEC is an entry in `org-export-odt-table-styles'
1018 applicable to the current table. It is `nil' if the table is not
1019 associated with any style attributes.
1021 Return a cons of (TABLE-CELL-STYLE-NAME . PARAGRAPH-STYLE-NAME).
1023 When STYLE-SPEC is nil, style the table cell the conventional way
1024 - choose cell borders based on row and column groupings and
1025 choose paragraph alignment based on `org-col-cookies' text
1026 property. See also
1027 `org-odt-get-paragraph-style-cookie-for-table-cell'.
1029 When STYLE-SPEC is non-nil, ignore the above cookie and return
1030 styles congruent with the ODF-1.2 specification."
1031 (cond
1032 (style-spec
1034 ;; LibreOffice - particularly the Writer - honors neither table
1035 ;; templates nor custom table-cell styles. Inorder to retain
1036 ;; inter-operability with LibreOffice, only automatic styles are
1037 ;; used for styling of table-cells. The current implementation is
1038 ;; congruent with ODF-1.2 specification and hence is
1039 ;; future-compatible.
1041 ;; Additional Note: LibreOffice's AutoFormat facility for tables -
1042 ;; which recognizes as many as 16 different cell types - is much
1043 ;; richer. Unfortunately it is NOT amenable to easy configuration
1044 ;; by hand.
1046 (let* ((template-name (nth 1 style-spec))
1047 (cell-style-selectors (nth 2 style-spec))
1048 (cell-type
1049 (cond
1050 ((and (cdr (assoc 'use-first-column-styles cell-style-selectors))
1051 (= c 0)) "FirstColumn")
1052 ((and (cdr (assoc 'use-last-column-styles cell-style-selectors))
1053 (= c (1- org-lparse-table-ncols))) "LastColumn")
1054 ((and (cdr (assoc 'use-first-row-styles cell-style-selectors))
1055 (= r 0)) "FirstRow")
1056 ((and (cdr (assoc 'use-last-row-styles cell-style-selectors))
1057 (= r org-lparse-table-rownum))
1058 "LastRow")
1059 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
1060 (= (% r 2) 1)) "EvenRow")
1061 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
1062 (= (% r 2) 0)) "OddRow")
1063 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
1064 (= (% c 2) 1)) "EvenColumn")
1065 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
1066 (= (% c 2) 0)) "OddColumn")
1067 (t ""))))
1068 (cons
1069 (concat template-name cell-type "TableCell")
1070 (concat template-name cell-type "TableParagraph"))))
1072 (cons
1073 (concat
1074 "OrgTblCell"
1075 (cond
1076 ((= r 0) "T")
1077 ((eq (cdr (assoc r org-lparse-table-rowgrp-info)) :start) "T")
1078 (t ""))
1079 (when (= r org-lparse-table-rownum) "B")
1080 (cond
1081 ((= c 0) "")
1082 ((or (memq (nth c org-table-colgroup-info) '(:start :startend))
1083 (memq (nth (1- c) org-table-colgroup-info) '(:end :startend))) "L")
1084 (t "")))
1085 (capitalize (aref org-lparse-table-colalign-vector c))))))
1087 (defun org-odt-get-paragraph-style-cookie-for-table-cell (r c)
1088 (concat
1089 (and (not org-odt-table-style-spec)
1090 (cond
1091 (org-lparse-table-cur-rowgrp-is-hdr "OrgTableHeading")
1092 ((and (= c 0) (org-lparse-get 'TABLE-FIRST-COLUMN-AS-LABELS))
1093 "OrgTableHeading")
1094 (t "OrgTableContents")))
1095 (and org-lparse-table-is-styled
1096 (format "@@table-cell:p@@%03d@@%03d@@" r c))))
1098 (defun org-odt-get-style-name-cookie-for-table-cell (r c)
1099 (when org-lparse-table-is-styled
1100 (format "@@table-cell:style-name@@%03d@@%03d@@" r c)))
1102 (defun org-odt-format-table-cell (data r c horiz-span)
1103 (concat
1104 (let* ((paragraph-style-cookie
1105 (org-odt-get-paragraph-style-cookie-for-table-cell r c))
1106 (style-name-cookie
1107 (org-odt-get-style-name-cookie-for-table-cell r c))
1108 (extra (and style-name-cookie
1109 (format " table:style-name=\"%s\"" style-name-cookie)))
1110 (extra (concat extra
1111 (and (> horiz-span 0)
1112 (format " table:number-columns-spanned=\"%d\""
1113 (1+ horiz-span))))))
1114 (org-odt-format-tags
1115 '("<table:table-cell%s>" . "</table:table-cell>")
1116 (if org-lparse-list-table-p data
1117 (org-odt-format-stylized-paragraph paragraph-style-cookie data)) extra))
1118 (let (s)
1119 (dotimes (i horiz-span)
1120 (setq s (concat s "\n<table:covered-table-cell/>"))) s)
1121 "\n"))
1123 (defun org-odt-begin-footnote-definition (n)
1124 (org-lparse-begin-paragraph 'footnote))
1126 (defun org-odt-end-footnote-definition (n)
1127 (org-lparse-end-paragraph))
1129 (defun org-odt-begin-toc (lang-specific-heading max-level)
1130 (insert
1131 (format "
1132 <text:table-of-content text:style-name=\"Sect2\" text:protected=\"true\" text:name=\"Table of Contents1\">
1133 <text:table-of-content-source text:outline-level=\"%d\">
1134 <text:index-title-template text:style-name=\"Contents_20_Heading\">%s</text:index-title-template>
1135 " max-level lang-specific-heading))
1136 (loop for level from 1 upto 10
1137 do (insert (format
1139 <text:table-of-content-entry-template text:outline-level=\"%d\" text:style-name=\"Contents_20_%d\">
1140 <text:index-entry-link-start text:style-name=\"Internet_20_link\"/>
1141 <text:index-entry-chapter/>
1142 <text:index-entry-text/>
1143 <text:index-entry-link-end/>
1144 </text:table-of-content-entry-template>
1145 " level level)))
1147 (insert
1148 (format "
1149 </text:table-of-content-source>
1151 <text:index-body>
1152 <text:index-title text:style-name=\"Sect1\" text:name=\"Table of Contents1_Head\">
1153 <text:p text:style-name=\"Contents_20_Heading\">%s</text:p>
1154 </text:index-title>
1155 " lang-specific-heading)))
1157 (defun org-odt-end-toc ()
1158 (insert "
1159 </text:index-body>
1160 </text:table-of-content>
1163 (defun org-odt-format-toc-entry (snumber todo headline tags href)
1164 (setq headline (concat
1165 (and org-export-with-section-numbers
1166 (concat snumber ". "))
1167 headline
1168 (and tags
1169 (concat
1170 (org-lparse-format 'SPACES 3)
1171 (org-lparse-format 'FONTIFY tags "tag")))))
1172 (when todo
1173 (setq headline (org-lparse-format 'FONTIFY headline "todo")))
1175 (let ((org-odt-suppress-xref t))
1176 (org-odt-format-link headline (concat "#" href))))
1178 (defun org-odt-format-toc-item (toc-entry level org-last-level)
1179 (let ((style (format "Contents_20_%d"
1180 (+ level (or (org-lparse-get 'TOPLEVEL-HLEVEL) 1) -1))))
1181 (insert "\n" (org-odt-format-stylized-paragraph style toc-entry) "\n")))
1183 ;; Following variable is let bound during 'ORG-LINK callback. See
1184 ;; org-html.el
1185 (defvar org-lparse-link-description-is-image nil)
1186 (defun org-odt-format-link (desc href &optional attr)
1187 (cond
1188 ((and (= (string-to-char href) ?#) (not org-odt-suppress-xref))
1189 (setq href (concat org-export-odt-bookmark-prefix (substring href 1)))
1190 (let ((xref-format "text"))
1191 (when (numberp desc)
1192 (setq desc (format "%d" desc) xref-format "number"))
1193 (org-odt-format-tags
1194 '("<text:bookmark-ref text:reference-format=\"%s\" text:ref-name=\"%s\">" .
1195 "</text:bookmark-ref>")
1196 desc xref-format href)))
1197 (org-lparse-link-description-is-image
1198 (org-odt-format-tags
1199 '("<draw:a xlink:type=\"simple\" xlink:href=\"%s\" %s>" . "</draw:a>")
1200 desc href (or attr "")))
1202 (org-odt-format-tags
1203 '("<text:a xlink:type=\"simple\" xlink:href=\"%s\" %s>" . "</text:a>")
1204 desc href (or attr "")))))
1206 (defun org-odt-format-spaces (n)
1207 (cond
1208 ((= n 1) " ")
1209 ((> n 1) (concat
1210 " " (org-odt-format-tags "<text:s text:c=\"%d\"/>" "" (1- n))))
1211 (t "")))
1213 (defun org-odt-format-tabs (&optional n)
1214 (let ((tab "<text:tab/>")
1215 (n (or n 1)))
1216 (insert tab)))
1218 (defun org-odt-format-line-break ()
1219 (org-odt-format-tags "<text:line-break/>" ""))
1221 (defun org-odt-format-horizontal-line ()
1222 (org-odt-format-stylized-paragraph 'horizontal-line ""))
1224 (defun org-odt-encode-plain-text (line &optional no-whitespace-filling)
1225 (setq line (org-xml-encode-plain-text line))
1226 (if no-whitespace-filling line
1227 (org-odt-fill-tabs-and-spaces line)))
1229 (defun org-odt-format-line (line)
1230 (case org-lparse-dyn-current-environment
1231 (fixedwidth (concat
1232 (org-odt-format-stylized-paragraph
1233 'fixedwidth (org-odt-encode-plain-text line)) "\n"))
1234 (t (concat line "\n"))))
1236 (defun org-odt-format-comment (fmt &rest args)
1237 (let ((comment (apply 'format fmt args)))
1238 (format "\n<!-- %s -->\n" comment)))
1240 (defun org-odt-format-org-entity (wd)
1241 (org-entity-get-representation wd 'utf8))
1243 (defun org-odt-fill-tabs-and-spaces (line)
1244 (replace-regexp-in-string
1245 "\\([\t]\\|\\([ ]+\\)\\)" (lambda (s)
1246 (cond
1247 ((string= s "\t") (org-odt-format-tabs))
1248 (t (org-odt-format-spaces (length s))))) line))
1250 (defcustom org-export-odt-fontify-srcblocks t
1251 "Specify whether or not source blocks need to be fontified.
1252 Turn this option on if you want to colorize the source code
1253 blocks in the exported file. For colorization to work, you need
1254 to make available an enhanced version of `htmlfontify' library."
1255 :type 'boolean
1256 :group 'org-export-odt)
1258 (defun org-odt-format-source-line-with-line-number-and-label
1259 (line rpllbl num fontifier par-style)
1261 (let ((keep-label (not (numberp rpllbl)))
1262 (ref (org-find-text-property-in-string 'org-coderef line)))
1263 (setq line (concat line (and keep-label ref (format "(%s)" ref))))
1264 (setq line (funcall fontifier line))
1265 (when ref
1266 (setq line (org-odt-format-target line (concat "coderef-" ref))))
1267 (setq line (org-odt-format-stylized-paragraph par-style line))
1268 (if (not num) line
1269 (org-odt-format-tags '("<text:list-item>" . "</text:list-item>") line))))
1271 (defun org-odt-format-source-code-or-example-plain
1272 (lines lang caption textareap cols rows num cont rpllbl fmt)
1273 "Format source or example blocks much like fixedwidth blocks.
1274 Use this when `org-export-odt-fontify-srcblocks' option is turned
1275 off."
1276 (let* ((lines (org-split-string lines "[\r\n]"))
1277 (line-count (length lines))
1278 (i 0))
1279 (mapconcat
1280 (lambda (line)
1281 (incf i)
1282 (org-odt-format-source-line-with-line-number-and-label
1283 line rpllbl num 'org-odt-encode-plain-text
1284 (if (= i line-count) "OrgFixedWidthBlockLastLine"
1285 "OrgFixedWidthBlock")))
1286 lines "\n")))
1288 (defvar org-src-block-paragraph-format
1289 "<style:style style:name=\"OrgSrcBlock\" style:family=\"paragraph\" style:parent-style-name=\"Preformatted_20_Text\">
1290 <style:paragraph-properties fo:background-color=\"%s\" fo:padding=\"0.049cm\" fo:border=\"0.51pt solid #000000\" style:shadow=\"none\">
1291 <style:background-image/>
1292 </style:paragraph-properties>
1293 <style:text-properties fo:color=\"%s\"/>
1294 </style:style>"
1295 "Custom paragraph style for colorized source and example blocks.
1296 This style is much the same as that of \"OrgFixedWidthBlock\"
1297 except that the foreground and background colors are set
1298 according to the default face identified by the `htmlfontify'.")
1300 (defvar hfy-optimisations)
1301 (declare-function hfy-face-to-style "htmlfontify" (fn))
1302 (declare-function hfy-face-or-def-to-name "htmlfontify" (fn))
1304 (defun org-odt-hfy-face-to-css (fn)
1305 "Create custom style for face FN.
1306 When FN is the default face, use it's foreground and background
1307 properties to create \"OrgSrcBlock\" paragraph style. Otherwise
1308 use it's color attribute to create a character style whose name
1309 is obtained from FN. Currently all attributes of FN other than
1310 color are ignored.
1312 The style name for a face FN is derived using the following
1313 operations on the face name in that order - de-dash, CamelCase
1314 and prefix with \"OrgSrc\". For example,
1315 `font-lock-function-name-face' is associated with
1316 \"OrgSrcFontLockFunctionNameFace\"."
1317 (let* ((css-list (hfy-face-to-style fn))
1318 (style-name ((lambda (fn)
1319 (concat "OrgSrc"
1320 (mapconcat
1321 'capitalize (split-string
1322 (hfy-face-or-def-to-name fn) "-")
1323 ""))) fn))
1324 (color-val (cdr (assoc "color" css-list)))
1325 (background-color-val (cdr (assoc "background" css-list)))
1326 (style (and org-export-odt-create-custom-styles-for-srcblocks
1327 (cond
1328 ((eq fn 'default)
1329 (format org-src-block-paragraph-format
1330 background-color-val color-val))
1332 (format
1334 <style:style style:name=\"%s\" style:family=\"text\">
1335 <style:text-properties fo:color=\"%s\"/>
1336 </style:style>" style-name color-val))))))
1337 (cons style-name style)))
1339 (defun org-odt-insert-custom-styles-for-srcblocks (styles)
1340 "Save STYLES used for colorizing of source blocks.
1341 Update styles.xml with styles that were collected as part of
1342 `org-odt-hfy-face-to-css' callbacks."
1343 (when styles
1344 (with-current-buffer
1345 (find-file-noselect (expand-file-name "styles.xml") t)
1346 (goto-char (point-min))
1347 (when (re-search-forward "</office:styles>" nil t)
1348 (goto-char (match-beginning 0))
1349 (insert "\n<!-- Org Htmlfontify Styles -->\n" styles "\n")))))
1351 (defun org-odt-format-source-code-or-example-colored
1352 (lines lang caption textareap cols rows num cont rpllbl fmt)
1353 "Format source or example blocks using `htmlfontify-string'.
1354 Use this routine when `org-export-odt-fontify-srcblocks' option
1355 is turned on."
1356 (let* ((lang-m (and lang (or (cdr (assoc lang org-src-lang-modes)) lang)))
1357 (mode (and lang-m (intern (concat (if (symbolp lang-m)
1358 (symbol-name lang-m)
1359 lang-m) "-mode"))))
1360 (org-inhibit-startup t)
1361 (org-startup-folded nil)
1362 (lines (with-temp-buffer
1363 (insert lines)
1364 (if (functionp mode) (funcall mode) (fundamental-mode))
1365 (font-lock-fontify-buffer)
1366 (buffer-string)))
1367 (hfy-html-quote-regex "\\([<\"&> ]\\)")
1368 (hfy-html-quote-map '(("\"" "&quot;")
1369 ("<" "&lt;")
1370 ("&" "&amp;")
1371 (">" "&gt;")
1372 (" " "<text:s/>")
1373 (" " "<text:tab/>")))
1374 (hfy-face-to-css 'org-odt-hfy-face-to-css)
1375 (hfy-optimisations-1 (copy-seq hfy-optimisations))
1376 (hfy-optimisations (add-to-list 'hfy-optimisations-1
1377 'body-text-only))
1378 (hfy-begin-span-handler
1379 (lambda (style text-block text-id text-begins-block-p)
1380 (insert (format "<text:span text:style-name=\"%s\">" style))))
1381 (hfy-end-span-handler (lambda nil (insert "</text:span>"))))
1382 (when (fboundp 'htmlfontify-string)
1383 (let* ((lines (org-split-string lines "[\r\n]"))
1384 (line-count (length lines))
1385 (i 0))
1386 (mapconcat
1387 (lambda (line)
1388 (incf i)
1389 (org-odt-format-source-line-with-line-number-and-label
1390 line rpllbl num 'htmlfontify-string
1391 (if (= i line-count) "OrgSrcBlockLastLine" "OrgSrcBlock")))
1392 lines "\n")))))
1394 (defun org-odt-format-source-code-or-example (lines lang caption textareap
1395 cols rows num cont
1396 rpllbl fmt)
1397 "Format source or example blocks for export.
1398 Use `org-odt-format-source-code-or-example-plain' or
1399 `org-odt-format-source-code-or-example-colored' depending on the
1400 value of `org-export-odt-fontify-srcblocks."
1401 (setq lines (org-export-number-lines
1402 lines 0 0 num cont rpllbl fmt 'preprocess)
1403 lines (funcall
1404 (or (and org-export-odt-fontify-srcblocks
1405 (or (featurep 'htmlfontify)
1406 ;; htmlfontify.el was introduced in Emacs 23.2
1407 ;; So load it with some caution
1408 (require 'htmlfontify nil t))
1409 (fboundp 'htmlfontify-string)
1410 'org-odt-format-source-code-or-example-colored)
1411 'org-odt-format-source-code-or-example-plain)
1412 lines lang caption textareap cols rows num cont rpllbl fmt))
1413 (if (not num) lines
1414 (let ((extra (format " text:continue-numbering=\"%s\""
1415 (if cont "true" "false"))))
1416 (org-odt-format-tags
1417 '("<text:list text:style-name=\"OrgSrcBlockNumberedLine\"%s>"
1418 . "</text:list>") lines extra))))
1420 (defun org-odt-remap-stylenames (style-name)
1422 (cdr (assoc style-name '(("timestamp-wrapper" . "OrgTimestampWrapper")
1423 ("timestamp" . "OrgTimestamp")
1424 ("timestamp-kwd" . "OrgTimestampKeyword")
1425 ("tag" . "OrgTag")
1426 ("todo" . "OrgTodo")
1427 ("done" . "OrgDone")
1428 ("target" . "OrgTarget"))))
1429 style-name))
1431 (defun org-odt-format-fontify (text style &optional id)
1432 (let* ((style-name
1433 (cond
1434 ((stringp style)
1435 (org-odt-remap-stylenames style))
1436 ((symbolp style)
1437 (org-odt-get-style-name-for-entity 'character style))
1438 ((listp style)
1439 (assert (< 1 (length style)))
1440 (let ((parent-style (pop style)))
1441 (mapconcat (lambda (s)
1442 ;; (assert (stringp s) t)
1443 (org-odt-remap-stylenames s)) style "")
1444 (org-odt-remap-stylenames parent-style)))
1445 (t (error "Don't how to handle style %s" style)))))
1446 (org-odt-format-tags
1447 '("<text:span text:style-name=\"%s\">" . "</text:span>")
1448 text style-name)))
1450 (defun org-odt-relocate-relative-path (path dir)
1451 (if (file-name-absolute-p path) path
1452 (file-relative-name (expand-file-name path dir)
1453 (expand-file-name "eyecandy" dir))))
1455 (defun org-odt-format-inline-image (thefile)
1456 (let* ((thelink (if (file-name-absolute-p thefile) thefile
1457 (org-xml-format-href
1458 (org-odt-relocate-relative-path
1459 thefile org-current-export-file))))
1460 (href
1461 (org-odt-format-tags
1462 "<draw:image xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>" ""
1463 (if org-export-odt-embed-images
1464 (org-odt-copy-image-file thefile) thelink))))
1465 (org-export-odt-format-image thefile href)))
1467 (defun org-export-odt-format-formula (src href &optional embed-as)
1468 "Create image tag with source and attributes."
1469 (save-match-data
1470 (let* ((caption (org-find-text-property-in-string 'org-caption src))
1471 (caption (and caption (org-xml-format-desc caption)))
1472 (label (org-find-text-property-in-string 'org-label src))
1473 (latex-frag (org-find-text-property-in-string 'org-latex-src src))
1474 (embed-as (or embed-as
1475 (and latex-frag
1476 (org-find-text-property-in-string
1477 'org-latex-src-embed-type src))
1478 (if (or caption label) 'paragraph 'character)))
1479 width height)
1480 (when latex-frag
1481 (setq href (org-propertize href :title "LaTeX Fragment"
1482 :description latex-frag)))
1483 (cond
1484 ((eq embed-as 'character)
1485 (org-odt-format-entity "InlineFormula" href width height))
1487 (org-lparse-end-paragraph)
1488 (org-lparse-insert-list-table
1489 `((,(org-odt-format-entity
1490 (if caption "CaptionedDisplayFormula" "DisplayFormula")
1491 href width height :caption caption :label nil)
1492 ,(if (not label) ""
1493 (org-odt-format-entity-caption label nil "__MathFormula__"))))
1494 nil nil nil "OrgEquation" nil '((1 "c" 8) (2 "c" 1)))
1495 (throw 'nextline nil))))))
1497 (defvar org-odt-embedded-formulas-count 0)
1498 (defun org-odt-copy-formula-file (path)
1499 "Returns the internal name of the file"
1500 (let* ((src-file (expand-file-name
1501 path (file-name-directory org-current-export-file)))
1502 (target-dir (format "Formula-%04d/"
1503 (incf org-odt-embedded-formulas-count)))
1504 (target-file (concat target-dir "content.xml")))
1505 (when (not org-lparse-to-buffer)
1506 (message "Embedding %s as %s ..."
1507 (substring-no-properties path) target-file)
1509 (make-directory target-dir)
1510 (org-odt-create-manifest-file-entry
1511 "application/vnd.oasis.opendocument.formula" target-dir "1.2")
1513 (case (org-odt-is-formula-link-p src-file)
1514 (mathml
1515 (copy-file src-file target-file 'overwrite))
1516 (odf
1517 (org-odt-zip-extract-one src-file "content.xml" target-dir))
1519 (error "%s is not a formula file" src-file)))
1521 (org-odt-create-manifest-file-entry "text/xml" target-file))
1522 target-file))
1524 (defun org-odt-format-inline-formula (thefile)
1525 (let* ((thelink (if (file-name-absolute-p thefile) thefile
1526 (org-xml-format-href
1527 (org-odt-relocate-relative-path
1528 thefile org-current-export-file))))
1529 (href
1530 (org-odt-format-tags
1531 "<draw:object xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>" ""
1532 (file-name-directory (org-odt-copy-formula-file thefile)))))
1533 (org-export-odt-format-formula thefile href)))
1535 (defun org-odt-is-formula-link-p (file)
1536 (let ((case-fold-search nil))
1537 (cond
1538 ((string-match "\\.\\(mathml\\|mml\\)\\'" file)
1539 'mathml)
1540 ((string-match "\\.odf\\'" file)
1541 'odf))))
1543 (defun org-odt-format-org-link (opt-plist type-1 path fragment desc attr
1544 descp)
1545 "Make a OpenDocument link.
1546 OPT-PLIST is an options list.
1547 TYPE-1 is the device-type of the link (THIS://foo.html).
1548 PATH is the path of the link (http://THIS#location).
1549 FRAGMENT is the fragment part of the link, if any (foo.html#THIS).
1550 DESC is the link description, if any.
1551 ATTR is a string of other attributes of the a element."
1552 (declare (special org-lparse-par-open))
1553 (save-match-data
1554 (let* ((may-inline-p
1555 (and (member type-1 '("http" "https" "file"))
1556 (org-lparse-should-inline-p path descp)
1557 (not fragment)))
1558 (type (if (equal type-1 "id") "file" type-1))
1559 (filename path)
1560 (thefile path))
1561 (cond
1562 ;; check for inlined images
1563 ((and (member type '("file"))
1564 (not fragment)
1565 (org-file-image-p
1566 filename org-export-odt-inline-image-extensions)
1567 (or (eq t org-export-odt-inline-images)
1568 (and org-export-odt-inline-images (not descp))))
1569 (org-odt-format-inline-image thefile))
1570 ;; check for embedded formulas
1571 ((and (member type '("file"))
1572 (not fragment)
1573 (org-odt-is-formula-link-p filename)
1574 (or (not descp)))
1575 (org-odt-format-inline-formula thefile))
1576 ((string= type "coderef")
1577 (let* ((ref fragment)
1578 (lineno-or-ref (cdr (assoc ref org-export-code-refs)))
1579 (desc (and descp desc))
1580 (org-odt-suppress-xref nil)
1581 (href (org-xml-format-href (concat "#coderef-" ref))))
1582 (cond
1583 ((and (numberp lineno-or-ref) (not desc))
1584 (org-odt-format-link lineno-or-ref href))
1585 ((and (numberp lineno-or-ref) desc
1586 (string-match (regexp-quote (concat "(" ref ")")) desc))
1587 (format (replace-match "%s" t t desc)
1588 (org-odt-format-link lineno-or-ref href)))
1590 (setq desc (format
1591 (if (and desc (string-match
1592 (regexp-quote (concat "(" ref ")"))
1593 desc))
1594 (replace-match "%s" t t desc)
1595 (or desc "%s"))
1596 lineno-or-ref))
1597 (org-odt-format-link (org-xml-format-desc desc) href)))))
1599 (when (string= type "file")
1600 (setq thefile
1601 (cond
1602 ((file-name-absolute-p path)
1603 (concat "file://" (expand-file-name path)))
1604 (t (org-odt-relocate-relative-path
1605 thefile org-current-export-file)))))
1607 (when (and (member type '("" "http" "https" "file")) fragment)
1608 (setq thefile (concat thefile "#" fragment)))
1610 (setq thefile (org-xml-format-href thefile))
1612 (when (not (member type '("" "file")))
1613 (setq thefile (concat type ":" thefile)))
1615 (let ((org-odt-suppress-xref nil))
1616 (org-odt-format-link
1617 (org-xml-format-desc desc) thefile attr)))))))
1619 (defun org-odt-format-heading (text level &optional id)
1620 (let* ((text (if id (org-odt-format-target text id) text)))
1621 (org-odt-format-tags
1622 '("<text:h text:style-name=\"Heading_20_%s\" text:outline-level=\"%s\">" .
1623 "</text:h>") text level level)))
1625 (defun org-odt-format-headline (title extra-targets tags
1626 &optional snumber level)
1627 (concat
1628 (org-lparse-format 'EXTRA-TARGETS extra-targets)
1630 ;; No need to generate section numbers. They are auto-generated by
1631 ;; the application
1633 ;; (concat (org-lparse-format 'SECTION-NUMBER snumber level) " ")
1634 title
1635 (and tags (concat (org-lparse-format 'SPACES 3)
1636 (org-lparse-format 'ORG-TAGS tags)))))
1638 (defun org-odt-format-anchor (text name &optional class)
1639 (org-odt-format-target text name))
1641 (defun org-odt-format-bookmark (text id)
1642 (if id
1643 (org-odt-format-tags "<text:bookmark text:name=\"%s\"/>" text id)
1644 text))
1646 (defun org-odt-format-target (text id)
1647 (let ((name (concat org-export-odt-bookmark-prefix id)))
1648 (concat
1649 (and id (org-odt-format-tags
1650 "<text:bookmark-start text:name=\"%s\"/>" "" name))
1651 (org-odt-format-bookmark text id)
1652 (and id (org-odt-format-tags
1653 "<text:bookmark-end text:name=\"%s\"/>" "" name)))))
1655 (defun org-odt-format-footnote (n def)
1656 (let ((id (concat "fn" n))
1657 (note-class "footnote")
1658 (par-style "Footnote"))
1659 (org-odt-format-tags
1660 '("<text:note text:id=\"%s\" text:note-class=\"%s\">" .
1661 "</text:note>")
1662 (concat
1663 (org-odt-format-tags
1664 '("<text:note-citation>" . "</text:note-citation>")
1666 (org-odt-format-tags
1667 '("<text:note-body>" . "</text:note-body>")
1668 def))
1669 id note-class)))
1671 (defun org-odt-format-footnote-reference (n def refcnt)
1672 (if (= refcnt 1)
1673 (org-odt-format-footnote n def)
1674 (org-odt-format-footnote-ref n)))
1676 (defun org-odt-format-footnote-ref (n)
1677 (let ((note-class "footnote")
1678 (ref-format "text")
1679 (ref-name (concat "fn" n)))
1680 (org-odt-format-tags
1681 '("<text:span text:style-name=\"%s\">" . "</text:span>")
1682 (org-odt-format-tags
1683 '("<text:note-ref text:note-class=\"%s\" text:reference-format=\"%s\" text:ref-name=\"%s\">" . "</text:note-ref>")
1684 n note-class ref-format ref-name)
1685 "OrgSuperscript")))
1687 (defun org-odt-get-image-name (file-name)
1688 (require 'sha1)
1689 (file-relative-name
1690 (expand-file-name
1691 (concat (sha1 file-name) "." (file-name-extension file-name)) "Pictures")))
1693 (defun org-export-odt-format-image (src href)
1694 "Create image tag with source and attributes."
1695 (save-match-data
1696 (let* ((caption (org-find-text-property-in-string 'org-caption src))
1697 (caption (and caption (org-xml-format-desc caption)))
1698 (attr (org-find-text-property-in-string 'org-attributes src))
1699 (label (org-find-text-property-in-string 'org-label src))
1700 (latex-frag (org-find-text-property-in-string
1701 'org-latex-src src))
1702 (category (and latex-frag "__DvipngImage__"))
1703 (attr-plist (org-lparse-get-block-params attr))
1704 (user-frame-anchor
1705 (car (assoc-string (plist-get attr-plist :anchor)
1706 (if (or caption label)
1707 '(("paragraph") ("page"))
1708 '(("character") ("paragraph") ("page"))) t)))
1709 (user-frame-style
1710 (and user-frame-anchor (plist-get attr-plist :style)))
1711 (user-frame-attrs
1712 (and user-frame-anchor (plist-get attr-plist :attributes)))
1713 (user-frame-params
1714 (list user-frame-style user-frame-attrs user-frame-anchor))
1715 (embed-as (cond
1716 (latex-frag
1717 (symbol-name
1718 (or (org-find-text-property-in-string
1719 'org-latex-src-embed-type src) 'character)))
1720 (user-frame-anchor)
1721 (t "paragraph")))
1722 (size (org-odt-image-size-from-file
1723 src (plist-get attr-plist :width)
1724 (plist-get attr-plist :height)
1725 (plist-get attr-plist :scale) nil embed-as))
1726 (width (car size)) (height (cdr size)))
1727 (when latex-frag
1728 (setq href (org-propertize href :title "LaTeX Fragment"
1729 :description latex-frag)))
1730 (let ((frame-style-handle (concat (and (or caption label) "Captioned")
1731 embed-as "Image")))
1732 (org-odt-format-entity
1733 frame-style-handle href width height
1734 :caption caption :label label :category category
1735 :user-frame-params user-frame-params)))))
1737 (defun org-odt-format-object-description (title description)
1738 (concat (and title (org-odt-format-tags
1739 '("<svg:title>" . "</svg:title>")
1740 (org-odt-encode-plain-text title t)))
1741 (and description (org-odt-format-tags
1742 '("<svg:desc>" . "</svg:desc>")
1743 (org-odt-encode-plain-text description t)))))
1745 (defun org-odt-format-frame (text width height style &optional
1746 extra anchor-type)
1747 (let ((frame-attrs
1748 (concat
1749 (if width (format " svg:width=\"%0.2fcm\"" width) "")
1750 (if height (format " svg:height=\"%0.2fcm\"" height) "")
1751 extra
1752 (format " text:anchor-type=\"%s\"" (or anchor-type "paragraph")))))
1753 (org-odt-format-tags
1754 '("<draw:frame draw:style-name=\"%s\"%s>" . "</draw:frame>")
1755 (concat text (org-odt-format-object-description
1756 (get-text-property 0 :title text)
1757 (get-text-property 0 :description text)))
1758 style frame-attrs)))
1760 (defun org-odt-format-textbox (text width height style &optional
1761 extra anchor-type)
1762 (org-odt-format-frame
1763 (org-odt-format-tags
1764 '("<draw:text-box %s>" . "</draw:text-box>")
1765 text (concat (format " fo:min-height=\"%0.2fcm\"" (or height .2))
1766 (unless width
1767 (format " fo:min-width=\"%0.2fcm\"" (or width .2)))))
1768 width nil style extra anchor-type))
1770 (defun org-odt-format-inlinetask (heading content
1771 &optional todo priority tags)
1772 (org-odt-format-stylized-paragraph
1773 nil (org-odt-format-textbox
1774 (concat (org-odt-format-stylized-paragraph
1775 "OrgInlineTaskHeading"
1776 (org-lparse-format
1777 'HEADLINE (concat (org-lparse-format-todo todo) " " heading)
1778 nil tags))
1779 content) nil nil "OrgInlineTaskFrame" " style:rel-width=\"100%\"")))
1781 (defvar org-odt-entity-frame-styles
1782 '(("CharacterImage" "__Figure__" ("OrgInlineImage" nil "as-char"))
1783 ("ParagraphImage" "__Figure__" ("OrgDisplayImage" nil "paragraph"))
1784 ("PageImage" "__Figure__" ("OrgPageImage" nil "page"))
1785 ("CaptionedParagraphImage" "__Figure__"
1786 ("OrgCaptionedImage"
1787 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
1788 ("OrgImageCaptionFrame" nil "paragraph"))
1789 ("CaptionedPageImage" "__Figure__"
1790 ("OrgCaptionedImage"
1791 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
1792 ("OrgPageImageCaptionFrame" nil "page"))
1793 ("InlineFormula" "__MathFormula__" ("OrgInlineFormula" nil "as-char"))
1794 ("DisplayFormula" "__MathFormula__" ("OrgDisplayFormula" nil "as-char"))
1795 ("CaptionedDisplayFormula" "__MathFormula__"
1796 ("OrgCaptionedFormula" nil "paragraph")
1797 ("OrgFormulaCaptionFrame" nil "as-char"))))
1799 (defun org-odt-merge-frame-params(default-frame-params user-frame-params)
1800 (if (not user-frame-params) default-frame-params
1801 (assert (= (length default-frame-params) 3))
1802 (assert (= (length user-frame-params) 3))
1803 (loop for user-frame-param in user-frame-params
1804 for default-frame-param in default-frame-params
1805 collect (or user-frame-param default-frame-param))))
1807 (defun* org-odt-format-entity (entity href width height
1808 &key caption label category
1809 user-frame-params)
1810 (let* ((entity-style (assoc-string entity org-odt-entity-frame-styles t))
1811 default-frame-params frame-params)
1812 (cond
1813 ((not (or caption label))
1814 (setq default-frame-params (nth 2 entity-style))
1815 (setq frame-params (org-odt-merge-frame-params
1816 default-frame-params user-frame-params))
1817 (apply 'org-odt-format-frame href width height frame-params))
1819 (setq default-frame-params (nth 3 entity-style))
1820 (setq frame-params (org-odt-merge-frame-params
1821 default-frame-params user-frame-params))
1822 (apply 'org-odt-format-textbox
1823 (org-odt-format-stylized-paragraph
1824 'illustration
1825 (concat
1826 (apply 'org-odt-format-frame href width height
1827 (nth 2 entity-style))
1828 (org-odt-format-entity-caption
1829 label caption (or category (nth 1 entity-style)))))
1830 width height frame-params)))))
1832 (defvar org-odt-embedded-images-count 0)
1833 (defun org-odt-copy-image-file (path)
1834 "Returns the internal name of the file"
1835 (let* ((image-type (file-name-extension path))
1836 (media-type (format "image/%s" image-type))
1837 (src-file (expand-file-name
1838 path (file-name-directory org-current-export-file)))
1839 (target-dir "Images/")
1840 (target-file
1841 (format "%s%04d.%s" target-dir
1842 (incf org-odt-embedded-images-count) image-type)))
1843 (when (not org-lparse-to-buffer)
1844 (message "Embedding %s as %s ..."
1845 (substring-no-properties path) target-file)
1847 (when (= 1 org-odt-embedded-images-count)
1848 (make-directory target-dir)
1849 (org-odt-create-manifest-file-entry "" target-dir))
1851 (copy-file src-file target-file 'overwrite)
1852 (org-odt-create-manifest-file-entry media-type target-file))
1853 target-file))
1855 (defvar org-export-odt-image-size-probe-method
1856 '(emacs imagemagick force)
1857 "Ordered list of methods by for determining size of an embedded
1858 image.")
1860 (defvar org-export-odt-default-image-sizes-alist
1861 '(("character" . (5 . 0.4))
1862 ("paragraph" . (5 . 5)))
1863 "Hardcoded image dimensions one for each of the anchor
1864 methods.")
1866 ;; A4 page size is 21.0 by 29.7 cms
1867 ;; The default page settings has 2cm margin on each of the sides. So
1868 ;; the effective text area is 17.0 by 25.7 cm
1869 (defvar org-export-odt-max-image-size '(17.0 . 20.0)
1870 "Limiting dimensions for an embedded image.")
1872 (defun org-odt-do-image-size (probe-method file &optional dpi anchor-type)
1873 (setq dpi (or dpi org-export-odt-pixels-per-inch))
1874 (setq anchor-type (or anchor-type "paragraph"))
1875 (flet ((size-in-cms (size-in-pixels)
1876 (flet ((pixels-to-cms (pixels)
1877 (let* ((cms-per-inch 2.54)
1878 (inches (/ pixels dpi)))
1879 (* cms-per-inch inches))))
1880 (and size-in-pixels
1881 (cons (pixels-to-cms (car size-in-pixels))
1882 (pixels-to-cms (cdr size-in-pixels)))))))
1883 (case probe-method
1884 (emacs
1885 (size-in-cms (ignore-errors (image-size (create-image file) 'pixels))))
1886 (imagemagick
1887 (size-in-cms
1888 (let ((dim (shell-command-to-string
1889 (format "identify -format \"%%w:%%h\" \"%s\"" file))))
1890 (when (string-match "\\([0-9]+\\):\\([0-9]+\\)" dim)
1891 (cons (string-to-number (match-string 1 dim))
1892 (string-to-number (match-string 2 dim)))))))
1894 (cdr (assoc-string anchor-type
1895 org-export-odt-default-image-sizes-alist))))))
1897 (defun org-odt-image-size-from-file (file &optional user-width
1898 user-height scale dpi embed-as)
1899 (unless (file-name-absolute-p file)
1900 (setq file (expand-file-name
1901 file (file-name-directory org-current-export-file))))
1902 (let* (size width height)
1903 (unless (and user-height user-width)
1904 (loop for probe-method in org-export-odt-image-size-probe-method
1905 until size
1906 do (setq size (org-odt-do-image-size
1907 probe-method file dpi embed-as)))
1908 (or size (error "Cannot determine Image size. Aborting ..."))
1909 (setq width (car size) height (cdr size)))
1910 (cond
1911 (scale
1912 (setq width (* width scale) height (* height scale)))
1913 ((and user-height user-width)
1914 (setq width user-width height user-height))
1915 (user-height
1916 (setq width (* user-height (/ width height)) height user-height))
1917 (user-width
1918 (setq height (* user-width (/ height width)) width user-width))
1919 (t (ignore)))
1920 ;; ensure that an embedded image fits comfortably within a page
1921 (let ((max-width (car org-export-odt-max-image-size))
1922 (max-height (cdr org-export-odt-max-image-size)))
1923 (when (or (> width max-width) (> height max-height))
1924 (let* ((scale1 (/ max-width width))
1925 (scale2 (/ max-height height))
1926 (scale (min scale1 scale2)))
1927 (setq width (* scale width) height (* scale height)))))
1928 (cons width height)))
1930 (defvar org-odt-entity-labels-alist nil
1931 "Associate Labels with the Labeled entities.
1932 Each element of the alist is of the form (LABEL-NAME
1933 CATEGORY-NAME SEQNO LABEL-STYLE-NAME). LABEL-NAME is same as
1934 that specified by \"#+LABEL: ...\" line. CATEGORY-NAME is the
1935 type of the entity that LABEL-NAME is attached to. CATEGORY-NAME
1936 can be one of \"Table\", \"Figure\" or \"Equation\". SEQNO is
1937 the unique number assigned to the referenced entity on a
1938 per-CATEGORY basis. It is generated sequentially and is 1-based.
1939 LABEL-STYLE-NAME is a key `org-odt-label-styles'.
1941 See `org-odt-add-label-definition' and
1942 `org-odt-fixup-label-references'.")
1944 (defvar org-odt-entity-counts-plist nil
1945 "Plist of running counters of SEQNOs for each of the CATEGORY-NAMEs.
1946 See `org-odt-entity-labels-alist' for known CATEGORY-NAMEs.")
1948 (defvar org-odt-label-styles
1949 '(("text" "(%n)" "text" "(%n)")
1950 ("category-and-value" "%e %n%c" "category-and-value" "%e %n"))
1951 "Specify how labels are applied and referenced.
1952 This is an alist where each element is of the
1953 form (LABEL-STYLE-NAME LABEL-ATTACH-FMT LABEL-REF-MODE
1954 LABEL-REF-FMT).
1956 LABEL-ATTACH-FMT controls how labels and captions are attached to
1957 an entity. It may contain following specifiers - %e, %n and %c.
1958 %e is replaced with the CATEGORY-NAME. %n is replaced with
1959 \"<text:sequence ...> SEQNO </text:sequence>\". %c is replaced
1960 with CAPTION. See `org-odt-format-label-definition'.
1962 LABEL-REF-MODE and LABEL-REF-FMT controls how label references
1963 are generated. The following XML is generated for a label
1964 reference - \"<text:sequence-ref
1965 text:reference-format=\"LABEL-REF-MODE\" ...> LABEL-REF-FMT
1966 </text:sequence-ref>\". LABEL-REF-FMT may contain following
1967 specifiers - %e and %n. %e is replaced with the CATEGORY-NAME.
1968 %n is replaced with SEQNO. See
1969 `org-odt-format-label-reference'.")
1971 (defvar org-odt-category-map-alist
1972 '(("__Table__" "Table" "category-and-value")
1973 ("__Figure__" "Figure" "category-and-value")
1974 ("__MathFormula__" "Equation" "text")
1975 ("__DvipngImage__" "Equation" "category-and-value"))
1976 "Map a CATEGORY-HANDLE to CATEGORY-NAME and LABEL-STYLE.
1977 This is an alist where each element is of the form
1978 \\(CATEGORY-HANDLE CATEGORY-NAME LABEL-STYLE\\). CATEGORY_HANDLE
1979 could either be one of the internal handles (as seen above) or be
1980 derived from the \"#+LABEL:<label-name>\" specification. See
1981 `org-export-odt-get-category-from-label'. CATEGORY-NAME and
1982 LABEL-STYLE are used for generating ODT labels. See
1983 `org-odt-label-styles'.")
1985 (defvar org-export-odt-user-categories
1986 '("Illustration" "Table" "Text" "Drawing" "Equation" "Figure"))
1988 (defvar org-export-odt-get-category-from-label nil
1989 "Should category of label be inferred from label itself.
1990 When this option is non-nil, a label is parsed in to two
1991 component parts delimited by a \":\" (colon) as shown here -
1992 #+LABEL:[CATEGORY-HANDLE:]EXTRA. The CATEGORY-HANDLE is mapped
1993 to a CATEGORY-NAME and LABEL-STYLE using
1994 `org-odt-category-map-alist'. (If no such map is provided and
1995 CATEGORY-NAME is set to CATEGORY-HANDLE and LABEL-STYLE is set to
1996 \"category-and-value\"). If CATEGORY-NAME so obtained is listed
1997 under `org-export-odt-user-categories' then the user specified
1998 styles are used. Otherwise styles as determined by the internal
1999 CATEGORY-HANDLE is used. See
2000 `org-odt-get-label-category-and-style' for details.")
2002 (defun org-odt-get-label-category-and-style (label default-category)
2003 "See `org-export-odt-get-category-from-label'."
2004 (let ((default-category-map
2005 (assoc default-category org-odt-category-map-alist))
2006 user-category user-category-map category)
2007 (cond
2008 ((not org-export-odt-get-category-from-label)
2009 default-category-map)
2010 ((not (setq user-category
2011 (save-match-data
2012 (and (string-match "\\`\\(.*\\):.+" label)
2013 (match-string 1 label)))))
2014 default-category-map)
2016 (setq user-category-map
2017 (or (assoc user-category org-odt-category-map-alist)
2018 (list nil user-category "category-and-value"))
2019 category (nth 1 user-category-map))
2020 (if (member category org-export-odt-user-categories)
2021 user-category-map
2022 default-category-map)))))
2024 (defun org-odt-add-label-definition (label default-category)
2025 "Create an entry in `org-odt-entity-labels-alist' and return it."
2026 (setq label (substring-no-properties label))
2027 (let* ((label-props (org-odt-get-label-category-and-style
2028 label default-category))
2029 (category (nth 1 label-props))
2030 (counter category)
2031 (label-style (nth 2 label-props))
2032 (sequence-var (intern (mapconcat
2033 'downcase
2034 (org-split-string counter) "-")))
2035 (seqno (1+ (or (plist-get org-odt-entity-counts-plist sequence-var)
2036 0)))
2037 (label-props (list label category seqno label-style)))
2038 (setq org-odt-entity-counts-plist
2039 (plist-put org-odt-entity-counts-plist sequence-var seqno))
2040 (push label-props org-odt-entity-labels-alist)
2041 label-props))
2043 (defun org-odt-format-label-definition (caption label category seqno label-style)
2044 (assert label)
2045 (format-spec
2046 (cadr (assoc-string label-style org-odt-label-styles t))
2047 `((?e . ,category)
2048 (?n . ,(org-odt-format-tags
2049 '("<text:sequence text:ref-name=\"%s\" text:name=\"%s\" text:formula=\"ooow:%s+1\" style:num-format=\"1\">" . "</text:sequence>")
2050 (format "%d" seqno) label category category))
2051 (?c . ,(or (and caption (concat ": " caption)) "")))))
2053 (defun org-odt-format-label-reference (label category seqno label-style)
2054 (assert label)
2055 (save-match-data
2056 (let* ((fmt (cddr (assoc-string label-style org-odt-label-styles t)))
2057 (fmt1 (car fmt))
2058 (fmt2 (cadr fmt)))
2059 (org-odt-format-tags
2060 '("<text:sequence-ref text:reference-format=\"%s\" text:ref-name=\"%s\">"
2061 . "</text:sequence-ref>")
2062 (format-spec fmt2 `((?e . ,category)
2063 (?n . ,(format "%d" seqno)))) fmt1 label))))
2065 (defun org-odt-fixup-label-references ()
2066 (goto-char (point-min))
2067 (while (re-search-forward
2068 "<text:sequence-ref text:ref-name=\"\\([^\"]+\\)\">[ \t\n]*</text:sequence-ref>"
2069 nil t)
2070 (let* ((label (match-string 1))
2071 (label-def (assoc label org-odt-entity-labels-alist))
2072 (rpl (and label-def
2073 (apply 'org-odt-format-label-reference label-def))))
2074 (if rpl (replace-match rpl t t)
2075 (org-lparse-warn
2076 (format "Unable to resolve reference to label \"%s\"" label))))))
2078 (defun org-odt-format-entity-caption (label caption category)
2079 (or (and label
2080 (apply 'org-odt-format-label-definition
2081 caption (org-odt-add-label-definition label category)))
2082 caption ""))
2084 (defun org-odt-format-tags (tag text &rest args)
2085 (let ((prefix (when org-lparse-encode-pending "@"))
2086 (suffix (when org-lparse-encode-pending "@")))
2087 (apply 'org-lparse-format-tags tag text prefix suffix args)))
2089 (defvar org-odt-manifest-file-entries nil)
2090 (defun org-odt-init-outfile (filename)
2091 (unless (executable-find "zip")
2092 ;; Not at all OSes ship with zip by default
2093 (error "Executable \"zip\" needed for creating OpenDocument files"))
2095 (let* ((outdir (make-temp-file
2096 (format org-export-odt-tmpdir-prefix org-lparse-backend) t))
2097 (content-file (expand-file-name "content.xml" outdir)))
2099 ;; init conten.xml
2100 (with-current-buffer (find-file-noselect content-file t))
2102 ;; reset variables
2103 (setq org-odt-manifest-file-entries nil
2104 org-odt-embedded-images-count 0
2105 org-odt-embedded-formulas-count 0
2106 org-odt-section-count 0
2107 org-odt-entity-labels-alist nil
2108 org-odt-list-stack-stashed nil
2109 org-odt-entity-counts-plist nil)
2110 content-file))
2112 (defcustom org-export-odt-prettify-xml nil
2113 "Specify whether or not the xml output should be prettified.
2114 When this option is turned on, `indent-region' is run on all
2115 component xml buffers before they are saved. Turn this off for
2116 regular use. Turn this on if you need to examine the xml
2117 visually."
2118 :group 'org-export-odt
2119 :type 'boolean)
2121 (defvar hfy-user-sheet-assoc) ; bound during org-do-lparse
2122 (defun org-odt-save-as-outfile (target opt-plist)
2123 ;; write meta file
2124 (org-odt-update-meta-file opt-plist)
2126 ;; write styles file
2127 (when (equal org-lparse-backend 'odt)
2128 (org-odt-update-styles-file opt-plist))
2130 ;; create mimetype file
2131 (let ((mimetype (org-odt-write-mimetype-file org-lparse-backend)))
2132 (org-odt-create-manifest-file-entry mimetype "/" "1.2"))
2134 ;; create a manifest entry for content.xml
2135 (org-odt-create-manifest-file-entry "text/xml" "content.xml")
2137 ;; write out the manifest entries before zipping
2138 (org-odt-write-manifest-file)
2140 (let ((xml-files '("mimetype" "META-INF/manifest.xml" "content.xml"
2141 "meta.xml"))
2142 (zipdir default-directory))
2143 (when (equal org-lparse-backend 'odt)
2144 (push "styles.xml" xml-files))
2145 (message "Switching to directory %s" (expand-file-name zipdir))
2147 ;; save all xml files
2148 (mapc (lambda (file)
2149 (with-current-buffer
2150 (find-file-noselect (expand-file-name file) t)
2151 ;; prettify output if needed
2152 (when org-export-odt-prettify-xml
2153 (indent-region (point-min) (point-max)))
2154 (save-buffer 0)))
2155 xml-files)
2157 (let* ((target-name (file-name-nondirectory target))
2158 (target-dir (file-name-directory target))
2159 (cmds `(("zip" "-mX0" ,target-name "mimetype")
2160 ("zip" "-rmTq" ,target-name "."))))
2161 (when (file-exists-p target)
2162 ;; FIXME: If the file is locked this throws a cryptic error
2163 (delete-file target))
2165 (let ((coding-system-for-write 'no-conversion) exitcode err-string)
2166 (message "Creating odt file...")
2167 (mapc
2168 (lambda (cmd)
2169 (message "Running %s" (mapconcat 'identity cmd " "))
2170 (setq err-string
2171 (with-output-to-string
2172 (setq exitcode
2173 (apply 'call-process (car cmd)
2174 nil standard-output nil (cdr cmd)))))
2175 (or (zerop exitcode)
2176 (ignore (message "%s" err-string))
2177 (error "Unable to create odt file (%S)" exitcode)))
2178 cmds))
2180 ;; move the file from outdir to target-dir
2181 (rename-file target-name target-dir)
2183 ;; kill all xml buffers
2184 (mapc (lambda (file)
2185 (kill-buffer
2186 (find-file-noselect (expand-file-name file zipdir) t)))
2187 xml-files)
2189 (delete-directory zipdir)))
2190 (message "Created %s" target)
2191 (set-buffer (find-file-noselect target t)))
2193 (defconst org-odt-manifest-file-entry-tag
2195 <manifest:file-entry manifest:media-type=\"%s\" manifest:full-path=\"%s\"%s/>")
2197 (defun org-odt-create-manifest-file-entry (&rest args)
2198 (push args org-odt-manifest-file-entries))
2200 (defun org-odt-write-manifest-file ()
2201 (make-directory "META-INF")
2202 (let ((manifest-file (expand-file-name "META-INF/manifest.xml")))
2203 (with-current-buffer
2204 (find-file-noselect manifest-file t)
2205 (insert
2206 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
2207 <manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"1.2\">\n")
2208 (mapc
2209 (lambda (file-entry)
2210 (let* ((version (nth 2 file-entry))
2211 (extra (if version
2212 (format " manifest:version=\"%s\"" version)
2213 "")))
2214 (insert
2215 (format org-odt-manifest-file-entry-tag
2216 (nth 0 file-entry) (nth 1 file-entry) extra))))
2217 org-odt-manifest-file-entries)
2218 (insert "\n</manifest:manifest>"))))
2220 (defun org-odt-update-meta-file (opt-plist)
2221 (let ((date (org-odt-format-date (plist-get opt-plist :date)))
2222 (author (or (plist-get opt-plist :author) ""))
2223 (email (plist-get opt-plist :email))
2224 (keywords (plist-get opt-plist :keywords))
2225 (description (plist-get opt-plist :description))
2226 (title (plist-get opt-plist :title)))
2227 (write-region
2228 (concat
2229 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
2230 <office:document-meta
2231 xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"
2232 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2233 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2234 xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"
2235 xmlns:ooo=\"http://openoffice.org/2004/office\"
2236 office:version=\"1.2\">
2237 <office:meta>" "\n"
2238 (org-odt-format-author)
2239 (org-odt-format-tags
2240 '("\n<meta:initial-creator>" . "</meta:initial-creator>") author)
2241 (org-odt-format-tags '("\n<dc:date>" . "</dc:date>") date)
2242 (org-odt-format-tags
2243 '("\n<meta:creation-date>" . "</meta:creation-date>") date)
2244 (org-odt-format-tags '("\n<meta:generator>" . "</meta:generator>")
2245 (when org-export-creator-info
2246 (format "Org-%s/Emacs-%s"
2247 org-version emacs-version)))
2248 (org-odt-format-tags '("\n<meta:keyword>" . "</meta:keyword>") keywords)
2249 (org-odt-format-tags '("\n<dc:subject>" . "</dc:subject>") description)
2250 (org-odt-format-tags '("\n<dc:title>" . "</dc:title>") title)
2251 "\n"
2252 " </office:meta>" "</office:document-meta>")
2253 nil (expand-file-name "meta.xml")))
2255 ;; create a manifest entry for meta.xml
2256 (org-odt-create-manifest-file-entry "text/xml" "meta.xml"))
2258 (defun org-odt-update-styles-file (opt-plist)
2259 ;; write styles file
2260 (let ((styles-file (plist-get opt-plist :odt-styles-file)))
2261 (org-odt-copy-styles-file (and styles-file
2262 (read (org-trim styles-file)))))
2264 ;; Update styles.xml - take care of outline numbering
2265 (with-current-buffer
2266 (find-file-noselect (expand-file-name "styles.xml") t)
2267 ;; Don't make automatic backup of styles.xml file. This setting
2268 ;; prevents the backed-up styles.xml file from being zipped in to
2269 ;; odt file. This is more of a hackish fix. Better alternative
2270 ;; would be to fix the zip command so that the output odt file
2271 ;; includes only the needed files and excludes any auto-generated
2272 ;; extra files like backups and auto-saves etc etc. Note that
2273 ;; currently the zip command zips up the entire temp directory so
2274 ;; that any auto-generated files created under the hood ends up in
2275 ;; the resulting odt file.
2276 (set (make-local-variable 'backup-inhibited) t)
2278 ;; Import local setting of `org-export-with-section-numbers'
2279 (org-lparse-bind-local-variables opt-plist)
2280 (org-odt-configure-outline-numbering
2281 (if org-export-with-section-numbers org-export-headline-levels 0)))
2283 ;; Write custom styles for source blocks
2284 (org-odt-insert-custom-styles-for-srcblocks
2285 (mapconcat
2286 (lambda (style)
2287 (format " %s\n" (cddr style)))
2288 hfy-user-sheet-assoc "")))
2290 (defun org-odt-write-mimetype-file (format)
2291 ;; create mimetype file
2292 (let ((mimetype
2293 (case format
2294 (odt "application/vnd.oasis.opendocument.text")
2295 (odf "application/vnd.oasis.opendocument.formula")
2296 (t (error "Unknown OpenDocument backend %S" org-lparse-backend)))))
2297 (write-region mimetype nil (expand-file-name "mimetype"))
2298 mimetype))
2300 (defun org-odt-finalize-outfile ()
2301 (org-odt-delete-empty-paragraphs))
2303 (defun org-odt-delete-empty-paragraphs ()
2304 (goto-char (point-min))
2305 (let ((open "<text:p[^>]*>")
2306 (close "</text:p>"))
2307 (while (re-search-forward (format "%s[ \r\n\t]*%s" open close) nil t)
2308 (replace-match ""))))
2310 (defcustom org-export-odt-convert-processes
2311 '(("BasicODConverter"
2312 ("soffice" "-norestore" "-invisible" "-headless"
2313 "\"macro:///BasicODConverter.Main.Convert(%I,%f,%O)\""))
2314 ("unoconv"
2315 ("unoconv" "-f" "%f" "-o" "%d" "%i")))
2316 "Specify a list of document converters and their usage.
2317 The converters in this list are offered as choices while
2318 customizing `org-export-odt-convert-process'.
2320 This variable is an alist where each element is of the
2321 form (CONVERTER-NAME CONVERTER-PROCESS). CONVERTER-NAME is name
2322 of the converter. CONVERTER-PROCESS specifies the command-line
2323 syntax of the converter and is of the form (CONVERTER-PROGRAM
2324 ARG1 ARG2 ...). CONVERTER-PROGRAM is the name of the executable.
2325 ARG1, ARG2 etc are command line options that are passed to
2326 CONVERTER-PROGRAM. Format specifiers can be used in the ARGs and
2327 they are interpreted as below:
2329 %i input file name in full
2330 %I input file name as a URL
2331 %f format of the output file
2332 %o output file name in full
2333 %O output file name as a URL
2334 %d output dir in full
2335 %D output dir as a URL."
2336 :group 'org-export-odt
2337 :type
2338 '(choice
2339 (const :tag "None" nil)
2340 (alist :tag "Converters"
2341 :key-type (string :tag "Converter Name")
2342 :value-type (group (cons (string :tag "Executable")
2343 (repeat (string :tag "Command line args")))))))
2345 (defcustom org-export-odt-convert-process nil
2346 "Use this converter to convert from \"odt\" format to other formats.
2347 During customization, the list of converter names are populated
2348 from `org-export-odt-convert-processes'."
2349 :group 'org-export-odt
2350 :type '(choice :convert-widget
2351 (lambda (w)
2352 (apply 'widget-convert (widget-type w)
2353 (eval (car (widget-get w :args)))))
2354 `((const :tag "None" nil)
2355 ,@(mapcar (lambda (c)
2356 `(const :tag ,(car c) ,(car c)))
2357 org-export-odt-convert-processes))))
2359 (defcustom org-export-odt-convert-capabilities
2360 '(("Text"
2361 ("odt" "ott" "doc" "rtf")
2362 (("pdf" "pdf") ("odt" "odt") ("xhtml" "html") ("rtf" "rtf")
2363 ("ott" "ott") ("doc" "doc") ("ooxml" "xml") ("html" "html")))
2364 ("Web"
2365 ("html" "xhtml") (("pdf" "pdf") ("odt" "txt") ("html" "html")))
2366 ("Spreadsheet"
2367 ("ods" "ots" "xls" "csv")
2368 (("pdf" "pdf") ("ots" "ots") ("html" "html") ("csv" "csv")
2369 ("ods" "ods") ("xls" "xls") ("xhtml" "xhtml") ("ooxml" "xml")))
2370 ("Presentation"
2371 ("odp" "otp" "ppt")
2372 (("pdf" "pdf") ("swf" "swf") ("odp" "odp") ("xhtml" "xml")
2373 ("otp" "otp") ("ppt" "ppt") ("odg" "odg") ("html" "html"))))
2374 "Specify input and output formats of `org-export-odt-convert-process'.
2375 More correctly, specify the set of input and output formats that
2376 the user is actually interested in.
2378 This variable is an alist where each element is of the
2379 form (DOCUMENT-CLASS INPUT-FMT-LIST OUTPUT-FMT-ALIST).
2380 INPUT-FMT-LIST is a list of INPUT-FMTs. OUTPUT-FMT-ALIST is an
2381 alist where each element is of the form (OUTPUT-FMT
2382 OUTPUT-FILE-EXTENSION).
2384 The variable is interpreted as follows:
2385 `org-export-odt-convert-process' can take any document that is in
2386 INPUT-FMT-LIST and produce any document that is in the
2387 OUTPUT-FMT-LIST. A document converted to OUTPUT-FMT will have
2388 OUTPUT-FILE-EXTENSION as the file name extension. OUTPUT-FMT
2389 serves dual purposes:
2390 - It is used for populating completion candidates during
2391 `org-export-odt-convert' commands.
2392 - It is used as the value of \"%f\" specifier in
2393 `org-export-odt-convert-process'.
2395 DOCUMENT-CLASS is used to group a set of file formats in
2396 INPUT-FMT-LIST in to a single class.
2398 Note that this variable inherently captures how LibreOffice based
2399 converters work. LibreOffice maps documents of various formats
2400 to classes like Text, Web, Spreadsheet, Presentation etc and
2401 allow document of a given class (irrespective of it's source
2402 format) to be converted to any of the export formats associated
2403 with that class.
2405 See default setting of this variable for an typical
2406 configuration."
2407 :group 'org-export-odt
2408 :type
2409 '(choice
2410 (const :tag "None" nil)
2411 (alist :key-type (string :tag "Document Class")
2412 :value-type
2413 (group (repeat :tag "Input formats" (string :tag "Input format"))
2414 (alist :tag "Output formats"
2415 :key-type (string :tag "Output format")
2416 :value-type
2417 (group (string :tag "Output file extension")))))))
2419 (declare-function org-create-math-formula "org"
2420 (latex-frag &optional mathml-file))
2422 ;;;###autoload
2423 (defun org-export-odt-convert (&optional in-file out-fmt prefix-arg)
2424 "Convert IN-FILE to format OUT-FMT using a command line converter.
2425 IN-FILE is the file to be converted. If unspecified, it defaults
2426 to variable `buffer-file-name'. OUT-FMT is the desired output
2427 format. Use `org-export-odt-convert-process' as the converter.
2428 If PREFIX-ARG is non-nil then the newly converted file is opened
2429 using `org-open-file'."
2430 (interactive
2431 (append (org-lparse-convert-read-params) current-prefix-arg))
2432 (org-lparse-do-convert in-file out-fmt prefix-arg))
2434 (defun org-odt-get (what &optional opt-plist)
2435 (case what
2436 (BACKEND 'odt)
2437 (EXPORT-DIR (org-export-directory :html opt-plist))
2438 (FILE-NAME-EXTENSION "odt")
2439 (EXPORT-BUFFER-NAME "*Org ODT Export*")
2440 (ENTITY-CONTROL org-odt-entity-control-callbacks-alist)
2441 (ENTITY-FORMAT org-odt-entity-format-callbacks-alist)
2442 (INIT-METHOD 'org-odt-init-outfile)
2443 (FINAL-METHOD 'org-odt-finalize-outfile)
2444 (SAVE-METHOD 'org-odt-save-as-outfile)
2445 (CONVERT-METHOD
2446 (and org-export-odt-convert-process
2447 (cadr (assoc-string org-export-odt-convert-process
2448 org-export-odt-convert-processes t))))
2449 (CONVERT-CAPABILITIES
2450 (and org-export-odt-convert-process
2451 (cadr (assoc-string org-export-odt-convert-process
2452 org-export-odt-convert-processes t))
2453 org-export-odt-convert-capabilities))
2454 (TOPLEVEL-HLEVEL 1)
2455 (SPECIAL-STRING-REGEXPS org-export-odt-special-string-regexps)
2456 (INLINE-IMAGES 'maybe)
2457 (INLINE-IMAGE-EXTENSIONS '("png" "jpeg" "jpg" "gif" "svg"))
2458 (PLAIN-TEXT-MAP '(("&" . "&amp;") ("<" . "&lt;") (">" . "&gt;")))
2459 (TABLE-FIRST-COLUMN-AS-LABELS nil)
2460 (FOOTNOTE-SEPARATOR (org-lparse-format 'FONTIFY "," 'superscript))
2461 (CODING-SYSTEM-FOR-WRITE 'utf-8)
2462 (CODING-SYSTEM-FOR-SAVE 'utf-8)
2463 (t (error "Unknown property: %s" what))))
2465 (defvar org-lparse-latex-fragment-fallback) ; set by org-do-lparse
2466 (defun org-export-odt-do-preprocess-latex-fragments ()
2467 "Convert LaTeX fragments to images."
2468 (let* ((latex-frag-opt (plist-get org-lparse-opt-plist :LaTeX-fragments))
2469 (latex-frag-opt ; massage the options
2470 (or (and (member latex-frag-opt '(mathjax t))
2471 (not (and (fboundp 'org-format-latex-mathml-available-p)
2472 (org-format-latex-mathml-available-p)))
2473 (prog1 org-lparse-latex-fragment-fallback
2474 (org-lparse-warn
2475 (concat
2476 "LaTeX to MathML converter not available. "
2477 (format "Using %S instead."
2478 org-lparse-latex-fragment-fallback)))))
2479 latex-frag-opt))
2480 cache-dir display-msg)
2481 (cond
2482 ((eq latex-frag-opt 'dvipng)
2483 (setq cache-dir "ltxpng/")
2484 (setq display-msg "Creating LaTeX image %s"))
2485 ((member latex-frag-opt '(mathjax t))
2486 (setq latex-frag-opt 'mathml)
2487 (setq cache-dir "ltxmathml/")
2488 (setq display-msg "Creating MathML formula %s")))
2489 (when (and org-current-export-file)
2490 (org-format-latex
2491 (concat cache-dir (file-name-sans-extension
2492 (file-name-nondirectory org-current-export-file)))
2493 org-current-export-dir nil display-msg
2494 nil nil latex-frag-opt))))
2496 (defadvice org-format-latex-as-mathml
2497 (after org-odt-protect-latex-fragment activate)
2498 "Encode LaTeX fragment as XML.
2499 Do this when translation to MathML fails."
2500 (when (or (not (> (length ad-return-value) 0))
2501 (get-text-property 0 'org-protected ad-return-value))
2502 (setq ad-return-value
2503 (org-propertize (org-odt-encode-plain-text (ad-get-arg 0))
2504 'org-protected t))))
2506 (defun org-export-odt-preprocess-latex-fragments ()
2507 (when (equal org-export-current-backend 'odt)
2508 (org-export-odt-do-preprocess-latex-fragments)))
2510 (defun org-export-odt-preprocess-label-references ()
2511 (goto-char (point-min))
2512 (let (label label-components category value pretty-label)
2513 (while (re-search-forward "\\\\ref{\\([^{}\n]+\\)}" nil t)
2514 (org-if-unprotected-at (match-beginning 1)
2515 (replace-match
2516 (let ((org-lparse-encode-pending t)
2517 (label (match-string 1)))
2518 ;; markup generated below is mostly an eye-candy. At
2519 ;; pre-processing stage, there is no information on which
2520 ;; entity a label reference points to. The actual markup
2521 ;; is generated as part of `org-odt-fixup-label-references'
2522 ;; which gets called at the fag end of export. By this
2523 ;; time we would have seen and collected all the label
2524 ;; definitions in `org-odt-entity-labels-alist'.
2525 (org-odt-format-tags
2526 '("<text:sequence-ref text:ref-name=\"%s\">" .
2527 "</text:sequence-ref>")
2528 "" (org-add-props label '(org-protected t)))) t t)))))
2530 ;; process latex fragments as part of
2531 ;; `org-export-preprocess-after-blockquote-hook'. Note that this hook
2532 ;; is the one that is closest and well before the call to
2533 ;; `org-export-attach-captions-and-attributes' in
2534 ;; `org-export-preprocess-string'. The above arrangement permits
2535 ;; captions, labels and attributes to be attached to png images
2536 ;; generated out of latex equations.
2537 (add-hook 'org-export-preprocess-after-blockquote-hook
2538 'org-export-odt-preprocess-latex-fragments)
2540 (defun org-export-odt-preprocess (parameters)
2541 (org-export-odt-preprocess-label-references))
2543 (declare-function archive-zip-extract "arc-mode.el" (archive name))
2544 (defun org-odt-zip-extract-one (archive member &optional target)
2545 (require 'arc-mode)
2546 (let* ((target (or target default-directory))
2547 (archive (expand-file-name archive))
2548 (archive-zip-extract
2549 (list "unzip" "-qq" "-o" "-d" target))
2550 exit-code command-output)
2551 (setq command-output
2552 (with-temp-buffer
2553 (setq exit-code (archive-zip-extract archive member))
2554 (buffer-string)))
2555 (unless (zerop exit-code)
2556 (message command-output)
2557 (error "Extraction failed"))))
2559 (defun org-odt-zip-extract (archive members &optional target)
2560 (when (atom members) (setq members (list members)))
2561 (mapc (lambda (member)
2562 (org-odt-zip-extract-one archive member target))
2563 members))
2565 (defun org-odt-copy-styles-file (&optional styles-file)
2566 ;; Non-availability of styles.xml is not a critical error. For now
2567 ;; throw an error purely for aesthetic reasons.
2568 (setq styles-file (or styles-file
2569 org-export-odt-styles-file
2570 (expand-file-name "OrgOdtStyles.xml"
2571 org-odt-styles-dir)
2572 (error "org-odt: Missing styles file?")))
2573 (cond
2574 ((listp styles-file)
2575 (let ((archive (nth 0 styles-file))
2576 (members (nth 1 styles-file)))
2577 (org-odt-zip-extract archive members)
2578 (mapc
2579 (lambda (member)
2580 (when (org-file-image-p member)
2581 (let* ((image-type (file-name-extension member))
2582 (media-type (format "image/%s" image-type)))
2583 (org-odt-create-manifest-file-entry media-type member))))
2584 members)))
2585 ((and (stringp styles-file) (file-exists-p styles-file))
2586 (let ((styles-file-type (file-name-extension styles-file)))
2587 (cond
2588 ((string= styles-file-type "xml")
2589 (copy-file styles-file "styles.xml" t))
2590 ((member styles-file-type '("odt" "ott"))
2591 (org-odt-zip-extract styles-file "styles.xml")))))
2593 (error (format "Invalid specification of styles.xml file: %S"
2594 org-export-odt-styles-file))))
2596 ;; create a manifest entry for styles.xml
2597 (org-odt-create-manifest-file-entry "text/xml" "styles.xml"))
2599 (defvar org-export-odt-factory-settings
2600 "d4328fb9d1b6cb211d4320ff546829f26700dc5e"
2601 "SHA1 hash of OrgOdtStyles.xml.")
2603 (defun org-odt-configure-outline-numbering (level)
2604 "Outline numbering is retained only upto LEVEL.
2605 To disable outline numbering pass a LEVEL of 0."
2606 (goto-char (point-min))
2607 (let ((regex
2608 "<text:outline-level-style\\([^>]*\\)text:level=\"\\([^\"]*\\)\"\\([^>]*\\)>")
2609 (replacement
2610 "<text:outline-level-style\\1text:level=\"\\2\" style:num-format=\"\">"))
2611 (while (re-search-forward regex nil t)
2612 (when (> (string-to-number (match-string 2)) level)
2613 (replace-match replacement t nil))))
2614 (save-buffer 0))
2616 ;;;###autoload
2617 (defun org-export-as-odf (latex-frag &optional odf-file)
2618 "Export LATEX-FRAG as OpenDocument formula file ODF-FILE.
2619 Use `org-create-math-formula' to convert LATEX-FRAG first to
2620 MathML. When invoked as an interactive command, use
2621 `org-latex-regexps' to infer LATEX-FRAG from currently active
2622 region. If no LaTeX fragments are found, prompt for it. Push
2623 MathML source to kill ring, if `org-export-copy-to-kill-ring' is
2624 non-nil."
2625 (interactive
2626 `(,(let (frag)
2627 (setq frag (and (setq frag (and (region-active-p)
2628 (buffer-substring (region-beginning)
2629 (region-end))))
2630 (loop for e in org-latex-regexps
2631 thereis (when (string-match (nth 1 e) frag)
2632 (match-string (nth 2 e) frag)))))
2633 (read-string "LaTeX Fragment: " frag nil frag))
2634 ,(let ((odf-filename (expand-file-name
2635 (concat
2636 (file-name-sans-extension
2637 (or (file-name-nondirectory buffer-file-name)))
2638 "." "odf")
2639 (file-name-directory buffer-file-name))))
2640 (message "default val is %s" odf-filename)
2641 (read-file-name "ODF filename: " nil odf-filename nil
2642 (file-name-nondirectory odf-filename)))))
2643 (let* ((org-lparse-backend 'odf)
2644 org-lparse-opt-plist
2645 (filename (or odf-file
2646 (expand-file-name
2647 (concat
2648 (file-name-sans-extension
2649 (or (file-name-nondirectory buffer-file-name)))
2650 "." "odf")
2651 (file-name-directory buffer-file-name))))
2652 (buffer (find-file-noselect (org-odt-init-outfile filename)))
2653 (coding-system-for-write 'utf-8)
2654 (save-buffer-coding-system 'utf-8))
2655 (set-buffer buffer)
2656 (set-buffer-file-coding-system coding-system-for-write)
2657 (let ((mathml (org-create-math-formula latex-frag)))
2658 (unless mathml (error "No Math formula created"))
2659 (insert mathml)
2660 (or (org-export-push-to-kill-ring
2661 (upcase (symbol-name org-lparse-backend)))
2662 (message "Exporting... done")))
2663 (org-odt-save-as-outfile filename nil)))
2665 ;;;###autoload
2666 (defun org-export-as-odf-and-open ()
2667 "Export LaTeX fragment as OpenDocument formula and immediately open it.
2668 Use `org-export-as-odf' to read LaTeX fragment and OpenDocument
2669 formula file."
2670 (interactive)
2671 (org-lparse-and-open
2672 nil nil nil (call-interactively 'org-export-as-odf)))
2674 (provide 'org-odt)
2676 ;;; org-odt.el ends here