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