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