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