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