New function `org-insert-drawer'.
[org-mode.git] / lisp / org-odt.el
blob83a833ee170af56056803801b8743bc6fb506aab
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)
1538 (save-match-data
1539 (let* ((caption (org-find-text-property-in-string 'org-caption src))
1540 (caption (and caption (org-xml-format-desc caption)))
1541 (label (org-find-text-property-in-string 'org-label src))
1542 (latex-frag (org-find-text-property-in-string 'org-latex-src src))
1543 (embed-as (or (and latex-frag
1544 (org-find-text-property-in-string
1545 'org-latex-src-embed-type src))
1546 (if (or caption label) 'paragraph 'character)))
1547 width height)
1548 (when latex-frag
1549 (setq href (org-propertize href :title "LaTeX Fragment"
1550 :description latex-frag)))
1551 (cond
1552 ((eq embed-as 'character)
1553 (org-odt-format-entity "InlineFormula" href width height))
1555 (org-lparse-end-paragraph)
1556 (org-lparse-insert-list-table
1557 `((,(org-odt-format-entity
1558 (if caption "CaptionedDisplayFormula" "DisplayFormula")
1559 href width height :caption caption :label nil)
1560 ,(if (not label) ""
1561 (org-odt-format-entity-caption label nil "__MathFormula__"))))
1562 nil nil nil ":style \"OrgEquation\"" nil '((1 "c" 8) (2 "c" 1)))
1563 (throw 'nextline nil))))))
1565 (defvar org-odt-embedded-formulas-count 0)
1566 (defun org-odt-copy-formula-file (path)
1567 "Returns the internal name of the file"
1568 (let* ((src-file (expand-file-name
1569 path (file-name-directory org-current-export-file)))
1570 (target-dir (format "Formula-%04d/"
1571 (incf org-odt-embedded-formulas-count)))
1572 (target-file (concat target-dir "content.xml")))
1573 (when (not org-lparse-to-buffer)
1574 (message "Embedding %s as %s ..."
1575 (substring-no-properties path) target-file)
1577 (make-directory target-dir)
1578 (org-odt-create-manifest-file-entry
1579 "application/vnd.oasis.opendocument.formula" target-dir "1.2")
1581 (case (org-odt-is-formula-link-p src-file)
1582 (mathml
1583 (copy-file src-file target-file 'overwrite))
1584 (odf
1585 (org-odt-zip-extract-one src-file "content.xml" target-dir))
1587 (error "%s is not a formula file" src-file)))
1589 (org-odt-create-manifest-file-entry "text/xml" target-file))
1590 target-file))
1592 (defun org-odt-format-inline-formula (thefile)
1593 (let* ((thelink (if (file-name-absolute-p thefile) thefile
1594 (org-xml-format-href
1595 (org-odt-relocate-relative-path
1596 thefile org-current-export-file))))
1597 (href
1598 (org-odt-format-tags
1599 "<draw:object xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>" ""
1600 (file-name-directory (org-odt-copy-formula-file thefile)))))
1601 (org-export-odt-format-formula thefile href)))
1603 (defun org-odt-is-formula-link-p (file)
1604 (let ((case-fold-search nil))
1605 (cond
1606 ((string-match "\\.\\(mathml\\|mml\\)\\'" file)
1607 'mathml)
1608 ((string-match "\\.odf\\'" file)
1609 'odf))))
1611 (defun org-odt-format-org-link (opt-plist type-1 path fragment desc attr
1612 descp)
1613 "Make a OpenDocument link.
1614 OPT-PLIST is an options list.
1615 TYPE-1 is the device-type of the link (THIS://foo.html).
1616 PATH is the path of the link (http://THIS#location).
1617 FRAGMENT is the fragment part of the link, if any (foo.html#THIS).
1618 DESC is the link description, if any.
1619 ATTR is a string of other attributes of the a element."
1620 (declare (special org-lparse-par-open))
1621 (save-match-data
1622 (let* ((may-inline-p
1623 (and (member type-1 '("http" "https" "file"))
1624 (org-lparse-should-inline-p path descp)
1625 (not fragment)))
1626 (type (if (equal type-1 "id") "file" type-1))
1627 (filename path)
1628 (thefile path))
1629 (cond
1630 ;; check for inlined images
1631 ((and (member type '("file"))
1632 (not fragment)
1633 (org-file-image-p
1634 filename org-export-odt-inline-image-extensions)
1635 (or (eq t org-export-odt-inline-images)
1636 (and org-export-odt-inline-images (not descp))))
1637 (org-odt-format-inline-image thefile))
1638 ;; check for embedded formulas
1639 ((and (member type '("file"))
1640 (not fragment)
1641 (org-odt-is-formula-link-p filename)
1642 (or (not descp)))
1643 (org-odt-format-inline-formula thefile))
1644 ((string= type "coderef")
1645 (let* ((ref fragment)
1646 (lineno-or-ref (cdr (assoc ref org-export-code-refs)))
1647 (desc (and descp desc))
1648 (org-odt-suppress-xref nil)
1649 (href (org-xml-format-href (concat "#coderef-" ref))))
1650 (cond
1651 ((and (numberp lineno-or-ref) (not desc))
1652 (org-odt-format-link lineno-or-ref href))
1653 ((and (numberp lineno-or-ref) desc
1654 (string-match (regexp-quote (concat "(" ref ")")) desc))
1655 (format (replace-match "%s" t t desc)
1656 (org-odt-format-link lineno-or-ref href)))
1658 (setq desc (format
1659 (if (and desc (string-match
1660 (regexp-quote (concat "(" ref ")"))
1661 desc))
1662 (replace-match "%s" t t desc)
1663 (or desc "%s"))
1664 lineno-or-ref))
1665 (org-odt-format-link (org-xml-format-desc desc) href)))))
1667 (when (string= type "file")
1668 (setq thefile
1669 (cond
1670 ((file-name-absolute-p path)
1671 (concat "file://" (expand-file-name path)))
1672 (t (org-odt-relocate-relative-path
1673 thefile org-current-export-file)))))
1675 (when (and (member type '("" "http" "https" "file")) fragment)
1676 (setq thefile (concat thefile "#" fragment)))
1678 (setq thefile (org-xml-format-href thefile))
1680 (when (not (member type '("" "file")))
1681 (setq thefile (concat type ":" thefile)))
1683 (let ((org-odt-suppress-xref nil))
1684 (org-odt-format-link
1685 (org-xml-format-desc desc) thefile attr)))))))
1687 (defun org-odt-format-heading (text level &optional id)
1688 (let* ((text (if id (org-odt-format-target text id) text)))
1689 (org-odt-format-tags
1690 '("<text:h text:style-name=\"Heading_20_%s\" text:outline-level=\"%s\">" .
1691 "</text:h>") text level level)))
1693 (defun org-odt-format-headline (title extra-targets tags
1694 &optional snumber level)
1695 (concat
1696 (org-lparse-format 'EXTRA-TARGETS extra-targets)
1698 ;; No need to generate section numbers. They are auto-generated by
1699 ;; the application
1701 ;; (concat (org-lparse-format 'SECTION-NUMBER snumber level) " ")
1702 title
1703 (and tags (concat (org-lparse-format 'SPACES 3)
1704 (org-lparse-format 'ORG-TAGS tags)))))
1706 (defun org-odt-format-anchor (text name &optional class)
1707 (org-odt-format-target text name))
1709 (defun org-odt-format-bookmark (text id)
1710 (if id
1711 (org-odt-format-tags "<text:bookmark text:name=\"%s\"/>" text id)
1712 text))
1714 (defun org-odt-format-target (text id)
1715 (let ((name (concat org-export-odt-bookmark-prefix id)))
1716 (concat
1717 (and id (org-odt-format-tags
1718 "<text:bookmark-start text:name=\"%s\"/>" "" name))
1719 (org-odt-format-bookmark text id)
1720 (and id (org-odt-format-tags
1721 "<text:bookmark-end text:name=\"%s\"/>" "" name)))))
1723 (defun org-odt-format-footnote (n def)
1724 (let ((id (concat "fn" n))
1725 (note-class "footnote")
1726 (par-style "Footnote"))
1727 (org-odt-format-tags
1728 '("<text:note text:id=\"%s\" text:note-class=\"%s\">" .
1729 "</text:note>")
1730 (concat
1731 (org-odt-format-tags
1732 '("<text:note-citation>" . "</text:note-citation>")
1734 (org-odt-format-tags
1735 '("<text:note-body>" . "</text:note-body>")
1736 def))
1737 id note-class)))
1739 (defun org-odt-format-footnote-reference (n def refcnt)
1740 (if (= refcnt 1)
1741 (org-odt-format-footnote n def)
1742 (org-odt-format-footnote-ref n)))
1744 (defun org-odt-format-footnote-ref (n)
1745 (let ((note-class "footnote")
1746 (ref-format "text")
1747 (ref-name (concat "fn" n)))
1748 (org-odt-format-tags
1749 '("<text:span text:style-name=\"%s\">" . "</text:span>")
1750 (org-odt-format-tags
1751 '("<text:note-ref text:note-class=\"%s\" text:reference-format=\"%s\" text:ref-name=\"%s\">" . "</text:note-ref>")
1752 n note-class ref-format ref-name)
1753 "OrgSuperscript")))
1755 (defun org-odt-get-image-name (file-name)
1756 (require 'sha1)
1757 (file-relative-name
1758 (expand-file-name
1759 (concat (sha1 file-name) "." (file-name-extension file-name)) "Pictures")))
1761 (defun org-export-odt-format-image (src href)
1762 "Create image tag with source and attributes."
1763 (save-match-data
1764 (let* ((caption (org-find-text-property-in-string 'org-caption src))
1765 (caption (and caption (org-xml-format-desc caption)))
1766 (attr (org-find-text-property-in-string 'org-attributes src))
1767 (label (org-find-text-property-in-string 'org-label src))
1768 (latex-frag (org-find-text-property-in-string
1769 'org-latex-src src))
1770 (category (and latex-frag "__DvipngImage__"))
1771 (attr-plist (org-lparse-get-block-params attr))
1772 (user-frame-anchor
1773 (car (assoc-string (plist-get attr-plist :anchor)
1774 '(("as-char") ("paragraph") ("page")) t)))
1775 (user-frame-style
1776 (and user-frame-anchor (plist-get attr-plist :style)))
1777 (user-frame-attrs
1778 (and user-frame-anchor (plist-get attr-plist :attributes)))
1779 (user-frame-params
1780 (list user-frame-style user-frame-attrs user-frame-anchor))
1781 (embed-as (cond
1782 (latex-frag
1783 (symbol-name
1784 (case (org-find-text-property-in-string
1785 'org-latex-src-embed-type src)
1786 (paragraph 'paragraph)
1787 (t 'as-char))))
1788 (user-frame-anchor)
1789 (t "paragraph")))
1790 (size (org-odt-image-size-from-file
1791 src (plist-get attr-plist :width)
1792 (plist-get attr-plist :height)
1793 (plist-get attr-plist :scale) nil embed-as))
1794 (width (car size)) (height (cdr size)))
1795 (when latex-frag
1796 (setq href (org-propertize href :title "LaTeX Fragment"
1797 :description latex-frag)))
1798 (let ((frame-style-handle (concat (and (or caption label) "Captioned")
1799 embed-as "Image")))
1800 (org-odt-format-entity
1801 frame-style-handle href width height
1802 :caption caption :label label :category category
1803 :user-frame-params user-frame-params)))))
1805 (defun org-odt-format-object-description (title description)
1806 (concat (and title (org-odt-format-tags
1807 '("<svg:title>" . "</svg:title>")
1808 (org-odt-encode-plain-text title t)))
1809 (and description (org-odt-format-tags
1810 '("<svg:desc>" . "</svg:desc>")
1811 (org-odt-encode-plain-text description t)))))
1813 (defun org-odt-format-frame (text width height style &optional
1814 extra anchor-type)
1815 (let ((frame-attrs
1816 (concat
1817 (if width (format " svg:width=\"%0.2fcm\"" width) "")
1818 (if height (format " svg:height=\"%0.2fcm\"" height) "")
1819 extra
1820 (format " text:anchor-type=\"%s\"" (or anchor-type "paragraph")))))
1821 (org-odt-format-tags
1822 '("<draw:frame draw:style-name=\"%s\"%s>" . "</draw:frame>")
1823 (concat text (org-odt-format-object-description
1824 (get-text-property 0 :title text)
1825 (get-text-property 0 :description text)))
1826 style frame-attrs)))
1828 (defun org-odt-format-textbox (text width height style &optional
1829 extra anchor-type)
1830 (org-odt-format-frame
1831 (org-odt-format-tags
1832 '("<draw:text-box %s>" . "</draw:text-box>")
1833 text (concat (format " fo:min-height=\"%0.2fcm\"" (or height .2))
1834 (unless width
1835 (format " fo:min-width=\"%0.2fcm\"" (or width .2)))))
1836 width nil style extra anchor-type))
1838 (defun org-odt-format-inlinetask (heading content
1839 &optional todo priority tags)
1840 (org-odt-format-stylized-paragraph
1841 nil (org-odt-format-textbox
1842 (concat (org-odt-format-stylized-paragraph
1843 "OrgInlineTaskHeading"
1844 (org-lparse-format
1845 'HEADLINE (concat (org-lparse-format-todo todo) " " heading)
1846 nil tags))
1847 content) nil nil "OrgInlineTaskFrame" " style:rel-width=\"100%\"")))
1849 (defvar org-odt-entity-frame-styles
1850 '(("As-CharImage" "__Figure__" ("OrgInlineImage" nil "as-char"))
1851 ("ParagraphImage" "__Figure__" ("OrgDisplayImage" nil "paragraph"))
1852 ("PageImage" "__Figure__" ("OrgPageImage" nil "page"))
1853 ("CaptionedAs-CharImage" "__Figure__"
1854 ("OrgCaptionedImage"
1855 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
1856 ("OrgInlineImage" nil "as-char"))
1857 ("CaptionedParagraphImage" "__Figure__"
1858 ("OrgCaptionedImage"
1859 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
1860 ("OrgImageCaptionFrame" nil "paragraph"))
1861 ("CaptionedPageImage" "__Figure__"
1862 ("OrgCaptionedImage"
1863 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
1864 ("OrgPageImageCaptionFrame" nil "page"))
1865 ("InlineFormula" "__MathFormula__" ("OrgInlineFormula" nil "as-char"))
1866 ("DisplayFormula" "__MathFormula__" ("OrgDisplayFormula" nil "as-char"))
1867 ("CaptionedDisplayFormula" "__MathFormula__"
1868 ("OrgCaptionedFormula" nil "paragraph")
1869 ("OrgFormulaCaptionFrame" nil "as-char"))))
1871 (defun org-odt-merge-frame-params(default-frame-params user-frame-params)
1872 (if (not user-frame-params) default-frame-params
1873 (assert (= (length default-frame-params) 3))
1874 (assert (= (length user-frame-params) 3))
1875 (loop for user-frame-param in user-frame-params
1876 for default-frame-param in default-frame-params
1877 collect (or user-frame-param default-frame-param))))
1879 (defun* org-odt-format-entity (entity href width height
1880 &key caption label category
1881 user-frame-params)
1882 (let* ((entity-style (assoc-string entity org-odt-entity-frame-styles t))
1883 default-frame-params frame-params)
1884 (cond
1885 ((not (or caption label))
1886 (setq default-frame-params (nth 2 entity-style))
1887 (setq frame-params (org-odt-merge-frame-params
1888 default-frame-params user-frame-params))
1889 (apply 'org-odt-format-frame href width height frame-params))
1891 (setq default-frame-params (nth 3 entity-style))
1892 (setq frame-params (org-odt-merge-frame-params
1893 default-frame-params user-frame-params))
1894 (apply 'org-odt-format-textbox
1895 (org-odt-format-stylized-paragraph
1896 'illustration
1897 (concat
1898 (apply 'org-odt-format-frame href width height
1899 (nth 2 entity-style))
1900 (org-odt-format-entity-caption
1901 label caption (or category (nth 1 entity-style)))))
1902 width height frame-params)))))
1904 (defvar org-odt-embedded-images-count 0)
1905 (defun org-odt-copy-image-file (path)
1906 "Returns the internal name of the file"
1907 (let* ((image-type (file-name-extension path))
1908 (media-type (format "image/%s" image-type))
1909 (src-file (expand-file-name
1910 path (file-name-directory org-current-export-file)))
1911 (target-dir "Images/")
1912 (target-file
1913 (format "%s%04d.%s" target-dir
1914 (incf org-odt-embedded-images-count) image-type)))
1915 (when (not org-lparse-to-buffer)
1916 (message "Embedding %s as %s ..."
1917 (substring-no-properties path) target-file)
1919 (when (= 1 org-odt-embedded-images-count)
1920 (make-directory target-dir)
1921 (org-odt-create-manifest-file-entry "" target-dir))
1923 (copy-file src-file target-file 'overwrite)
1924 (org-odt-create-manifest-file-entry media-type target-file))
1925 target-file))
1927 (defvar org-export-odt-image-size-probe-method
1928 '(emacs imagemagick force)
1929 "Ordered list of methods by for determining size of an embedded
1930 image.")
1932 (defvar org-export-odt-default-image-sizes-alist
1933 '(("as-char" . (5 . 0.4))
1934 ("paragraph" . (5 . 5)))
1935 "Hardcoded image dimensions one for each of the anchor
1936 methods.")
1938 ;; A4 page size is 21.0 by 29.7 cms
1939 ;; The default page settings has 2cm margin on each of the sides. So
1940 ;; the effective text area is 17.0 by 25.7 cm
1941 (defvar org-export-odt-max-image-size '(17.0 . 20.0)
1942 "Limiting dimensions for an embedded image.")
1944 (defun org-odt-do-image-size (probe-method file &optional dpi anchor-type)
1945 (setq dpi (or dpi org-export-odt-pixels-per-inch))
1946 (setq anchor-type (or anchor-type "paragraph"))
1947 (flet ((size-in-cms (size-in-pixels)
1948 (flet ((pixels-to-cms (pixels)
1949 (let* ((cms-per-inch 2.54)
1950 (inches (/ pixels dpi)))
1951 (* cms-per-inch inches))))
1952 (and size-in-pixels
1953 (cons (pixels-to-cms (car size-in-pixels))
1954 (pixels-to-cms (cdr size-in-pixels)))))))
1955 (case probe-method
1956 (emacs
1957 (size-in-cms (ignore-errors (image-size (create-image file) 'pixels))))
1958 (imagemagick
1959 (size-in-cms
1960 (let ((dim (shell-command-to-string
1961 (format "identify -format \"%%w:%%h\" \"%s\"" file))))
1962 (when (string-match "\\([0-9]+\\):\\([0-9]+\\)" dim)
1963 (cons (string-to-number (match-string 1 dim))
1964 (string-to-number (match-string 2 dim)))))))
1966 (cdr (assoc-string anchor-type
1967 org-export-odt-default-image-sizes-alist))))))
1969 (defun org-odt-image-size-from-file (file &optional user-width
1970 user-height scale dpi embed-as)
1971 (unless (file-name-absolute-p file)
1972 (setq file (expand-file-name
1973 file (file-name-directory org-current-export-file))))
1974 (let* (size width height)
1975 (unless (and user-height user-width)
1976 (loop for probe-method in org-export-odt-image-size-probe-method
1977 until size
1978 do (setq size (org-odt-do-image-size
1979 probe-method file dpi embed-as)))
1980 (or size (error "Cannot determine Image size. Aborting ..."))
1981 (setq width (car size) height (cdr size)))
1982 (cond
1983 (scale
1984 (setq width (* width scale) height (* height scale)))
1985 ((and user-height user-width)
1986 (setq width user-width height user-height))
1987 (user-height
1988 (setq width (* user-height (/ width height)) height user-height))
1989 (user-width
1990 (setq height (* user-width (/ height width)) width user-width))
1991 (t (ignore)))
1992 ;; ensure that an embedded image fits comfortably within a page
1993 (let ((max-width (car org-export-odt-max-image-size))
1994 (max-height (cdr org-export-odt-max-image-size)))
1995 (when (or (> width max-width) (> height max-height))
1996 (let* ((scale1 (/ max-width width))
1997 (scale2 (/ max-height height))
1998 (scale (min scale1 scale2)))
1999 (setq width (* scale width) height (* scale height)))))
2000 (cons width height)))
2002 (defvar org-odt-entity-labels-alist nil
2003 "Associate Labels with the Labeled entities.
2004 Each element of the alist is of the form (LABEL-NAME
2005 CATEGORY-NAME SEQNO LABEL-STYLE-NAME). LABEL-NAME is same as
2006 that specified by \"#+LABEL: ...\" line. CATEGORY-NAME is the
2007 type of the entity that LABEL-NAME is attached to. CATEGORY-NAME
2008 can be one of \"Table\", \"Figure\" or \"Equation\". SEQNO is
2009 the unique number assigned to the referenced entity on a
2010 per-CATEGORY basis. It is generated sequentially and is 1-based.
2011 LABEL-STYLE-NAME is a key `org-odt-label-styles'.
2013 See `org-odt-add-label-definition' and
2014 `org-odt-fixup-label-references'.")
2016 (defvar org-odt-entity-counts-plist nil
2017 "Plist of running counters of SEQNOs for each of the CATEGORY-NAMEs.
2018 See `org-odt-entity-labels-alist' for known CATEGORY-NAMEs.")
2020 (defvar org-odt-label-styles
2021 '(("text" "(%n)" "text" "(%n)")
2022 ("category-and-value" "%e %n%c" "category-and-value" "%e %n")
2023 ("value" "%e %n%c" "value" "%n"))
2024 "Specify how labels are applied and referenced.
2025 This is an alist where each element is of the
2026 form (LABEL-STYLE-NAME LABEL-ATTACH-FMT LABEL-REF-MODE
2027 LABEL-REF-FMT).
2029 LABEL-ATTACH-FMT controls how labels and captions are attached to
2030 an entity. It may contain following specifiers - %e, %n and %c.
2031 %e is replaced with the CATEGORY-NAME. %n is replaced with
2032 \"<text:sequence ...> SEQNO </text:sequence>\". %c is replaced
2033 with CAPTION. See `org-odt-format-label-definition'.
2035 LABEL-REF-MODE and LABEL-REF-FMT controls how label references
2036 are generated. The following XML is generated for a label
2037 reference - \"<text:sequence-ref
2038 text:reference-format=\"LABEL-REF-MODE\" ...> LABEL-REF-FMT
2039 </text:sequence-ref>\". LABEL-REF-FMT may contain following
2040 specifiers - %e and %n. %e is replaced with the CATEGORY-NAME.
2041 %n is replaced with SEQNO. See
2042 `org-odt-format-label-reference'.")
2044 (defvar org-odt-category-map-alist
2045 '(("__Table__" "Table" "value")
2046 ("__Figure__" "Figure" "value")
2047 ("__MathFormula__" "Equation" "text")
2048 ("__DvipngImage__" "Equation" "value")
2049 ;; ("__Table__" "Table" "category-and-value")
2050 ;; ("__Figure__" "Figure" "category-and-value")
2051 ;; ("__DvipngImage__" "Equation" "category-and-value")
2053 "Map a CATEGORY-HANDLE to CATEGORY-NAME and LABEL-STYLE.
2054 This is an alist where each element is of the form
2055 \\(CATEGORY-HANDLE CATEGORY-NAME LABEL-STYLE\\). CATEGORY_HANDLE
2056 could either be one of the internal handles (as seen above) or be
2057 derived from the \"#+LABEL:<label-name>\" specification. See
2058 `org-export-odt-get-category-from-label'. CATEGORY-NAME and
2059 LABEL-STYLE are used for generating ODT labels. See
2060 `org-odt-label-styles'.")
2062 (defvar org-export-odt-user-categories
2063 '("Illustration" "Table" "Text" "Drawing" "Equation" "Figure"))
2065 (defvar org-export-odt-get-category-from-label nil
2066 "Should category of label be inferred from label itself.
2067 When this option is non-nil, a label is parsed in to two
2068 component parts delimited by a \":\" (colon) as shown here -
2069 #+LABEL:[CATEGORY-HANDLE:]EXTRA. The CATEGORY-HANDLE is mapped
2070 to a CATEGORY-NAME and LABEL-STYLE using
2071 `org-odt-category-map-alist'. (If no such map is provided and
2072 CATEGORY-NAME is set to CATEGORY-HANDLE and LABEL-STYLE is set to
2073 \"category-and-value\"). If CATEGORY-NAME so obtained is listed
2074 under `org-export-odt-user-categories' then the user specified
2075 styles are used. Otherwise styles as determined by the internal
2076 CATEGORY-HANDLE is used. See
2077 `org-odt-get-label-category-and-style' for details.")
2079 (defun org-odt-get-label-category-and-style (label default-category)
2080 "See `org-export-odt-get-category-from-label'."
2081 (let ((default-category-map
2082 (assoc default-category org-odt-category-map-alist))
2083 user-category user-category-map category)
2084 (cond
2085 ((not org-export-odt-get-category-from-label)
2086 default-category-map)
2087 ((not (setq user-category
2088 (save-match-data
2089 (and (string-match "\\`\\(.*\\):.+" label)
2090 (match-string 1 label)))))
2091 default-category-map)
2093 (setq user-category-map
2094 (or (assoc user-category org-odt-category-map-alist)
2095 (list nil user-category "category-and-value"))
2096 category (nth 1 user-category-map))
2097 (if (member category org-export-odt-user-categories)
2098 user-category-map
2099 default-category-map)))))
2101 (defun org-odt-add-label-definition (label default-category)
2102 "Create an entry in `org-odt-entity-labels-alist' and return it."
2103 (setq label (substring-no-properties label))
2104 (let* ((label-props (org-odt-get-label-category-and-style
2105 label default-category))
2106 (category (nth 1 label-props))
2107 (counter category)
2108 (label-style (nth 2 label-props))
2109 (sequence-var (intern (mapconcat
2110 'downcase
2111 (org-split-string counter) "-")))
2112 (seqno (1+ (or (plist-get org-odt-entity-counts-plist sequence-var)
2113 0)))
2114 (label-props (list label category seqno label-style)))
2115 (setq org-odt-entity-counts-plist
2116 (plist-put org-odt-entity-counts-plist sequence-var seqno))
2117 (push label-props org-odt-entity-labels-alist)
2118 label-props))
2120 (defun org-odt-format-label-definition (caption label category seqno label-style)
2121 (assert label)
2122 (format-spec
2123 (cadr (assoc-string label-style org-odt-label-styles t))
2124 `((?e . ,category)
2125 (?n . ,(org-odt-format-tags
2126 '("<text:sequence text:ref-name=\"%s\" text:name=\"%s\" text:formula=\"ooow:%s+1\" style:num-format=\"1\">" . "</text:sequence>")
2127 (format "%d" seqno) label category category))
2128 (?c . ,(or (and caption (concat ": " caption)) "")))))
2130 (defun org-odt-format-label-reference (label category seqno label-style)
2131 (assert label)
2132 (save-match-data
2133 (let* ((fmt (cddr (assoc-string label-style org-odt-label-styles t)))
2134 (fmt1 (car fmt))
2135 (fmt2 (cadr fmt)))
2136 (org-odt-format-tags
2137 '("<text:sequence-ref text:reference-format=\"%s\" text:ref-name=\"%s\">"
2138 . "</text:sequence-ref>")
2139 (format-spec fmt2 `((?e . ,category)
2140 (?n . ,(format "%d" seqno)))) fmt1 label))))
2142 (defun org-odt-fixup-label-references ()
2143 (goto-char (point-min))
2144 (while (re-search-forward
2145 "<text:sequence-ref text:ref-name=\"\\([^\"]+\\)\">[ \t\n]*</text:sequence-ref>"
2146 nil t)
2147 (let* ((label (match-string 1))
2148 (label-def (assoc label org-odt-entity-labels-alist))
2149 (rpl (and label-def
2150 (apply 'org-odt-format-label-reference label-def))))
2151 (if rpl (replace-match rpl t t)
2152 (org-lparse-warn
2153 (format "Unable to resolve reference to label \"%s\"" label))))))
2155 (defun org-odt-format-entity-caption (label caption category)
2156 (or (and label
2157 (apply 'org-odt-format-label-definition
2158 caption (org-odt-add-label-definition label category)))
2159 caption ""))
2161 (defun org-odt-format-tags (tag text &rest args)
2162 (let ((prefix (when org-lparse-encode-pending "@"))
2163 (suffix (when org-lparse-encode-pending "@")))
2164 (apply 'org-lparse-format-tags tag text prefix suffix args)))
2166 (defvar org-odt-manifest-file-entries nil)
2167 (defun org-odt-init-outfile (filename)
2168 (unless (executable-find "zip")
2169 ;; Not at all OSes ship with zip by default
2170 (error "Executable \"zip\" needed for creating OpenDocument files"))
2172 (let* ((outdir (make-temp-file
2173 (format org-export-odt-tmpdir-prefix org-lparse-backend) t))
2174 (content-file (expand-file-name "content.xml" outdir)))
2176 ;; init conten.xml
2177 (with-current-buffer (find-file-noselect content-file t))
2179 ;; reset variables
2180 (setq org-odt-manifest-file-entries nil
2181 org-odt-embedded-images-count 0
2182 org-odt-embedded-formulas-count 0
2183 org-odt-entity-labels-alist nil
2184 org-odt-list-stack-stashed nil
2185 org-odt-automatic-styles nil
2186 org-odt-object-counters nil
2187 org-odt-entity-counts-plist nil)
2188 content-file))
2190 (defcustom org-export-odt-prettify-xml nil
2191 "Specify whether or not the xml output should be prettified.
2192 When this option is turned on, `indent-region' is run on all
2193 component xml buffers before they are saved. Turn this off for
2194 regular use. Turn this on if you need to examine the xml
2195 visually."
2196 :group 'org-export-odt
2197 :type 'boolean)
2199 (defvar hfy-user-sheet-assoc) ; bound during org-do-lparse
2200 (defun org-odt-save-as-outfile (target opt-plist)
2201 ;; write automatic styles
2202 (org-odt-write-automatic-styles)
2204 ;; write meta file
2205 (org-odt-update-meta-file opt-plist)
2207 ;; write styles file
2208 (when (equal org-lparse-backend 'odt)
2209 (org-odt-update-styles-file opt-plist))
2211 ;; create mimetype file
2212 (let ((mimetype (org-odt-write-mimetype-file org-lparse-backend)))
2213 (org-odt-create-manifest-file-entry mimetype "/" "1.2"))
2215 ;; create a manifest entry for content.xml
2216 (org-odt-create-manifest-file-entry "text/xml" "content.xml")
2218 ;; write out the manifest entries before zipping
2219 (org-odt-write-manifest-file)
2221 (let ((xml-files '("mimetype" "META-INF/manifest.xml" "content.xml"
2222 "meta.xml"))
2223 (zipdir default-directory))
2224 (when (equal org-lparse-backend 'odt)
2225 (push "styles.xml" xml-files))
2226 (message "Switching to directory %s" (expand-file-name zipdir))
2228 ;; save all xml files
2229 (mapc (lambda (file)
2230 (with-current-buffer
2231 (find-file-noselect (expand-file-name file) t)
2232 ;; prettify output if needed
2233 (when org-export-odt-prettify-xml
2234 (indent-region (point-min) (point-max)))
2235 (save-buffer 0)))
2236 xml-files)
2238 (let* ((target-name (file-name-nondirectory target))
2239 (target-dir (file-name-directory target))
2240 (cmds `(("zip" "-mX0" ,target-name "mimetype")
2241 ("zip" "-rmTq" ,target-name "."))))
2242 (when (file-exists-p target)
2243 ;; FIXME: If the file is locked this throws a cryptic error
2244 (delete-file target))
2246 (let ((coding-system-for-write 'no-conversion) exitcode err-string)
2247 (message "Creating odt file...")
2248 (mapc
2249 (lambda (cmd)
2250 (message "Running %s" (mapconcat 'identity cmd " "))
2251 (setq err-string
2252 (with-output-to-string
2253 (setq exitcode
2254 (apply 'call-process (car cmd)
2255 nil standard-output nil (cdr cmd)))))
2256 (or (zerop exitcode)
2257 (ignore (message "%s" err-string))
2258 (error "Unable to create odt file (%S)" exitcode)))
2259 cmds))
2261 ;; move the file from outdir to target-dir
2262 (rename-file target-name target-dir)
2264 ;; kill all xml buffers
2265 (mapc (lambda (file)
2266 (kill-buffer
2267 (find-file-noselect (expand-file-name file zipdir) t)))
2268 xml-files)
2270 (delete-directory zipdir)))
2271 (message "Created %s" target)
2272 (set-buffer (find-file-noselect target t)))
2274 (defconst org-odt-manifest-file-entry-tag
2276 <manifest:file-entry manifest:media-type=\"%s\" manifest:full-path=\"%s\"%s/>")
2278 (defun org-odt-create-manifest-file-entry (&rest args)
2279 (push args org-odt-manifest-file-entries))
2281 (defun org-odt-write-manifest-file ()
2282 (make-directory "META-INF")
2283 (let ((manifest-file (expand-file-name "META-INF/manifest.xml")))
2284 (with-current-buffer
2285 (find-file-noselect manifest-file t)
2286 (insert
2287 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
2288 <manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"1.2\">\n")
2289 (mapc
2290 (lambda (file-entry)
2291 (let* ((version (nth 2 file-entry))
2292 (extra (if version
2293 (format " manifest:version=\"%s\"" version)
2294 "")))
2295 (insert
2296 (format org-odt-manifest-file-entry-tag
2297 (nth 0 file-entry) (nth 1 file-entry) extra))))
2298 org-odt-manifest-file-entries)
2299 (insert "\n</manifest:manifest>"))))
2301 (defun org-odt-update-meta-file (opt-plist)
2302 (let ((date (org-odt-format-date (plist-get opt-plist :date)))
2303 (author (or (plist-get opt-plist :author) ""))
2304 (email (plist-get opt-plist :email))
2305 (keywords (plist-get opt-plist :keywords))
2306 (description (plist-get opt-plist :description))
2307 (title (plist-get opt-plist :title)))
2308 (write-region
2309 (concat
2310 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
2311 <office:document-meta
2312 xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"
2313 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2314 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2315 xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"
2316 xmlns:ooo=\"http://openoffice.org/2004/office\"
2317 office:version=\"1.2\">
2318 <office:meta>" "\n"
2319 (org-odt-format-author)
2320 (org-odt-format-tags
2321 '("\n<meta:initial-creator>" . "</meta:initial-creator>") author)
2322 (org-odt-format-tags '("\n<dc:date>" . "</dc:date>") date)
2323 (org-odt-format-tags
2324 '("\n<meta:creation-date>" . "</meta:creation-date>") date)
2325 (org-odt-format-tags '("\n<meta:generator>" . "</meta:generator>")
2326 (when org-export-creator-info
2327 (format "Org-%s/Emacs-%s"
2328 org-version emacs-version)))
2329 (org-odt-format-tags '("\n<meta:keyword>" . "</meta:keyword>") keywords)
2330 (org-odt-format-tags '("\n<dc:subject>" . "</dc:subject>") description)
2331 (org-odt-format-tags '("\n<dc:title>" . "</dc:title>") title)
2332 "\n"
2333 " </office:meta>" "</office:document-meta>")
2334 nil (expand-file-name "meta.xml")))
2336 ;; create a manifest entry for meta.xml
2337 (org-odt-create-manifest-file-entry "text/xml" "meta.xml"))
2339 (defun org-odt-update-styles-file (opt-plist)
2340 ;; write styles file
2341 (let ((styles-file (plist-get opt-plist :odt-styles-file)))
2342 (org-odt-copy-styles-file (and styles-file
2343 (read (org-trim styles-file)))))
2345 ;; Update styles.xml - take care of outline numbering
2346 (with-current-buffer
2347 (find-file-noselect (expand-file-name "styles.xml") t)
2348 ;; Don't make automatic backup of styles.xml file. This setting
2349 ;; prevents the backed-up styles.xml file from being zipped in to
2350 ;; odt file. This is more of a hackish fix. Better alternative
2351 ;; would be to fix the zip command so that the output odt file
2352 ;; includes only the needed files and excludes any auto-generated
2353 ;; extra files like backups and auto-saves etc etc. Note that
2354 ;; currently the zip command zips up the entire temp directory so
2355 ;; that any auto-generated files created under the hood ends up in
2356 ;; the resulting odt file.
2357 (set (make-local-variable 'backup-inhibited) t)
2359 ;; Import local setting of `org-export-with-section-numbers'
2360 (org-lparse-bind-local-variables opt-plist)
2361 (org-odt-configure-outline-numbering
2362 (if org-export-with-section-numbers org-export-headline-levels 0)))
2364 ;; Write custom styles for source blocks
2365 (org-odt-insert-custom-styles-for-srcblocks
2366 (mapconcat
2367 (lambda (style)
2368 (format " %s\n" (cddr style)))
2369 hfy-user-sheet-assoc "")))
2371 (defun org-odt-write-mimetype-file (format)
2372 ;; create mimetype file
2373 (let ((mimetype
2374 (case format
2375 (odt "application/vnd.oasis.opendocument.text")
2376 (odf "application/vnd.oasis.opendocument.formula")
2377 (t (error "Unknown OpenDocument backend %S" org-lparse-backend)))))
2378 (write-region mimetype nil (expand-file-name "mimetype"))
2379 mimetype))
2381 (defun org-odt-finalize-outfile ()
2382 (org-odt-delete-empty-paragraphs))
2384 (defun org-odt-delete-empty-paragraphs ()
2385 (goto-char (point-min))
2386 (let ((open "<text:p[^>]*>")
2387 (close "</text:p>"))
2388 (while (re-search-forward (format "%s[ \r\n\t]*%s" open close) nil t)
2389 (replace-match ""))))
2391 (defcustom org-export-odt-convert-processes
2392 '(("BasicODConverter"
2393 ("soffice" "-norestore" "-invisible" "-headless"
2394 "\"macro:///BasicODConverter.Main.Convert(%I,%f,%O)\""))
2395 ("unoconv"
2396 ("unoconv" "-f" "%f" "-o" "%d" "%i")))
2397 "Specify a list of document converters and their usage.
2398 The converters in this list are offered as choices while
2399 customizing `org-export-odt-convert-process'.
2401 This variable is an alist where each element is of the
2402 form (CONVERTER-NAME CONVERTER-PROCESS). CONVERTER-NAME is name
2403 of the converter. CONVERTER-PROCESS specifies the command-line
2404 syntax of the converter and is of the form (CONVERTER-PROGRAM
2405 ARG1 ARG2 ...). CONVERTER-PROGRAM is the name of the executable.
2406 ARG1, ARG2 etc are command line options that are passed to
2407 CONVERTER-PROGRAM. Format specifiers can be used in the ARGs and
2408 they are interpreted as below:
2410 %i input file name in full
2411 %I input file name as a URL
2412 %f format of the output file
2413 %o output file name in full
2414 %O output file name as a URL
2415 %d output dir in full
2416 %D output dir as a URL."
2417 :group 'org-export-odt
2418 :type
2419 '(choice
2420 (const :tag "None" nil)
2421 (alist :tag "Converters"
2422 :key-type (string :tag "Converter Name")
2423 :value-type (group (cons (string :tag "Executable")
2424 (repeat (string :tag "Command line args")))))))
2426 (defcustom org-export-odt-convert-process nil
2427 "Use this converter to convert from \"odt\" format to other formats.
2428 During customization, the list of converter names are populated
2429 from `org-export-odt-convert-processes'."
2430 :group 'org-export-odt
2431 :type '(choice :convert-widget
2432 (lambda (w)
2433 (apply 'widget-convert (widget-type w)
2434 (eval (car (widget-get w :args)))))
2435 `((const :tag "None" nil)
2436 ,@(mapcar (lambda (c)
2437 `(const :tag ,(car c) ,(car c)))
2438 org-export-odt-convert-processes))))
2440 (defcustom org-export-odt-convert-capabilities
2441 '(("Text"
2442 ("odt" "ott" "doc" "rtf")
2443 (("pdf" "pdf") ("odt" "odt") ("xhtml" "html") ("rtf" "rtf")
2444 ("ott" "ott") ("doc" "doc") ("ooxml" "xml") ("html" "html")))
2445 ("Web"
2446 ("html" "xhtml") (("pdf" "pdf") ("odt" "txt") ("html" "html")))
2447 ("Spreadsheet"
2448 ("ods" "ots" "xls" "csv")
2449 (("pdf" "pdf") ("ots" "ots") ("html" "html") ("csv" "csv")
2450 ("ods" "ods") ("xls" "xls") ("xhtml" "xhtml") ("ooxml" "xml")))
2451 ("Presentation"
2452 ("odp" "otp" "ppt")
2453 (("pdf" "pdf") ("swf" "swf") ("odp" "odp") ("xhtml" "xml")
2454 ("otp" "otp") ("ppt" "ppt") ("odg" "odg") ("html" "html"))))
2455 "Specify input and output formats of `org-export-odt-convert-process'.
2456 More correctly, specify the set of input and output formats that
2457 the user is actually interested in.
2459 This variable is an alist where each element is of the
2460 form (DOCUMENT-CLASS INPUT-FMT-LIST OUTPUT-FMT-ALIST).
2461 INPUT-FMT-LIST is a list of INPUT-FMTs. OUTPUT-FMT-ALIST is an
2462 alist where each element is of the form (OUTPUT-FMT
2463 OUTPUT-FILE-EXTENSION).
2465 The variable is interpreted as follows:
2466 `org-export-odt-convert-process' can take any document that is in
2467 INPUT-FMT-LIST and produce any document that is in the
2468 OUTPUT-FMT-LIST. A document converted to OUTPUT-FMT will have
2469 OUTPUT-FILE-EXTENSION as the file name extension. OUTPUT-FMT
2470 serves dual purposes:
2471 - It is used for populating completion candidates during
2472 `org-export-odt-convert' commands.
2473 - It is used as the value of \"%f\" specifier in
2474 `org-export-odt-convert-process'.
2476 DOCUMENT-CLASS is used to group a set of file formats in
2477 INPUT-FMT-LIST in to a single class.
2479 Note that this variable inherently captures how LibreOffice based
2480 converters work. LibreOffice maps documents of various formats
2481 to classes like Text, Web, Spreadsheet, Presentation etc and
2482 allow document of a given class (irrespective of it's source
2483 format) to be converted to any of the export formats associated
2484 with that class.
2486 See default setting of this variable for an typical
2487 configuration."
2488 :group 'org-export-odt
2489 :type
2490 '(choice
2491 (const :tag "None" nil)
2492 (alist :key-type (string :tag "Document Class")
2493 :value-type
2494 (group (repeat :tag "Input formats" (string :tag "Input format"))
2495 (alist :tag "Output formats"
2496 :key-type (string :tag "Output format")
2497 :value-type
2498 (group (string :tag "Output file extension")))))))
2500 (declare-function org-create-math-formula "org"
2501 (latex-frag &optional mathml-file))
2503 ;;;###autoload
2504 (defun org-export-odt-convert (&optional in-file out-fmt prefix-arg)
2505 "Convert IN-FILE to format OUT-FMT using a command line converter.
2506 IN-FILE is the file to be converted. If unspecified, it defaults
2507 to variable `buffer-file-name'. OUT-FMT is the desired output
2508 format. Use `org-export-odt-convert-process' as the converter.
2509 If PREFIX-ARG is non-nil then the newly converted file is opened
2510 using `org-open-file'."
2511 (interactive
2512 (append (org-lparse-convert-read-params) current-prefix-arg))
2513 (org-lparse-do-convert in-file out-fmt prefix-arg))
2515 (defun org-odt-get (what &optional opt-plist)
2516 (case what
2517 (BACKEND 'odt)
2518 (EXPORT-DIR (org-export-directory :html opt-plist))
2519 (FILE-NAME-EXTENSION "odt")
2520 (EXPORT-BUFFER-NAME "*Org ODT Export*")
2521 (ENTITY-CONTROL org-odt-entity-control-callbacks-alist)
2522 (ENTITY-FORMAT org-odt-entity-format-callbacks-alist)
2523 (INIT-METHOD 'org-odt-init-outfile)
2524 (FINAL-METHOD 'org-odt-finalize-outfile)
2525 (SAVE-METHOD 'org-odt-save-as-outfile)
2526 (CONVERT-METHOD
2527 (and org-export-odt-convert-process
2528 (cadr (assoc-string org-export-odt-convert-process
2529 org-export-odt-convert-processes t))))
2530 (CONVERT-CAPABILITIES
2531 (and org-export-odt-convert-process
2532 (cadr (assoc-string org-export-odt-convert-process
2533 org-export-odt-convert-processes t))
2534 org-export-odt-convert-capabilities))
2535 (TOPLEVEL-HLEVEL 1)
2536 (SPECIAL-STRING-REGEXPS org-export-odt-special-string-regexps)
2537 (INLINE-IMAGES 'maybe)
2538 (INLINE-IMAGE-EXTENSIONS '("png" "jpeg" "jpg" "gif" "svg"))
2539 (PLAIN-TEXT-MAP '(("&" . "&amp;") ("<" . "&lt;") (">" . "&gt;")))
2540 (TABLE-FIRST-COLUMN-AS-LABELS nil)
2541 (FOOTNOTE-SEPARATOR (org-lparse-format 'FONTIFY "," 'superscript))
2542 (CODING-SYSTEM-FOR-WRITE 'utf-8)
2543 (CODING-SYSTEM-FOR-SAVE 'utf-8)
2544 (t (error "Unknown property: %s" what))))
2546 (defvar org-lparse-latex-fragment-fallback) ; set by org-do-lparse
2547 (defun org-export-odt-do-preprocess-latex-fragments ()
2548 "Convert LaTeX fragments to images."
2549 (let* ((latex-frag-opt (plist-get org-lparse-opt-plist :LaTeX-fragments))
2550 (latex-frag-opt ; massage the options
2551 (or (and (member latex-frag-opt '(mathjax t))
2552 (not (and (fboundp 'org-format-latex-mathml-available-p)
2553 (org-format-latex-mathml-available-p)))
2554 (prog1 org-lparse-latex-fragment-fallback
2555 (org-lparse-warn
2556 (concat
2557 "LaTeX to MathML converter not available. "
2558 (format "Using %S instead."
2559 org-lparse-latex-fragment-fallback)))))
2560 latex-frag-opt))
2561 cache-dir display-msg)
2562 (cond
2563 ((eq latex-frag-opt 'dvipng)
2564 (setq cache-dir "ltxpng/")
2565 (setq display-msg "Creating LaTeX image %s"))
2566 ((member latex-frag-opt '(mathjax t))
2567 (setq latex-frag-opt 'mathml)
2568 (setq cache-dir "ltxmathml/")
2569 (setq display-msg "Creating MathML formula %s")))
2570 (when (and org-current-export-file)
2571 (org-format-latex
2572 (concat cache-dir (file-name-sans-extension
2573 (file-name-nondirectory org-current-export-file)))
2574 org-current-export-dir nil display-msg
2575 nil nil latex-frag-opt))))
2577 (defadvice org-format-latex-as-mathml
2578 (after org-odt-protect-latex-fragment activate)
2579 "Encode LaTeX fragment as XML.
2580 Do this when translation to MathML fails."
2581 (when (or (not (> (length ad-return-value) 0))
2582 (get-text-property 0 'org-protected ad-return-value))
2583 (setq ad-return-value
2584 (org-propertize (org-odt-encode-plain-text (ad-get-arg 0))
2585 'org-protected t))))
2587 (defun org-export-odt-preprocess-latex-fragments ()
2588 (when (equal org-export-current-backend 'odt)
2589 (org-export-odt-do-preprocess-latex-fragments)))
2591 (defun org-export-odt-preprocess-label-references ()
2592 (goto-char (point-min))
2593 (let (label label-components category value pretty-label)
2594 (while (re-search-forward "\\\\ref{\\([^{}\n]+\\)}" nil t)
2595 (org-if-unprotected-at (match-beginning 1)
2596 (replace-match
2597 (let ((org-lparse-encode-pending t)
2598 (label (match-string 1)))
2599 ;; markup generated below is mostly an eye-candy. At
2600 ;; pre-processing stage, there is no information on which
2601 ;; entity a label reference points to. The actual markup
2602 ;; is generated as part of `org-odt-fixup-label-references'
2603 ;; which gets called at the fag end of export. By this
2604 ;; time we would have seen and collected all the label
2605 ;; definitions in `org-odt-entity-labels-alist'.
2606 (org-odt-format-tags
2607 '("<text:sequence-ref text:ref-name=\"%s\">" .
2608 "</text:sequence-ref>")
2609 "" (org-add-props label '(org-protected t)))) t t)))))
2611 ;; process latex fragments as part of
2612 ;; `org-export-preprocess-after-blockquote-hook'. Note that this hook
2613 ;; is the one that is closest and well before the call to
2614 ;; `org-export-attach-captions-and-attributes' in
2615 ;; `org-export-preprocess-string'. The above arrangement permits
2616 ;; captions, labels and attributes to be attached to png images
2617 ;; generated out of latex equations.
2618 (add-hook 'org-export-preprocess-after-blockquote-hook
2619 'org-export-odt-preprocess-latex-fragments)
2621 (defun org-export-odt-preprocess (parameters)
2622 (org-export-odt-preprocess-label-references))
2624 (declare-function archive-zip-extract "arc-mode.el" (archive name))
2625 (defun org-odt-zip-extract-one (archive member &optional target)
2626 (require 'arc-mode)
2627 (let* ((target (or target default-directory))
2628 (archive (expand-file-name archive))
2629 (archive-zip-extract
2630 (list "unzip" "-qq" "-o" "-d" target))
2631 exit-code command-output)
2632 (setq command-output
2633 (with-temp-buffer
2634 (setq exit-code (archive-zip-extract archive member))
2635 (buffer-string)))
2636 (unless (zerop exit-code)
2637 (message command-output)
2638 (error "Extraction failed"))))
2640 (defun org-odt-zip-extract (archive members &optional target)
2641 (when (atom members) (setq members (list members)))
2642 (mapc (lambda (member)
2643 (org-odt-zip-extract-one archive member target))
2644 members))
2646 (defun org-odt-copy-styles-file (&optional styles-file)
2647 ;; Non-availability of styles.xml is not a critical error. For now
2648 ;; throw an error purely for aesthetic reasons.
2649 (setq styles-file (or styles-file
2650 org-export-odt-styles-file
2651 (expand-file-name "OrgOdtStyles.xml"
2652 org-odt-styles-dir)
2653 (error "org-odt: Missing styles file?")))
2654 (cond
2655 ((listp styles-file)
2656 (let ((archive (nth 0 styles-file))
2657 (members (nth 1 styles-file)))
2658 (org-odt-zip-extract archive members)
2659 (mapc
2660 (lambda (member)
2661 (when (org-file-image-p member)
2662 (let* ((image-type (file-name-extension member))
2663 (media-type (format "image/%s" image-type)))
2664 (org-odt-create-manifest-file-entry media-type member))))
2665 members)))
2666 ((and (stringp styles-file) (file-exists-p styles-file))
2667 (let ((styles-file-type (file-name-extension styles-file)))
2668 (cond
2669 ((string= styles-file-type "xml")
2670 (copy-file styles-file "styles.xml" t))
2671 ((member styles-file-type '("odt" "ott"))
2672 (org-odt-zip-extract styles-file "styles.xml")))))
2674 (error (format "Invalid specification of styles.xml file: %S"
2675 org-export-odt-styles-file))))
2677 ;; create a manifest entry for styles.xml
2678 (org-odt-create-manifest-file-entry "text/xml" "styles.xml"))
2680 (defvar org-export-odt-factory-settings
2681 "d4328fb9d1b6cb211d4320ff546829f26700dc5e"
2682 "SHA1 hash of OrgOdtStyles.xml.")
2684 (defun org-odt-configure-outline-numbering (level)
2685 "Outline numbering is retained only upto LEVEL.
2686 To disable outline numbering pass a LEVEL of 0."
2687 (goto-char (point-min))
2688 (let ((regex
2689 "<text:outline-level-style\\([^>]*\\)text:level=\"\\([^\"]*\\)\"\\([^>]*\\)>")
2690 (replacement
2691 "<text:outline-level-style\\1text:level=\"\\2\" style:num-format=\"\">"))
2692 (while (re-search-forward regex nil t)
2693 (when (> (string-to-number (match-string 2)) level)
2694 (replace-match replacement t nil))))
2695 (save-buffer 0))
2697 ;;;###autoload
2698 (defun org-export-as-odf (latex-frag &optional odf-file)
2699 "Export LATEX-FRAG as OpenDocument formula file ODF-FILE.
2700 Use `org-create-math-formula' to convert LATEX-FRAG first to
2701 MathML. When invoked as an interactive command, use
2702 `org-latex-regexps' to infer LATEX-FRAG from currently active
2703 region. If no LaTeX fragments are found, prompt for it. Push
2704 MathML source to kill ring, if `org-export-copy-to-kill-ring' is
2705 non-nil."
2706 (interactive
2707 `(,(let (frag)
2708 (setq frag (and (setq frag (and (region-active-p)
2709 (buffer-substring (region-beginning)
2710 (region-end))))
2711 (loop for e in org-latex-regexps
2712 thereis (when (string-match (nth 1 e) frag)
2713 (match-string (nth 2 e) frag)))))
2714 (read-string "LaTeX Fragment: " frag nil frag))
2715 ,(let ((odf-filename (expand-file-name
2716 (concat
2717 (file-name-sans-extension
2718 (or (file-name-nondirectory buffer-file-name)))
2719 "." "odf")
2720 (file-name-directory buffer-file-name))))
2721 (read-file-name "ODF filename: " nil odf-filename nil
2722 (file-name-nondirectory odf-filename)))))
2723 (let* ((org-lparse-backend 'odf)
2724 org-lparse-opt-plist
2725 (filename (or odf-file
2726 (expand-file-name
2727 (concat
2728 (file-name-sans-extension
2729 (or (file-name-nondirectory buffer-file-name)))
2730 "." "odf")
2731 (file-name-directory buffer-file-name))))
2732 (buffer (find-file-noselect (org-odt-init-outfile filename)))
2733 (coding-system-for-write 'utf-8)
2734 (save-buffer-coding-system 'utf-8))
2735 (set-buffer buffer)
2736 (set-buffer-file-coding-system coding-system-for-write)
2737 (let ((mathml (org-create-math-formula latex-frag)))
2738 (unless mathml (error "No Math formula created"))
2739 (insert mathml)
2740 (or (org-export-push-to-kill-ring
2741 (upcase (symbol-name org-lparse-backend)))
2742 (message "Exporting... done")))
2743 (org-odt-save-as-outfile filename nil)))
2745 ;;;###autoload
2746 (defun org-export-as-odf-and-open ()
2747 "Export LaTeX fragment as OpenDocument formula and immediately open it.
2748 Use `org-export-as-odf' to read LaTeX fragment and OpenDocument
2749 formula file."
2750 (interactive)
2751 (org-lparse-and-open
2752 nil nil nil (call-interactively 'org-export-as-odf)))
2754 (provide 'org-odt)
2756 ;;; org-odt.el ends here