1 ;;; org-odt.el --- OpenDocumentText export for Org-mode
3 ;; Copyright (C) 2010-2011 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 not (yet) part of GNU Emacs.
10 ;; However, it is distributed under the same license.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
33 (defgroup org-export-odt nil
34 "Options specific for ODT export of Org-mode files."
38 (defun org-odt-end-export ()
39 (org-odt-fixup-label-references)
41 ;; remove empty paragraphs
42 (goto-char (point-min))
43 (while (re-search-forward
44 "<text:p\\( text:style-name=\"Text_20_body\"\\)?>[ \r\n\t]*</text:p>"
47 (goto-char (point-min))
49 ;; Convert whitespace place holders
50 (goto-char (point-min))
52 (while (setq beg (next-single-property-change (point) 'org-whitespace))
53 (setq n (get-text-property beg 'org-whitespace)
54 end (next-single-property-change beg 'org-whitespace))
56 (delete-region beg end)
57 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
58 (make-string n ?x)))))
60 ;; Remove empty lines at the beginning of the file.
61 (goto-char (point-min))
62 (when (looking-at "\\s-+\n") (replace-match ""))
64 ;; Remove display properties
65 (remove-text-properties (point-min) (point-max) '(display t)))
67 (defvar org-odt-suppress-xref nil)
68 (defconst org-export-odt-special-string-regexps
69 '(("\\\\-" . "­\\1") ; shy
70 ("---\\([^-]\\)" . "—\\1") ; mdash
71 ("--\\([^-]\\)" . "–\\1") ; ndash
72 ("\\.\\.\\." . "…")) ; hellip
73 "Regular expressions for special string conversion.")
75 (defconst org-odt-lib-dir (file-name-directory load-file-name)
76 "Location of ODT exporter.
77 Use this to infer values of `org-odt-styles-dir' and
78 `org-export-odt-schema-dir'.")
80 (defvar org-odt-data-dir nil
81 "Data directory for ODT exporter.
82 Use this to infer values of `org-odt-styles-dir' and
83 `org-export-odt-schema-dir'.")
85 (defconst org-odt-schema-dir-list
88 (expand-file-name "./schema/" org-odt-data-dir)) ; bail out
90 (and (boundp 'org-odt-data-dir) org-odt-data-dir ; see make install
91 (expand-file-name "./schema/" org-odt-data-dir)))
92 (expand-file-name "../contrib/odt/etc/schema/" org-odt-lib-dir) ; git
94 "List of directories to search for OpenDocument schema files.
95 Use this list to set the default value of
96 `org-export-odt-schema-dir'. The entries in this list are
97 populated heuristically based on the values of `org-odt-lib-dir'
98 and `org-odt-data-dir'.")
100 (defcustom org-export-odt-schema-dir
103 (message "Debug (org-odt): Searching for OpenDocument schema files...")
107 (message "Debug (org-odt): Trying %s..." schema-dir)
108 (when (and (file-readable-p
109 (expand-file-name "od-manifest-schema-v1.2-cs01.rnc"
112 (expand-file-name "od-schema-v1.2-cs01.rnc"
115 (expand-file-name "schemas.xml" schema-dir)))
116 (message "Debug (org-odt): Using schema files under %s"
118 (throw 'schema-dir schema-dir))))
119 org-odt-schema-dir-list)
120 (message "Debug (org-odt): No OpenDocument schema files installed")
123 "Directory that contains OpenDocument schema files.
125 This directory contains:
126 1. rnc files for OpenDocument schema
127 2. a \"schemas.xml\" file that specifies locating rules needed
128 for auto validation of OpenDocument XML files.
130 Use the customize interface to set this variable. This ensures
131 that `rng-schema-locating-files' is updated and auto-validation
132 of OpenDocument XML takes place based on the value
133 `rng-nxml-auto-validate-flag'.
135 The default value of this variable varies depending on the
136 version of org in use and is initialized from
137 `org-odt-schema-dir-list'. The OASIS schema files are available
138 only in the org's private git repository. It is *not* bundled
139 with GNU ELPA tar or standard Emacs distribution."
141 (const :tag "Not set" nil)
142 (directory :tag "Schema directory"))
143 :group 'org-export-odt
146 "Set `org-export-odt-schema-dir'.
147 Also add it to `rng-schema-locating-files'."
148 (let ((schema-dir value))
152 (expand-file-name "od-manifest-schema-v1.2-cs01.rnc" schema-dir))
154 (expand-file-name "od-schema-v1.2-cs01.rnc" schema-dir))
156 (expand-file-name "schemas.xml" schema-dir)))
159 (message "Error (org-odt): %s has no OpenDocument schema files"
162 (when org-export-odt-schema-dir
163 (eval-after-load 'rng-loc
164 '(add-to-list 'rng-schema-locating-files
165 (expand-file-name "schemas.xml"
166 org-export-odt-schema-dir))))))
168 (defconst org-odt-styles-dir-list
170 (and org-odt-data-dir
171 (expand-file-name "./styles/" org-odt-data-dir)) ; bail out
173 (and (boundp 'org-odt-data-dir) org-odt-data-dir ; see make install
174 (expand-file-name "./styles/" org-odt-data-dir)))
175 (expand-file-name "../etc/styles/" org-odt-lib-dir) ; git
176 (expand-file-name "./etc/styles/" org-odt-lib-dir) ; elpa
177 (expand-file-name "./org/" data-directory) ; system
179 "List of directories to search for OpenDocument styles files.
180 See `org-odt-styles-dir'. The entries in this list are populated
181 heuristically based on the values of `org-odt-lib-dir' and
182 `org-odt-data-dir'.")
184 (defconst org-odt-styles-dir
187 (message "Debug (org-odt): Searching for OpenDocument styles files...")
188 (mapc (lambda (styles-dir)
190 (message "Debug (org-odt): Trying %s..." styles-dir)
191 (when (and (file-readable-p
193 "OrgOdtContentTemplate.xml" styles-dir))
196 "OrgOdtStyles.xml" styles-dir)))
197 (message "Debug (org-odt): Using styles under %s"
199 (throw 'styles-dir styles-dir))))
200 org-odt-styles-dir-list)
203 (error "Error (org-odt): Cannot find factory styles files. Aborting."))
205 "Directory that holds auxiliary XML files used by the ODT exporter.
207 This directory contains the following XML files -
208 \"OrgOdtStyles.xml\" and \"OrgOdtContentTemplate.xml\". These
209 XML files are used as the default values of
210 `org-export-odt-styles-file' and
211 `org-export-odt-content-template-file'.
213 The default value of this variable varies depending on the
214 version of org in use and is initialized from
215 `org-odt-styles-dir-list'. Note that the user could be using org
216 from one of: org's own private git repository, GNU ELPA tar or
219 (defvar org-odt-file-extensions
220 '(("odt" . "OpenDocument Text")
221 ("ott" . "OpenDocument Text Template")
222 ("odm" . "OpenDocument Master Document")
223 ("ods" . "OpenDocument Spreadsheet")
224 ("ots" . "OpenDocument Spreadsheet Template")
225 ("odg" . "OpenDocument Drawing (Graphics)")
226 ("otg" . "OpenDocument Drawing Template")
227 ("odp" . "OpenDocument Presentation")
228 ("otp" . "OpenDocument Presentation Template")
229 ("odi" . "OpenDocument Image")
230 ("odf" . "OpenDocument Formula")
231 ("odc" . "OpenDocument Chart")))
235 ;; Let Org open all OpenDocument files using system-registered app
236 (add-to-list 'org-file-apps
237 (cons (concat "\\." (car desc) "\\'") 'system))
238 ;; Let Emacs open all OpenDocument files in archive mode
239 (add-to-list 'auto-mode-alist
240 (cons (concat "\\." (car desc) "\\'") 'archive-mode)))
241 org-odt-file-extensions)
243 ;; register the odt exporter with the pre-processor
244 (add-to-list 'org-export-backends 'odt)
246 ;; register the odt exporter with org-lparse library
247 (org-lparse-register-backend 'odt)
249 (defun org-odt-unload-function ()
250 (org-lparse-unregister-backend 'odt)
251 (remove-hook 'org-export-preprocess-after-blockquote-hook
252 'org-export-odt-preprocess-latex-fragments)
255 (defcustom org-export-odt-content-template-file nil
256 "Template file for \"content.xml\".
257 The exporter embeds the exported content just before
258 \"</office:text>\" element.
260 If unspecified, the file named \"OrgOdtContentTemplate.xml\"
261 under `org-odt-styles-dir' is used."
263 :group 'org-export-odt)
265 (defcustom org-export-odt-styles-file nil
266 "Default styles file for use with ODT export.
267 Valid values are one of:
269 2. path to a styles.xml file
270 3. path to a *.odt or a *.ott file
271 4. list of the form (ODT-OR-OTT-FILE (FILE-MEMBER-1 FILE-MEMBER-2
274 In case of option 1, an in-built styles.xml is used. See
275 `org-odt-styles-dir' for more information.
277 In case of option 3, the specified file is unzipped and the
278 styles.xml embedded therein is used.
280 In case of option 4, the specified ODT-OR-OTT-FILE is unzipped
281 and FILE-MEMBER-1, FILE-MEMBER-2 etc are copied in to the
282 generated odt file. Use relative path for specifying the
283 FILE-MEMBERS. styles.xml must be specified as one of the
286 Use options 1, 2 or 3 only if styles.xml alone suffices for
287 achieving the desired formatting. Use option 4, if the styles.xml
288 references additional files like header and footer images for
289 achieving the desired formattting.
291 Use \"#+ODT_STYLES_FILE: ...\" directive to set this variable on
292 a per-file basis. For example,
294 #+ODT_STYLES_FILE: \"/path/to/styles.xml\" or
295 #+ODT_STYLES_FILE: (\"/path/to/file.ott\" (\"styles.xml\" \"image/hdr.png\"))."
296 :group 'org-export-odt
299 (const :tag "Factory settings" nil)
300 (file :must-match t :tag "styles.xml")
301 (file :must-match t :tag "ODT or OTT file")
302 (list :tag "ODT or OTT file + Members"
303 (file :must-match t :tag "ODF Text or Text Template file")
305 (file :tag " Member" "styles.xml")
306 (repeat (file :tag "Member"))))))
308 (eval-after-load 'org-exp
309 '(add-to-list 'org-export-inbuffer-options-extra
310 '("ODT_STYLES_FILE" :odt-styles-file)))
312 (defconst org-export-odt-tmpdir-prefix "%s-")
313 (defconst org-export-odt-bookmark-prefix "OrgXref.")
315 (defvar org-export-odt-embed-images t
316 "Should the images be copied in to the odt file or just linked?")
318 (defvar org-export-odt-inline-images 'maybe) ; counterpart of
319 ; `org-export-html-inline-images'
321 (defcustom org-export-odt-inline-image-extensions
322 '("png" "jpeg" "jpg" "gif")
323 "Extensions of image files that can be inlined into HTML."
324 :type '(repeat (string :tag "Extension"))
325 :group 'org-export-odt)
327 (defcustom org-export-odt-pixels-per-inch display-pixels-per-inch
328 ;; FIXME add docstring
331 :group 'org-export-odt)
333 (defcustom org-export-odt-create-custom-styles-for-srcblocks t
334 "Whether custom styles for colorized source blocks be automatically created.
335 When this option is turned on, the exporter creates custom styles
336 for source blocks based on the advice of `htmlfontify'. Creation
337 of custom styles happen as part of `org-odt-hfy-face-to-css'.
339 When this option is turned off exporter does not create such
342 Use the latter option if you do not want the custom styles to be
343 based on your current display settings. It is necessary that the
344 styles.xml already contains needed styles for colorizing to work.
346 This variable is effective only if
347 `org-export-odt-fontify-srcblocks' is turned on."
348 :group 'org-export-odt
351 (defvar org-export-odt-default-org-styles-alist
352 '((paragraph . ((default . "Text_20_body")
353 (fixedwidth . "OrgFixedWidthBlock")
355 (quote . "Quotations")
356 (blockquote . "Quotations")
357 (center . "OrgCenter")
361 (subtitle . "OrgSubtitle")
362 (footnote . "Footnote")
363 (src . "OrgSrcBlock")
364 (illustration . "Illustration")
366 (definition-term . "Text_20_body_20_bold")
367 (horizontal-line . "Horizontal_20_Line")))
368 (character . ((bold . "Bold")
369 (emphasis . "Emphasis")
371 (verbatim . "OrgCode")
372 (strike . "Strikethrough")
373 (underline . "Underline")
374 (subscript . "OrgSubscript")
375 (superscript . "OrgSuperscript")))
376 (list . ((ordered . "OrgNumberedList")
377 (unordered . "OrgBulletedList")
378 (description . "OrgDescriptionList"))))
379 "Default styles for various entities.")
381 (defvar org-export-odt-org-styles-alist org-export-odt-default-org-styles-alist)
382 (defun org-odt-get-style-name-for-entity (category &optional entity)
383 (let ((entity (or entity 'default)))
385 (cdr (assoc entity (cdr (assoc category
386 org-export-odt-org-styles-alist))))
387 (cdr (assoc entity (cdr (assoc category
388 org-export-odt-default-org-styles-alist))))
389 (error "Cannot determine style name for entity %s of type %s"
392 (defcustom org-export-odt-preferred-output-format nil
393 "Automatically post-process to this format after exporting to \"odt\".
394 Interactive commands `org-export-as-odt' and
395 `org-export-as-odt-and-open' export first to \"odt\" format and
396 then use `org-export-odt-convert-process' to convert the
397 resulting document to this format. During customization of this
398 variable, the list of valid values are populated based on
399 `org-export-odt-convert-capabilities'."
400 :group 'org-export-odt
401 :type '(choice :convert-widget
403 (apply 'widget-convert (widget-type w)
404 (eval (car (widget-get w :args)))))
405 `((const :tag "None" nil)
406 ,@(mapcar (lambda (c)
408 (org-lparse-reachable-formats "odt")))))
411 (defun org-export-as-odt-and-open (arg)
412 "Export the outline as ODT and immediately open it with a browser.
413 If there is an active region, export only the region.
414 The prefix ARG specifies how many levels of the outline should become
415 headlines. The default is 3. Lower levels will become bulleted lists."
418 (or org-export-odt-preferred-output-format "odt") "odt" arg))
421 (defun org-export-as-odt-batch ()
422 "Call the function `org-lparse-batch'.
423 This function can be used in batch processing as:
425 --load=$HOME/lib/emacs/org.el
426 --eval \"(setq org-export-headline-levels 2)\"
427 --visit=MyFile --funcall org-export-as-odt-batch"
428 (org-lparse-batch "odt"))
431 (defun org-export-as-odt-to-buffer (arg)
432 "Call `org-lparse-odt` with output to a temporary buffer.
433 No file is created. The prefix ARG is passed through to `org-lparse-to-buffer'."
435 (org-lparse-to-buffer "odt" arg))
438 (defun org-replace-region-by-odt (beg end)
439 "Assume the current region has org-mode syntax, and convert it to ODT.
440 This can be used in any buffer. For example, you could write an
441 itemized list in org-mode syntax in an ODT buffer and then use this
442 command to convert it."
444 (org-replace-region-by "odt" beg end))
447 (defun org-export-region-as-odt (beg end &optional body-only buffer)
448 "Convert region from BEG to END in org-mode buffer to ODT.
449 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
450 contents, and only produce the region of converted text, useful for
451 cut-and-paste operations.
452 If BUFFER is a buffer or a string, use/create that buffer as a target
453 of the converted ODT. If BUFFER is the symbol `string', return the
454 produced ODT as a string and leave not buffer behind. For example,
455 a Lisp program could call this function in the following way:
457 (setq odt (org-export-region-as-odt beg end t 'string))
459 When called interactively, the output buffer is selected, and shown
460 in a window. A non-interactive call will only return the buffer."
462 (org-lparse-region "odt" beg end body-only buffer))
464 ;;; org-export-as-odt
466 (defun org-export-as-odt (arg &optional hidden ext-plist
467 to-buffer body-only pub-dir)
468 "Export the outline as a OpenDocumentText file.
469 If there is an active region, export only the region. The prefix
470 ARG specifies how many levels of the outline should become
471 headlines. The default is 3. Lower levels will become bulleted
472 lists. HIDDEN is obsolete and does nothing.
473 EXT-PLIST is a property list with external parameters overriding
474 org-mode's default settings, but still inferior to file-local
475 settings. When TO-BUFFER is non-nil, create a buffer with that
476 name and export to that buffer. If TO-BUFFER is the symbol
477 `string', don't leave any buffer behind but just return the
478 resulting XML as a string. When BODY-ONLY is set, don't produce
479 the file header and footer, simply return the content of
480 <body>...</body>, without even the body tags themselves. When
481 PUB-DIR is set, use this as the publishing directory."
483 (org-lparse (or org-export-odt-preferred-output-format "odt")
484 "odt" arg hidden ext-plist to-buffer body-only pub-dir))
486 (defvar org-odt-entity-control-callbacks-alist
488 . (org-odt-begin-export org-odt-end-export))
490 . (org-odt-begin-document-content org-odt-end-document-content))
492 . (org-odt-begin-document-body org-odt-end-document-body))
494 . (org-odt-begin-toc org-odt-end-toc))
496 . (org-odt-begin-environment org-odt-end-environment))
498 . (org-odt-begin-footnote-definition org-odt-end-footnote-definition))
500 . (org-odt-begin-table org-odt-end-table))
502 . (org-odt-begin-table-rowgroup org-odt-end-table-rowgroup))
504 . (org-odt-begin-list org-odt-end-list))
506 . (org-odt-begin-list-item org-odt-end-list-item))
508 . (org-odt-begin-outline org-odt-end-outline))
510 . (org-odt-begin-outline-text org-odt-end-outline-text))
512 . (org-odt-begin-paragraph org-odt-end-paragraph)))
515 (defvar org-odt-entity-format-callbacks-alist
516 `((EXTRA-TARGETS . org-lparse-format-extra-targets)
517 (ORG-TAGS . org-lparse-format-org-tags)
518 (SECTION-NUMBER . org-lparse-format-section-number)
519 (HEADLINE . org-odt-format-headline)
520 (TOC-ENTRY . org-odt-format-toc-entry)
521 (TOC-ITEM . org-odt-format-toc-item)
522 (TAGS . org-odt-format-tags)
523 (SPACES . org-odt-format-spaces)
524 (TABS . org-odt-format-tabs)
525 (LINE-BREAK . org-odt-format-line-break)
526 (FONTIFY . org-odt-format-fontify)
527 (TODO . org-lparse-format-todo)
528 (LINK . org-odt-format-link)
529 (INLINE-IMAGE . org-odt-format-inline-image)
530 (ORG-LINK . org-odt-format-org-link)
531 (HEADING . org-odt-format-heading)
532 (ANCHOR . org-odt-format-anchor)
533 (TABLE . org-lparse-format-table)
534 (TABLE-ROW . org-odt-format-table-row)
535 (TABLE-CELL . org-odt-format-table-cell)
536 (FOOTNOTES-SECTION . ignore)
537 (FOOTNOTE-REFERENCE . org-odt-format-footnote-reference)
538 (HORIZONTAL-LINE . org-odt-format-horizontal-line)
539 (COMMENT . org-odt-format-comment)
540 (LINE . org-odt-format-line)
541 (ORG-ENTITY . org-odt-format-org-entity))
545 ;;;_. control callbacks
547 (defun org-odt-begin-office-body ()
549 (insert-file-contents
550 (or org-export-odt-content-template-file
551 (expand-file-name "OrgOdtContentTemplate.xml"
552 org-odt-styles-dir)))
553 (goto-char (point-min))
554 (re-search-forward "</office:text>" nil nil)
555 (delete-region (match-beginning 0) (point-max)))
557 ;; Following variable is let bound when `org-do-lparse' is in
558 ;; progress. See org-html.el.
559 (defvar org-lparse-toc)
560 (defun org-odt-format-toc ()
561 (if (not org-lparse-toc) "" (concat "\n" org-lparse-toc "\n")))
563 (defun org-odt-format-preamble (opt-plist)
564 (let* ((title (plist-get opt-plist :title))
565 (author (plist-get opt-plist :author))
566 (date (plist-get opt-plist :date))
567 (iso-date (org-odt-format-date date))
568 (date (org-odt-format-date date "%d %b %Y"))
569 (email (plist-get opt-plist :email))
570 ;; switch on or off above vars based on user settings
571 (author (and (plist-get opt-plist :author-info) (or author email)))
572 (email (and (plist-get opt-plist :email-info) email))
573 (date (and (plist-get opt-plist :time-stamp-file) date)))
578 (org-odt-format-stylized-paragraph
579 'title (org-odt-format-tags
580 '("<text:title>" . "</text:title>") title))
582 "<text:p text:style-name=\"OrgTitle\"/>"))
584 ((and author (not email))
587 (org-odt-format-stylized-paragraph
590 '("<text:initial-creator>" . "</text:initial-creator>")
593 "<text:p text:style-name=\"OrgSubtitle\"/>"))
597 (org-odt-format-stylized-paragraph
601 '("<text:initial-creator>" . "</text:initial-creator>")
602 author) (concat "mailto:" email)))
604 "<text:p text:style-name=\"OrgSubtitle\"/>")))
608 (org-odt-format-stylized-paragraph
611 '("<text:date style:data-style-name=\"%s\" text:date-value=\"%s\">"
612 . "</text:date>") date "N75" iso-date))
614 "<text:p text:style-name=\"OrgSubtitle\"/>"))
616 (org-odt-format-toc))))
618 (defun org-odt-begin-document-body (opt-plist)
619 (org-odt-begin-office-body)
620 (insert (org-odt-format-preamble opt-plist)))
622 (defvar org-lparse-body-only) ; let bound during org-do-lparse
623 (defvar org-lparse-to-buffer) ; let bound during org-do-lparse
624 (defun org-odt-end-document-body (opt-plist)
625 (unless org-lparse-body-only
626 (org-lparse-insert-tag "</office:text>")
627 (org-lparse-insert-tag "</office:body>")))
629 (defun org-odt-begin-document-content (opt-plist)
632 (defun org-odt-end-document-content ()
633 (org-lparse-insert-tag "</office:document-content>"))
635 (defun org-odt-begin-outline (level1 snumber title tags
636 target extra-targets class)
638 'HEADING (org-lparse-format
639 'HEADLINE title extra-targets tags snumber level1)
642 (defun org-odt-end-outline ()
645 (defun org-odt-begin-outline-text (level1 snumber class)
648 (defun org-odt-end-outline-text ()
651 (defvar org-odt-section-count 0)
652 (defun org-odt-begin-section (style &optional name)
653 (setq name (or name (format "Section-%d" (incf org-odt-section-count))))
654 (org-lparse-insert-tag
655 "<text:section text:style-name=\"%s\" text:name=\"%s\">" style name))
657 (defun org-odt-end-section ()
658 (org-lparse-insert-tag "</text:section>"))
660 (defun org-odt-begin-paragraph (&optional style)
661 (org-lparse-insert-tag
662 "<text:p%s>" (org-odt-get-extra-attrs-for-paragraph-style style)))
664 (defun org-odt-end-paragraph ()
665 (org-lparse-insert-tag "</text:p>"))
667 (defun org-odt-get-extra-attrs-for-paragraph-style (style)
671 ((stringp style) style)
672 ((symbolp style) (org-odt-get-style-name-for-entity
675 (error "Don't know how to handle paragraph style %s" style))
676 (format " text:style-name=\"%s\"" style-name)))
678 (defun org-odt-format-stylized-paragraph (style text)
680 '("<text:p%s>" . "</text:p>") text
681 (org-odt-get-extra-attrs-for-paragraph-style style)))
683 (defvar org-lparse-opt-plist) ; bound during org-do-lparse
684 (defun org-odt-format-author (&optional author)
685 (when (setq author (or author (plist-get org-lparse-opt-plist :author)))
686 (org-odt-format-tags '("<dc:creator>" . "</dc:creator>") author)))
688 (defun org-odt-format-date (&optional org-ts fmt)
691 (and (stringp org-ts)
692 (string-match org-ts-regexp0 org-ts)
694 (org-fix-decoded-time
695 (org-parse-time-string (match-string 0 org-ts) t)))))
698 (fmt (format-time-string fmt time))
699 (t (setq date (format-time-string "%Y-%m-%dT%H:%M:%S%z" time))
700 (format "%s:%s" (substring date 0 -2) (substring date -2)))))))
702 (defun org-odt-begin-annotation (&optional author date)
703 (org-lparse-insert-tag "<office:annotation>")
704 (when (setq author (org-odt-format-author author))
706 (insert (org-odt-format-tags
707 '("<dc:date>" . "</dc:date>")
709 (or date (plist-get org-lparse-opt-plist :date)))))
710 (org-lparse-begin-paragraph))
712 (defun org-odt-end-annotation ()
713 (org-lparse-insert-tag "</office:annotation>"))
715 (defun org-odt-begin-environment (style env-options-plist)
718 (org-lparse-stash-save-paragraph-state)
719 (org-odt-begin-annotation (plist-get env-options-plist 'author)
720 (plist-get env-options-plist 'date)))
721 ((blockquote verse center quote)
722 (org-lparse-begin-paragraph style)
725 (org-lparse-end-paragraph)
727 (t (error "Unknown environment %s" style))))
729 (defun org-odt-end-environment (style env-options-plist)
732 (org-lparse-end-paragraph)
733 (org-odt-end-annotation)
734 (org-lparse-stash-pop-paragraph-state))
735 ((blockquote verse center quote)
736 (org-lparse-end-paragraph)
739 (org-lparse-begin-paragraph)
741 (t (error "Unknown environment %s" style))))
743 (defvar org-lparse-list-stack) ; dynamically bound in org-do-lparse
744 (defvar org-odt-list-stack-stashed)
745 (defun org-odt-begin-list (ltype)
746 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
748 (let* ((style-name (org-odt-get-style-name-for-entity 'list ltype))
749 (extra (concat (if (or org-lparse-list-table-p
750 (and (= 1 (length org-lparse-list-stack))
751 (null org-odt-list-stack-stashed)))
752 " text:continue-numbering=\"false\""
753 " text:continue-numbering=\"true\"")
755 (format " text:style-name=\"%s\"" style-name)))))
757 ((ordered unordered description)
758 (org-lparse-end-paragraph)
759 (org-lparse-insert-tag "<text:list%s>" extra))
760 (t (error "Unknown list type: %s" ltype)))))
762 (defun org-odt-end-list (ltype)
763 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
766 (org-lparse-insert-tag "</text:list>")
767 (error "Unknown list type: %s" ltype)))
769 (defun org-odt-begin-list-item (ltype &optional arg headline)
770 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
774 (assert (not headline) t)
775 (let* ((counter arg) (extra ""))
776 (org-lparse-insert-tag (if (= (length org-lparse-list-stack)
777 (length org-odt-list-stack-stashed))
778 "<text:list-header>" "<text:list-item>"))
779 (org-lparse-begin-paragraph)))
781 (let* ((id arg) (extra ""))
782 (org-lparse-insert-tag (if (= (length org-lparse-list-stack)
783 (length org-odt-list-stack-stashed))
784 "<text:list-header>" "<text:list-item>"))
785 (org-lparse-begin-paragraph)
786 (insert (if headline (org-odt-format-target headline id)
787 (org-odt-format-bookmark "" id)))))
789 (assert (not headline) t)
790 (let ((term (or arg "(no term)")))
793 '("<text:list-item>" . "</text:list-item>")
794 (org-odt-format-stylized-paragraph 'definition-term term)))
795 (org-lparse-begin-list-item 'unordered)
796 (org-lparse-begin-list 'description)
797 (org-lparse-begin-list-item 'unordered)))
798 (t (error "Unknown list type"))))
800 (defun org-odt-end-list-item (ltype)
801 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
805 (org-lparse-insert-tag (if (= (length org-lparse-list-stack)
806 (length org-odt-list-stack-stashed))
807 (prog1 "</text:list-header>"
808 (setq org-odt-list-stack-stashed nil))
809 "</text:list-item>")))
811 (org-lparse-end-list-item-1)
812 (org-lparse-end-list 'description)
813 (org-lparse-end-list-item-1))
814 (t (error "Unknown list type"))))
816 (defun org-odt-discontinue-list ()
817 (let ((stashed-stack org-lparse-list-stack))
818 (loop for list-type in stashed-stack
819 do (org-lparse-end-list-item-1 list-type)
820 (org-lparse-end-list list-type))
821 (setq org-odt-list-stack-stashed stashed-stack)))
823 (defun org-odt-continue-list ()
824 (setq org-odt-list-stack-stashed (nreverse org-odt-list-stack-stashed))
825 (loop for list-type in org-odt-list-stack-stashed
826 do (org-lparse-begin-list list-type)
827 (org-lparse-begin-list-item list-type)))
829 ;; Following variables are let bound when table emission is in
830 ;; progress. See org-lparse.el.
831 (defvar org-lparse-table-begin-marker)
832 (defvar org-lparse-table-ncols)
833 (defvar org-lparse-table-rowgrp-open)
834 (defvar org-lparse-table-rownum)
835 (defvar org-lparse-table-cur-rowgrp-is-hdr)
836 (defvar org-lparse-table-is-styled)
837 (defvar org-lparse-table-rowgrp-info)
838 (defvar org-lparse-table-colalign-vector)
840 (defvar org-odt-table-style nil
841 "Table style specified by \"#+ATTR_ODT: <style-name>\" line.
842 This is set during `org-odt-begin-table'.")
844 (defvar org-odt-table-style-spec nil
845 "Entry for `org-odt-table-style' in `org-export-odt-table-styles'.")
847 (defcustom org-export-odt-table-styles
848 '(("OrgEquation" "OrgEquation"
849 ((use-first-column-styles . t)
850 (use-last-column-styles . t))))
851 "Specify how Table Styles should be derived from a Table Template.
852 This is a list where each element is of the
853 form (TABLE-STYLE-NAME TABLE-TEMPLATE-NAME TABLE-CELL-OPTIONS).
855 TABLE-STYLE-NAME is the style associated with the table through
856 `org-odt-table-style'.
858 TABLE-TEMPLATE-NAME is a set of - upto 9 - automatic
859 TABLE-CELL-STYLE-NAMEs and PARAGRAPH-STYLE-NAMEs (as defined
860 below) that is included in
861 `org-export-odt-content-template-file'.
863 TABLE-CELL-STYLE-NAME := TABLE-TEMPLATE-NAME + TABLE-CELL-TYPE +
865 PARAGRAPH-STYLE-NAME := TABLE-TEMPLATE-NAME + TABLE-CELL-TYPE +
867 TABLE-CELL-TYPE := \"FirstRow\" | \"LastColumn\" |
868 \"FirstRow\" | \"LastRow\" |
869 \"EvenRow\" | \"OddRow\" |
870 \"EvenColumn\" | \"OddColumn\" | \"\"
871 where \"+\" above denotes string concatenation.
873 TABLE-CELL-OPTIONS is an alist where each element is of the
874 form (TABLE-CELL-STYLE-SELECTOR . ON-OR-OFF).
875 TABLE-CELL-STYLE-SELECTOR := `use-first-row-styles' |
876 `use-last-row-styles' |
877 `use-first-column-styles' |
878 `use-last-column-styles' |
879 `use-banding-rows-styles' |
880 `use-banding-columns-styles' |
881 `use-first-row-styles'
882 ON-OR-OFF := `t' | `nil'
884 For example, with the following configuration
886 \(setq org-export-odt-table-styles
887 '\(\(\"TableWithHeaderRowsAndColumns\" \"Custom\"
888 \(\(use-first-row-styles . t\)
889 \(use-first-column-styles . t\)\)\)
890 \(\"TableWithHeaderColumns\" \"Custom\"
891 \(\(use-first-column-styles . t\)\)\)\)\)
893 1. A table associated with \"TableWithHeaderRowsAndColumns\"
894 style will use the following table-cell styles -
895 \"CustomFirstRowTableCell\", \"CustomFirstColumnTableCell\",
896 \"CustomTableCell\" and the following paragraph styles
897 \"CustomFirstRowTableParagraph\",
898 \"CustomFirstColumnTableParagraph\", \"CustomTableParagraph\"
901 2. A table associated with \"TableWithHeaderColumns\" style will
902 use the following table-cell styles -
903 \"CustomFirstColumnTableCell\", \"CustomTableCell\" and the
904 following paragraph styles
905 \"CustomFirstColumnTableParagraph\", \"CustomTableParagraph\"
908 Note that TABLE-TEMPLATE-NAME corresponds to the
909 \"<table:table-template>\" elements contained within
910 \"<office:styles>\". The entries (TABLE-STYLE-NAME
911 TABLE-TEMPLATE-NAME TABLE-CELL-OPTIONS) correspond to
912 \"table:template-name\" and \"table:use-first-row-styles\" etc
913 attributes of \"<table:table>\" element. Refer ODF-1.2
914 specification for more information. Also consult the
915 implementation filed under `org-odt-get-table-cell-styles'.
917 The TABLE-STYLE-NAME \"OrgEquation\" is used internally for
918 formatting of numbered display equations. Do not delete this
919 style from the list."
920 :group 'org-export-odt
922 (const :tag "None" nil)
923 (repeat :tag "Table Styles"
924 (list :tag "Table Style Specification"
925 (string :tag "Table Style Name")
926 (string :tag "Table Template Name")
927 (alist :options (use-first-row-styles
929 use-first-column-styles
930 use-last-column-styles
931 use-banding-rows-styles
932 use-banding-columns-styles)
934 :value-type (const :tag "True" t))))))
936 (defvar org-odt-table-indentedp nil)
937 (defun org-odt-begin-table (caption label attributes)
938 (setq org-odt-table-indentedp (not (null org-lparse-list-stack)))
939 (when org-odt-table-indentedp
940 ;; Within the Org file, the table is appearing within a list item.
941 ;; OpenDocument doesn't allow table to appear within list items.
942 ;; Temporarily terminate the list, emit the table and then
943 ;; re-continue the list.
944 (org-odt-discontinue-list)
945 ;; Put the Table in an indented section.
946 (let ((level (length org-odt-list-stack-stashed)))
947 (org-odt-begin-section (format "OrgIndentedSection-Level-%d" level))))
949 (setq org-odt-table-style attributes)
950 (setq org-odt-table-style-spec
951 (assoc org-odt-table-style org-export-odt-table-styles))
954 (org-odt-format-stylized-paragraph
955 'table (org-odt-format-entity-caption label caption "__Table__"))))
956 (org-lparse-insert-tag
957 "<table:table table:name=\"%s\" table:style-name=\"%s\">"
958 (or label "") (or (nth 1 org-odt-table-style-spec) "OrgTable"))
959 (setq org-lparse-table-begin-marker (point)))
961 (defvar org-lparse-table-colalign-info)
962 (defun org-odt-end-table ()
963 (goto-char org-lparse-table-begin-marker)
964 (loop for level from 0 below org-lparse-table-ncols
965 do (let* ((col-cookie (and org-lparse-table-is-styled
966 (cdr (assoc (1+ level)
967 org-lparse-table-colalign-info))))
968 (extra-columns (or (nth 1 col-cookie) 0)))
969 (dotimes (i (1+ extra-columns))
972 "<table:table-column table:style-name=\"%sColumn\"/>"
973 "" (or (nth 1 org-odt-table-style-spec) "OrgTable"))))
975 ;; fill style attributes for table cells
976 (when org-lparse-table-is-styled
977 (while (re-search-forward "@@\\(table-cell:p\\|table-cell:style-name\\)@@\\([0-9]+\\)@@\\([0-9]+\\)@@" nil t)
978 (let* ((spec (match-string 1))
979 (r (string-to-number (match-string 2)))
980 (c (string-to-number (match-string 3)))
981 (cell-styles (org-odt-get-table-cell-styles
982 r c org-odt-table-style-spec))
983 (table-cell-style (car cell-styles))
984 (table-cell-paragraph-style (cdr cell-styles)))
986 ((equal spec "table-cell:p")
987 (replace-match table-cell-paragraph-style t t))
988 ((equal spec "table-cell:style-name")
989 (replace-match table-cell-style t t))))))
990 (goto-char (point-max))
991 (org-lparse-insert-tag "</table:table>")
992 (when org-odt-table-indentedp
993 (org-odt-end-section)
994 (org-odt-continue-list)))
996 (defun org-odt-begin-table-rowgroup (&optional is-header-row)
997 (when org-lparse-table-rowgrp-open
998 (org-lparse-end 'TABLE-ROWGROUP))
999 (org-lparse-insert-tag (if is-header-row
1000 "<table:table-header-rows>"
1001 "<table:table-rows>"))
1002 (setq org-lparse-table-rowgrp-open t)
1003 (setq org-lparse-table-cur-rowgrp-is-hdr is-header-row))
1005 (defun org-odt-end-table-rowgroup ()
1006 (when org-lparse-table-rowgrp-open
1007 (setq org-lparse-table-rowgrp-open nil)
1008 (org-lparse-insert-tag
1009 (if org-lparse-table-cur-rowgrp-is-hdr
1010 "</table:table-header-rows>" "</table:table-rows>"))))
1012 (defun org-odt-format-table-row (row)
1013 (org-odt-format-tags
1014 '("<table:table-row>" . "</table:table-row>") row))
1016 (defun org-odt-get-table-cell-styles (r c &optional style-spec)
1017 "Retrieve styles applicable to a table cell.
1018 R and C are (zero-based) row and column numbers of the table
1019 cell. STYLE-SPEC is an entry in `org-export-odt-table-styles'
1020 applicable to the current table. It is `nil' if the table is not
1021 associated with any style attributes.
1023 Return a cons of (TABLE-CELL-STYLE-NAME . PARAGRAPH-STYLE-NAME).
1025 When STYLE-SPEC is nil, style the table cell the conventional way
1026 - choose cell borders based on row and column groupings and
1027 choose paragraph alignment based on `org-col-cookies' text
1029 `org-odt-get-paragraph-style-cookie-for-table-cell'.
1031 When STYLE-SPEC is non-nil, ignore the above cookie and return
1032 styles congruent with the ODF-1.2 specification."
1036 ;; LibreOffice - particularly the Writer - honors neither table
1037 ;; templates nor custom table-cell styles. Inorder to retain
1038 ;; inter-operability with LibreOffice, only automatic styles are
1039 ;; used for styling of table-cells. The current implementation is
1040 ;; congruent with ODF-1.2 specification and hence is
1041 ;; future-compatible.
1043 ;; Additional Note: LibreOffice's AutoFormat facility for tables -
1044 ;; which recognizes as many as 16 different cell types - is much
1045 ;; richer. Unfortunately it is NOT amenable to easy configuration
1048 (let* ((template-name (nth 1 style-spec))
1049 (cell-style-selectors (nth 2 style-spec))
1052 ((and (cdr (assoc 'use-first-column-styles cell-style-selectors))
1053 (= c 0)) "FirstColumn")
1054 ((and (cdr (assoc 'use-last-column-styles cell-style-selectors))
1055 (= c (1- org-lparse-table-ncols))) "LastColumn")
1056 ((and (cdr (assoc 'use-first-row-styles cell-style-selectors))
1057 (= r 0)) "FirstRow")
1058 ((and (cdr (assoc 'use-last-row-styles cell-style-selectors))
1059 (= r org-lparse-table-rownum))
1061 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
1062 (= (% r 2) 1)) "EvenRow")
1063 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
1064 (= (% r 2) 0)) "OddRow")
1065 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
1066 (= (% c 2) 1)) "EvenColumn")
1067 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
1068 (= (% c 2) 0)) "OddColumn")
1071 (concat template-name cell-type "TableCell")
1072 (concat template-name cell-type "TableParagraph"))))
1079 ((eq (cdr (assoc r org-lparse-table-rowgrp-info)) :start) "T")
1081 (when (= r org-lparse-table-rownum) "B")
1084 ((or (memq (nth c org-table-colgroup-info) '(:start :startend))
1085 (memq (nth (1- c) org-table-colgroup-info) '(:end :startend))) "L")
1087 (capitalize (aref org-lparse-table-colalign-vector c))))))
1089 (defun org-odt-get-paragraph-style-cookie-for-table-cell (r c)
1091 (and (not org-odt-table-style-spec)
1093 (org-lparse-table-cur-rowgrp-is-hdr "OrgTableHeading")
1094 ((and (= c 0) (org-lparse-get 'TABLE-FIRST-COLUMN-AS-LABELS))
1096 (t "OrgTableContents")))
1097 (and org-lparse-table-is-styled
1098 (format "@@table-cell:p@@%03d@@%03d@@" r c))))
1100 (defun org-odt-get-style-name-cookie-for-table-cell (r c)
1101 (when org-lparse-table-is-styled
1102 (format "@@table-cell:style-name@@%03d@@%03d@@" r c)))
1104 (defun org-odt-format-table-cell (data r c horiz-span)
1106 (let* ((paragraph-style-cookie
1107 (org-odt-get-paragraph-style-cookie-for-table-cell r c))
1109 (org-odt-get-style-name-cookie-for-table-cell r c))
1110 (extra (and style-name-cookie
1111 (format " table:style-name=\"%s\"" style-name-cookie)))
1112 (extra (concat extra
1113 (and (> horiz-span 0)
1114 (format " table:number-columns-spanned=\"%d\""
1115 (1+ horiz-span))))))
1116 (org-odt-format-tags
1117 '("<table:table-cell%s>" . "</table:table-cell>")
1118 (if org-lparse-list-table-p data
1119 (org-odt-format-stylized-paragraph paragraph-style-cookie data)) extra))
1121 (dotimes (i horiz-span)
1122 (setq s (concat s "\n<table:covered-table-cell/>"))) s)
1125 (defun org-odt-begin-footnote-definition (n)
1126 (org-lparse-begin-paragraph 'footnote))
1128 (defun org-odt-end-footnote-definition (n)
1129 (org-lparse-end-paragraph))
1131 (defun org-odt-begin-toc (lang-specific-heading max-level)
1134 <text:table-of-content text:style-name=\"Sect2\" text:protected=\"true\" text:name=\"Table of Contents1\">
1135 <text:table-of-content-source text:outline-level=\"%d\">
1136 <text:index-title-template text:style-name=\"Contents_20_Heading\">%s</text:index-title-template>
1137 " max-level lang-specific-heading))
1138 (loop for level from 1 upto 10
1141 <text:table-of-content-entry-template text:outline-level=\"%d\" text:style-name=\"Contents_20_%d\">
1142 <text:index-entry-link-start text:style-name=\"Internet_20_link\"/>
1143 <text:index-entry-chapter/>
1144 <text:index-entry-text/>
1145 <text:index-entry-link-end/>
1146 </text:table-of-content-entry-template>
1151 </text:table-of-content-source>
1154 <text:index-title text:style-name=\"Sect1\" text:name=\"Table of Contents1_Head\">
1155 <text:p text:style-name=\"Contents_20_Heading\">%s</text:p>
1157 " lang-specific-heading)))
1159 (defun org-odt-end-toc ()
1162 </text:table-of-content>
1165 (defun org-odt-format-toc-entry (snumber todo headline tags href)
1166 (setq headline (concat
1167 (and org-export-with-section-numbers
1168 (concat snumber ". "))
1172 (org-lparse-format 'SPACES 3)
1173 (org-lparse-format 'FONTIFY tags "tag")))))
1175 (setq headline (org-lparse-format 'FONTIFY headline "todo")))
1177 (let ((org-odt-suppress-xref t))
1178 (org-odt-format-link headline (concat "#" href))))
1180 (defun org-odt-format-toc-item (toc-entry level org-last-level)
1181 (let ((style (format "Contents_20_%d"
1182 (+ level (or (org-lparse-get 'TOPLEVEL-HLEVEL) 1) -1))))
1183 (insert "\n" (org-odt-format-stylized-paragraph style toc-entry) "\n")))
1185 ;; Following variable is let bound during 'ORG-LINK callback. See
1187 (defvar org-lparse-link-description-is-image nil)
1188 (defun org-odt-format-link (desc href &optional attr)
1190 ((and (= (string-to-char href) ?#) (not org-odt-suppress-xref))
1191 (setq href (concat org-export-odt-bookmark-prefix (substring href 1)))
1192 (let ((xref-format "text"))
1193 (when (numberp desc)
1194 (setq desc (format "%d" desc) xref-format "number"))
1195 (org-odt-format-tags
1196 '("<text:bookmark-ref text:reference-format=\"%s\" text:ref-name=\"%s\">" .
1197 "</text:bookmark-ref>")
1198 desc xref-format href)))
1199 (org-lparse-link-description-is-image
1200 (org-odt-format-tags
1201 '("<draw:a xlink:type=\"simple\" xlink:href=\"%s\" %s>" . "</draw:a>")
1202 desc href (or attr "")))
1204 (org-odt-format-tags
1205 '("<text:a xlink:type=\"simple\" xlink:href=\"%s\" %s>" . "</text:a>")
1206 desc href (or attr "")))))
1208 (defun org-odt-format-spaces (n)
1212 " " (org-odt-format-tags "<text:s text:c=\"%d\"/>" "" (1- n))))
1215 (defun org-odt-format-tabs (&optional n)
1216 (let ((tab "<text:tab/>")
1220 (defun org-odt-format-line-break ()
1221 (org-odt-format-tags "<text:line-break/>" ""))
1223 (defun org-odt-format-horizontal-line ()
1224 (org-odt-format-stylized-paragraph 'horizontal-line ""))
1226 (defun org-odt-encode-plain-text (line &optional no-whitespace-filling)
1227 (setq line (org-xml-encode-plain-text line))
1228 (if no-whitespace-filling line
1229 (org-odt-fill-tabs-and-spaces line)))
1231 (defun org-odt-format-line (line)
1232 (case org-lparse-dyn-current-environment
1234 (org-odt-format-stylized-paragraph
1235 'fixedwidth (org-odt-encode-plain-text line)) "\n"))
1236 (t (concat line "\n"))))
1238 (defun org-odt-format-comment (fmt &rest args)
1239 (let ((comment (apply 'format fmt args)))
1240 (format "\n<!-- %s -->\n" comment)))
1242 (defun org-odt-format-org-entity (wd)
1243 (org-entity-get-representation wd 'utf8))
1245 (defun org-odt-fill-tabs-and-spaces (line)
1246 (replace-regexp-in-string
1247 "\\([\t]\\|\\([ ]+\\)\\)" (lambda (s)
1249 ((string= s "\t") (org-odt-format-tabs))
1250 (t (org-odt-format-spaces (length s))))) line))
1252 (defcustom org-export-odt-fontify-srcblocks t
1253 "Specify whether or not source blocks need to be fontified.
1254 Turn this option on if you want to colorize the source code
1255 blocks in the exported file. For colorization to work, you need
1256 to make available an enhanced version of `htmlfontify' library."
1258 :group 'org-export-odt)
1260 (defun org-odt-format-source-line-with-line-number-and-label
1261 (line rpllbl num fontifier par-style)
1263 (let ((keep-label (not (numberp rpllbl)))
1264 (ref (org-find-text-property-in-string 'org-coderef line)))
1265 (setq line (concat line (and keep-label ref (format "(%s)" ref))))
1266 (setq line (funcall fontifier line))
1268 (setq line (org-odt-format-target line (concat "coderef-" ref))))
1269 (setq line (org-odt-format-stylized-paragraph par-style line))
1271 (org-odt-format-tags '("<text:list-item>" . "</text:list-item>") line))))
1273 (defun org-odt-format-source-code-or-example-plain
1274 (lines lang caption textareap cols rows num cont rpllbl fmt)
1275 "Format source or example blocks much like fixedwidth blocks.
1276 Use this when `org-export-odt-fontify-srcblocks' option is turned
1278 (let* ((lines (org-split-string lines "[\r\n]"))
1279 (line-count (length lines))
1284 (org-odt-format-source-line-with-line-number-and-label
1285 line rpllbl num 'org-odt-encode-plain-text
1286 (if (= i line-count) "OrgFixedWidthBlockLastLine"
1287 "OrgFixedWidthBlock")))
1290 (defvar org-src-block-paragraph-format
1291 "<style:style style:name=\"OrgSrcBlock\" style:family=\"paragraph\" style:parent-style-name=\"Preformatted_20_Text\">
1292 <style:paragraph-properties fo:background-color=\"%s\" fo:padding=\"0.049cm\" fo:border=\"0.51pt solid #000000\" style:shadow=\"none\">
1293 <style:background-image/>
1294 </style:paragraph-properties>
1295 <style:text-properties fo:color=\"%s\"/>
1297 "Custom paragraph style for colorized source and example blocks.
1298 This style is much the same as that of \"OrgFixedWidthBlock\"
1299 except that the foreground and background colors are set
1300 according to the default face identified by the `htmlfontify'.")
1302 (defvar hfy-optimisations)
1303 (declare-function hfy-face-to-style "htmlfontify" (fn))
1304 (declare-function hfy-face-or-def-to-name "htmlfontify" (fn))
1306 (defun org-odt-hfy-face-to-css (fn)
1307 "Create custom style for face FN.
1308 When FN is the default face, use it's foreground and background
1309 properties to create \"OrgSrcBlock\" paragraph style. Otherwise
1310 use it's color attribute to create a character style whose name
1311 is obtained from FN. Currently all attributes of FN other than
1314 The style name for a face FN is derived using the following
1315 operations on the face name in that order - de-dash, CamelCase
1316 and prefix with \"OrgSrc\". For example,
1317 `font-lock-function-name-face' is associated with
1318 \"OrgSrcFontLockFunctionNameFace\"."
1319 (let* ((css-list (hfy-face-to-style fn))
1320 (style-name ((lambda (fn)
1323 'capitalize (split-string
1324 (hfy-face-or-def-to-name fn) "-")
1326 (color-val (cdr (assoc "color" css-list)))
1327 (background-color-val (cdr (assoc "background" css-list)))
1328 (style (and org-export-odt-create-custom-styles-for-srcblocks
1331 (format org-src-block-paragraph-format
1332 background-color-val color-val))
1336 <style:style style:name=\"%s\" style:family=\"text\">
1337 <style:text-properties fo:color=\"%s\"/>
1338 </style:style>" style-name color-val))))))
1339 (cons style-name style)))
1341 (defun org-odt-insert-custom-styles-for-srcblocks (styles)
1342 "Save STYLES used for colorizing of source blocks.
1343 Update styles.xml with styles that were collected as part of
1344 `org-odt-hfy-face-to-css' callbacks."
1346 (with-current-buffer
1347 (find-file-noselect (expand-file-name "styles.xml") t)
1348 (goto-char (point-min))
1349 (when (re-search-forward "</office:styles>" nil t)
1350 (goto-char (match-beginning 0))
1351 (insert "\n<!-- Org Htmlfontify Styles -->\n" styles "\n")))))
1353 (defun org-odt-format-source-code-or-example-colored
1354 (lines lang caption textareap cols rows num cont rpllbl fmt)
1355 "Format source or example blocks using `htmlfontify-string'.
1356 Use this routine when `org-export-odt-fontify-srcblocks' option
1358 (let* ((lang-m (and lang (or (cdr (assoc lang org-src-lang-modes)) lang)))
1359 (mode (and lang-m (intern (concat (if (symbolp lang-m)
1360 (symbol-name lang-m)
1362 (org-inhibit-startup t)
1363 (org-startup-folded nil)
1364 (lines (with-temp-buffer
1366 (if (functionp mode) (funcall mode) (fundamental-mode))
1367 (font-lock-fontify-buffer)
1369 (hfy-html-quote-regex "\\([<\"&> ]\\)")
1370 (hfy-html-quote-map '(("\"" """)
1375 (" " "<text:tab/>")))
1376 (hfy-face-to-css 'org-odt-hfy-face-to-css)
1377 (hfy-optimisations-1 (copy-seq hfy-optimisations))
1378 (hfy-optimisations (add-to-list 'hfy-optimisations-1
1380 (hfy-begin-span-handler
1381 (lambda (style text-block text-id text-begins-block-p)
1382 (insert (format "<text:span text:style-name=\"%s\">" style))))
1383 (hfy-end-span-handler (lambda nil (insert "</text:span>"))))
1384 (when (fboundp 'htmlfontify-string)
1385 (let* ((lines (org-split-string lines "[\r\n]"))
1386 (line-count (length lines))
1391 (org-odt-format-source-line-with-line-number-and-label
1392 line rpllbl num 'htmlfontify-string
1393 (if (= i line-count) "OrgSrcBlockLastLine" "OrgSrcBlock")))
1396 (defun org-odt-format-source-code-or-example (lines lang caption textareap
1399 "Format source or example blocks for export.
1400 Use `org-odt-format-source-code-or-example-plain' or
1401 `org-odt-format-source-code-or-example-colored' depending on the
1402 value of `org-export-odt-fontify-srcblocks."
1403 (setq lines (org-export-number-lines
1404 lines 0 0 num cont rpllbl fmt 'preprocess)
1406 (or (and org-export-odt-fontify-srcblocks
1407 (or (featurep 'htmlfontify)
1408 ;; htmlfontify.el was introduced in Emacs 23.2
1409 ;; So load it with some caution
1410 (require 'htmlfontify nil t))
1411 (fboundp 'htmlfontify-string)
1412 'org-odt-format-source-code-or-example-colored)
1413 'org-odt-format-source-code-or-example-plain)
1414 lines lang caption textareap cols rows num cont rpllbl fmt))
1416 (let ((extra (format " text:continue-numbering=\"%s\""
1417 (if cont "true" "false"))))
1418 (org-odt-format-tags
1419 '("<text:list text:style-name=\"OrgSrcBlockNumberedLine\"%s>"
1420 . "</text:list>") lines extra))))
1422 (defun org-odt-remap-stylenames (style-name)
1424 (cdr (assoc style-name '(("timestamp-wrapper" . "OrgTimestampWrapper")
1425 ("timestamp" . "OrgTimestamp")
1426 ("timestamp-kwd" . "OrgTimestampKeyword")
1428 ("todo" . "OrgTodo")
1429 ("done" . "OrgDone")
1430 ("target" . "OrgTarget"))))
1433 (defun org-odt-format-fontify (text style &optional id)
1437 (org-odt-remap-stylenames style))
1439 (org-odt-get-style-name-for-entity 'character style))
1441 (assert (< 1 (length style)))
1442 (let ((parent-style (pop style)))
1443 (mapconcat (lambda (s)
1444 ;; (assert (stringp s) t)
1445 (org-odt-remap-stylenames s)) style "")
1446 (org-odt-remap-stylenames parent-style)))
1447 (t (error "Don't how to handle style %s" style)))))
1448 (org-odt-format-tags
1449 '("<text:span text:style-name=\"%s\">" . "</text:span>")
1452 (defun org-odt-relocate-relative-path (path dir)
1453 (if (file-name-absolute-p path) path
1454 (file-relative-name (expand-file-name path dir)
1455 (expand-file-name "eyecandy" dir))))
1457 (defun org-odt-format-inline-image (thefile)
1458 (let* ((thelink (if (file-name-absolute-p thefile) thefile
1459 (org-xml-format-href
1460 (org-odt-relocate-relative-path
1461 thefile org-current-export-file))))
1463 (org-odt-format-tags
1464 "<draw:image xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>" ""
1465 (if org-export-odt-embed-images
1466 (org-odt-copy-image-file thefile) thelink))))
1467 (org-export-odt-format-image thefile href)))
1469 (defun org-export-odt-format-formula (src href &optional embed-as)
1470 "Create image tag with source and attributes."
1472 (let* ((caption (org-find-text-property-in-string 'org-caption src))
1473 (caption (and caption (org-xml-format-desc caption)))
1474 (label (org-find-text-property-in-string 'org-label src))
1475 (latex-frag (org-find-text-property-in-string 'org-latex-src src))
1476 (embed-as (or embed-as
1478 (org-find-text-property-in-string
1479 'org-latex-src-embed-type src))
1480 (if (or caption label) 'paragraph 'character)))
1483 (setq href (org-propertize href :title "LaTeX Fragment"
1484 :description latex-frag)))
1486 ((eq embed-as 'character)
1487 (org-odt-format-entity "InlineFormula" href width height))
1489 (org-lparse-end-paragraph)
1490 (org-lparse-insert-list-table
1491 `((,(org-odt-format-entity
1492 (if caption "CaptionedDisplayFormula" "DisplayFormula")
1493 href width height :caption caption :label nil)
1495 (org-odt-format-entity-caption label nil "__MathFormula__"))))
1496 nil nil nil "OrgEquation" nil '((1 "c" 8) (2 "c" 1)))
1497 (throw 'nextline nil))))))
1499 (defvar org-odt-embedded-formulas-count 0)
1500 (defun org-odt-copy-formula-file (path)
1501 "Returns the internal name of the file"
1502 (let* ((src-file (expand-file-name
1503 path (file-name-directory org-current-export-file)))
1504 (target-dir (format "Formula-%04d/"
1505 (incf org-odt-embedded-formulas-count)))
1506 (target-file (concat target-dir "content.xml")))
1507 (when (not org-lparse-to-buffer)
1508 (message "Embedding %s as %s ..."
1509 (substring-no-properties path) target-file)
1511 (make-directory target-dir)
1512 (org-odt-create-manifest-file-entry
1513 "application/vnd.oasis.opendocument.formula" target-dir "1.2")
1515 (case (org-odt-is-formula-link-p src-file)
1517 (copy-file src-file target-file 'overwrite))
1519 (org-odt-zip-extract-one src-file "content.xml" target-dir))
1521 (error "%s is not a formula file" src-file)))
1523 (org-odt-create-manifest-file-entry "text/xml" target-file))
1526 (defun org-odt-format-inline-formula (thefile)
1527 (let* ((thelink (if (file-name-absolute-p thefile) thefile
1528 (org-xml-format-href
1529 (org-odt-relocate-relative-path
1530 thefile org-current-export-file))))
1532 (org-odt-format-tags
1533 "<draw:object xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>" ""
1534 (file-name-directory (org-odt-copy-formula-file thefile)))))
1535 (org-export-odt-format-formula thefile href)))
1537 (defun org-odt-is-formula-link-p (file)
1538 (let ((case-fold-search nil))
1540 ((string-match "\\.\\(mathml\\|mml\\)\\'" file)
1542 ((string-match "\\.odf\\'" file)
1545 (defun org-odt-format-org-link (opt-plist type-1 path fragment desc attr
1547 "Make a OpenDocument link.
1548 OPT-PLIST is an options list.
1549 TYPE-1 is the device-type of the link (THIS://foo.html).
1550 PATH is the path of the link (http://THIS#location).
1551 FRAGMENT is the fragment part of the link, if any (foo.html#THIS).
1552 DESC is the link description, if any.
1553 ATTR is a string of other attributes of the a element."
1554 (declare (special org-lparse-par-open))
1556 (let* ((may-inline-p
1557 (and (member type-1 '("http" "https" "file"))
1558 (org-lparse-should-inline-p path descp)
1560 (type (if (equal type-1 "id") "file" type-1))
1564 ;; check for inlined images
1565 ((and (member type '("file"))
1568 filename org-export-odt-inline-image-extensions)
1569 (or (eq t org-export-odt-inline-images)
1570 (and org-export-odt-inline-images (not descp))))
1571 (org-odt-format-inline-image thefile))
1572 ;; check for embedded formulas
1573 ((and (member type '("file"))
1575 (org-odt-is-formula-link-p filename)
1577 (org-odt-format-inline-formula thefile))
1578 ((string= type "coderef")
1579 (let* ((ref fragment)
1580 (lineno-or-ref (cdr (assoc ref org-export-code-refs)))
1581 (desc (and descp desc))
1582 (org-odt-suppress-xref nil)
1583 (href (org-xml-format-href (concat "#coderef-" ref))))
1585 ((and (numberp lineno-or-ref) (not desc))
1586 (org-odt-format-link lineno-or-ref href))
1587 ((and (numberp lineno-or-ref) desc
1588 (string-match (regexp-quote (concat "(" ref ")")) desc))
1589 (format (replace-match "%s" t t desc)
1590 (org-odt-format-link lineno-or-ref href)))
1593 (if (and desc (string-match
1594 (regexp-quote (concat "(" ref ")"))
1596 (replace-match "%s" t t desc)
1599 (org-odt-format-link (org-xml-format-desc desc) href)))))
1601 (when (string= type "file")
1604 ((file-name-absolute-p path)
1605 (concat "file://" (expand-file-name path)))
1606 (t (org-odt-relocate-relative-path
1607 thefile org-current-export-file)))))
1609 (when (and (member type '("" "http" "https" "file")) fragment)
1610 (setq thefile (concat thefile "#" fragment)))
1612 (setq thefile (org-xml-format-href thefile))
1614 (when (not (member type '("" "file")))
1615 (setq thefile (concat type ":" thefile)))
1617 (let ((org-odt-suppress-xref nil))
1618 (org-odt-format-link
1619 (org-xml-format-desc desc) thefile attr)))))))
1621 (defun org-odt-format-heading (text level &optional id)
1622 (let* ((text (if id (org-odt-format-target text id) text)))
1623 (org-odt-format-tags
1624 '("<text:h text:style-name=\"Heading_20_%s\" text:outline-level=\"%s\">" .
1625 "</text:h>") text level level)))
1627 (defun org-odt-format-headline (title extra-targets tags
1628 &optional snumber level)
1630 (org-lparse-format 'EXTRA-TARGETS extra-targets)
1632 ;; No need to generate section numbers. They are auto-generated by
1635 ;; (concat (org-lparse-format 'SECTION-NUMBER snumber level) " ")
1637 (and tags (concat (org-lparse-format 'SPACES 3)
1638 (org-lparse-format 'ORG-TAGS tags)))))
1640 (defun org-odt-format-anchor (text name &optional class)
1641 (org-odt-format-target text name))
1643 (defun org-odt-format-bookmark (text id)
1645 (org-odt-format-tags "<text:bookmark text:name=\"%s\"/>" text id)
1648 (defun org-odt-format-target (text id)
1649 (let ((name (concat org-export-odt-bookmark-prefix id)))
1651 (and id (org-odt-format-tags
1652 "<text:bookmark-start text:name=\"%s\"/>" "" name))
1653 (org-odt-format-bookmark text id)
1654 (and id (org-odt-format-tags
1655 "<text:bookmark-end text:name=\"%s\"/>" "" name)))))
1657 (defun org-odt-format-footnote (n def)
1658 (let ((id (concat "fn" n))
1659 (note-class "footnote")
1660 (par-style "Footnote"))
1661 (org-odt-format-tags
1662 '("<text:note text:id=\"%s\" text:note-class=\"%s\">" .
1665 (org-odt-format-tags
1666 '("<text:note-citation>" . "</text:note-citation>")
1668 (org-odt-format-tags
1669 '("<text:note-body>" . "</text:note-body>")
1673 (defun org-odt-format-footnote-reference (n def refcnt)
1675 (org-odt-format-footnote n def)
1676 (org-odt-format-footnote-ref n)))
1678 (defun org-odt-format-footnote-ref (n)
1679 (let ((note-class "footnote")
1681 (ref-name (concat "fn" n)))
1682 (org-odt-format-tags
1683 '("<text:span text:style-name=\"%s\">" . "</text:span>")
1684 (org-odt-format-tags
1685 '("<text:note-ref text:note-class=\"%s\" text:reference-format=\"%s\" text:ref-name=\"%s\">" . "</text:note-ref>")
1686 n note-class ref-format ref-name)
1689 (defun org-odt-get-image-name (file-name)
1693 (concat (sha1 file-name) "." (file-name-extension file-name)) "Pictures")))
1695 (defun org-export-odt-format-image (src href)
1696 "Create image tag with source and attributes."
1698 (let* ((caption (org-find-text-property-in-string 'org-caption src))
1699 (caption (and caption (org-xml-format-desc caption)))
1700 (attr (org-find-text-property-in-string 'org-attributes src))
1701 (label (org-find-text-property-in-string 'org-label src))
1702 (latex-frag (org-find-text-property-in-string
1703 'org-latex-src src))
1704 (category (and latex-frag "__DvipngImage__"))
1705 (attr-plist (org-lparse-get-block-params attr))
1707 (car (assoc-string (plist-get attr-plist :anchor)
1708 (if (or caption label)
1709 '(("paragraph") ("page"))
1710 '(("character") ("paragraph") ("page"))) t)))
1712 (and user-frame-anchor (plist-get attr-plist :style)))
1714 (and user-frame-anchor (plist-get attr-plist :attributes)))
1716 (list user-frame-style user-frame-attrs user-frame-anchor))
1720 (or (org-find-text-property-in-string
1721 'org-latex-src-embed-type src) 'character)))
1724 (size (org-odt-image-size-from-file
1725 src (plist-get attr-plist :width)
1726 (plist-get attr-plist :height)
1727 (plist-get attr-plist :scale) nil embed-as))
1728 (width (car size)) (height (cdr size)))
1730 (setq href (org-propertize href :title "LaTeX Fragment"
1731 :description latex-frag)))
1732 (let ((frame-style-handle (concat (and (or caption label) "Captioned")
1734 (org-odt-format-entity
1735 frame-style-handle href width height
1736 :caption caption :label label :category category
1737 :user-frame-params user-frame-params)))))
1739 (defun org-odt-format-object-description (title description)
1740 (concat (and title (org-odt-format-tags
1741 '("<svg:title>" . "</svg:title>")
1742 (org-odt-encode-plain-text title t)))
1743 (and description (org-odt-format-tags
1744 '("<svg:desc>" . "</svg:desc>")
1745 (org-odt-encode-plain-text description t)))))
1747 (defun org-odt-format-frame (text width height style &optional
1751 (if width (format " svg:width=\"%0.2fcm\"" width) "")
1752 (if height (format " svg:height=\"%0.2fcm\"" height) "")
1754 (format " text:anchor-type=\"%s\"" (or anchor-type "paragraph")))))
1755 (org-odt-format-tags
1756 '("<draw:frame draw:style-name=\"%s\"%s>" . "</draw:frame>")
1757 (concat text (org-odt-format-object-description
1758 (get-text-property 0 :title text)
1759 (get-text-property 0 :description text)))
1760 style frame-attrs)))
1762 (defun org-odt-format-textbox (text width height style &optional
1764 (org-odt-format-frame
1765 (org-odt-format-tags
1766 '("<draw:text-box %s>" . "</draw:text-box>")
1767 text (concat (format " fo:min-height=\"%0.2fcm\"" (or height .2))
1768 (format " fo:min-width=\"%0.2fcm\"" (or width .2))))
1769 width nil style extra anchor-type))
1771 (defun org-odt-format-inlinetask (heading content
1772 &optional todo priority tags)
1773 (org-odt-format-stylized-paragraph
1774 nil (org-odt-format-textbox
1775 (concat (org-odt-format-stylized-paragraph
1776 "OrgInlineTaskHeading"
1778 'HEADLINE (concat (org-lparse-format-todo todo) " " heading)
1780 content) nil nil "OrgInlineTaskFrame" " style:rel-width=\"100%\"")))
1782 (defvar org-odt-entity-frame-styles
1783 '(("CharacterImage" "__Figure__" ("OrgInlineImage" nil "as-char"))
1784 ("ParagraphImage" "__Figure__" ("OrgDisplayImage" nil "paragraph"))
1785 ("PageImage" "__Figure__" ("OrgPageImage" nil "page"))
1786 ("CaptionedParagraphImage" "__Figure__"
1787 ("OrgCaptionedImage"
1788 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
1789 ("OrgImageCaptionFrame" nil "paragraph"))
1790 ("CaptionedPageImage" "__Figure__"
1791 ("OrgCaptionedImage"
1792 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
1793 ("OrgPageImageCaptionFrame" nil "page"))
1794 ("InlineFormula" "__MathFormula__" ("OrgInlineFormula" nil "as-char"))
1795 ("DisplayFormula" "__MathFormula__" ("OrgDisplayFormula" nil "as-char"))
1796 ("CaptionedDisplayFormula" "__MathFormula__"
1797 ("OrgCaptionedFormula" nil "paragraph")
1798 ("OrgFormulaCaptionFrame" nil "as-char"))))
1800 (defun org-odt-merge-frame-params(default-frame-params user-frame-params)
1801 (if (not user-frame-params) default-frame-params
1802 (assert (= (length default-frame-params) 3))
1803 (assert (= (length user-frame-params) 3))
1804 (loop for user-frame-param in user-frame-params
1805 for default-frame-param in default-frame-params
1806 collect (or user-frame-param default-frame-param))))
1808 (defun* org-odt-format-entity (entity href width height
1809 &key caption label category
1811 (let* ((entity-style (assoc-string entity org-odt-entity-frame-styles t))
1812 default-frame-params frame-params)
1814 ((not (or caption label))
1815 (setq default-frame-params (nth 2 entity-style))
1816 (setq frame-params (org-odt-merge-frame-params
1817 default-frame-params user-frame-params))
1818 (apply 'org-odt-format-frame href width height frame-params))
1820 (setq default-frame-params (nth 3 entity-style))
1821 (setq frame-params (org-odt-merge-frame-params
1822 default-frame-params user-frame-params))
1823 (apply 'org-odt-format-textbox
1824 (org-odt-format-stylized-paragraph
1827 (apply 'org-odt-format-frame href width height
1828 (nth 2 entity-style))
1829 (org-odt-format-entity-caption
1830 label caption (or category (nth 1 entity-style)))))
1831 width height frame-params)))))
1833 (defvar org-odt-embedded-images-count 0)
1834 (defun org-odt-copy-image-file (path)
1835 "Returns the internal name of the file"
1836 (let* ((image-type (file-name-extension path))
1837 (media-type (format "image/%s" image-type))
1838 (src-file (expand-file-name
1839 path (file-name-directory org-current-export-file)))
1840 (target-dir "Images/")
1842 (format "%s%04d.%s" target-dir
1843 (incf org-odt-embedded-images-count) image-type)))
1844 (when (not org-lparse-to-buffer)
1845 (message "Embedding %s as %s ..."
1846 (substring-no-properties path) target-file)
1848 (when (= 1 org-odt-embedded-images-count)
1849 (make-directory target-dir)
1850 (org-odt-create-manifest-file-entry "" target-dir))
1852 (copy-file src-file target-file 'overwrite)
1853 (org-odt-create-manifest-file-entry media-type target-file))
1856 (defvar org-export-odt-image-size-probe-method
1857 '(emacs imagemagick force)
1858 "Ordered list of methods by for determining size of an embedded
1861 (defvar org-export-odt-default-image-sizes-alist
1862 '(("character" . (5 . 0.4))
1863 ("paragraph" . (5 . 5)))
1864 "Hardcoded image dimensions one for each of the anchor
1867 ;; A4 page size is 21.0 by 29.7 cms
1868 ;; The default page settings has 2cm margin on each of the sides. So
1869 ;; the effective text area is 17.0 by 25.7 cm
1870 (defvar org-export-odt-max-image-size '(17.0 . 20.0)
1871 "Limiting dimensions for an embedded image.")
1873 (defun org-odt-do-image-size (probe-method file &optional dpi anchor-type)
1874 (setq dpi (or dpi org-export-odt-pixels-per-inch))
1875 (setq anchor-type (or anchor-type "paragraph"))
1876 (flet ((size-in-cms (size-in-pixels)
1877 (flet ((pixels-to-cms (pixels)
1878 (let* ((cms-per-inch 2.54)
1879 (inches (/ pixels dpi)))
1880 (* cms-per-inch inches))))
1882 (cons (pixels-to-cms (car size-in-pixels))
1883 (pixels-to-cms (cdr size-in-pixels)))))))
1886 (size-in-cms (ignore-errors (image-size (create-image file) 'pixels))))
1889 (let ((dim (shell-command-to-string
1890 (format "identify -format \"%%w:%%h\" \"%s\"" file))))
1891 (when (string-match "\\([0-9]+\\):\\([0-9]+\\)" dim)
1892 (cons (string-to-number (match-string 1 dim))
1893 (string-to-number (match-string 2 dim)))))))
1895 (cdr (assoc-string anchor-type
1896 org-export-odt-default-image-sizes-alist))))))
1898 (defun org-odt-image-size-from-file (file &optional user-width
1899 user-height scale dpi embed-as)
1900 (unless (file-name-absolute-p file)
1901 (setq file (expand-file-name
1902 file (file-name-directory org-current-export-file))))
1903 (let* (size width height)
1904 (unless (and user-height user-width)
1905 (loop for probe-method in org-export-odt-image-size-probe-method
1907 do (setq size (org-odt-do-image-size
1908 probe-method file dpi embed-as)))
1909 (or size (error "Cannot determine Image size. Aborting ..."))
1910 (setq width (car size) height (cdr size)))
1913 (setq width (* width scale) height (* height scale)))
1914 ((and user-height user-width)
1915 (setq width user-width height user-height))
1917 (setq width (* user-height (/ width height)) height user-height))
1919 (setq height (* user-width (/ height width)) width user-width))
1921 ;; ensure that an embedded image fits comfortably within a page
1922 (let ((max-width (car org-export-odt-max-image-size))
1923 (max-height (cdr org-export-odt-max-image-size)))
1924 (when (or (> width max-width) (> height max-height))
1925 (let* ((scale1 (/ max-width width))
1926 (scale2 (/ max-height height))
1927 (scale (min scale1 scale2)))
1928 (setq width (* scale width) height (* scale height)))))
1929 (cons width height)))
1931 (defvar org-odt-entity-labels-alist nil
1932 "Associate Labels with the Labelled entities.
1933 Each element of the alist is of the form (LABEL-NAME
1934 CATEGORY-NAME SEQNO LABEL-STYLE-NAME). LABEL-NAME is same as
1935 that specified by \"#+LABEL: ...\" line. CATEGORY-NAME is the
1936 type of the entity that LABEL-NAME is attached to. CATEGORY-NAME
1937 can be one of \"Table\", \"Figure\" or \"Equation\". SEQNO is
1938 the unique number assigned to the referenced entity on a
1939 per-CATEGORY basis. It is generated sequentially and is 1-based.
1940 LABEL-STYLE-NAME is a key `org-odt-label-styles'.
1942 See `org-odt-add-label-definition' and
1943 `org-odt-fixup-label-references'.")
1945 (defvar org-odt-entity-counts-plist nil
1946 "Plist of running counters of SEQNOs for each of the CATEGORY-NAMEs.
1947 See `org-odt-entity-labels-alist' for known CATEGORY-NAMEs.")
1949 (defvar org-odt-label-styles
1950 '(("text" "(%n)" "text" "(%n)")
1951 ("category-and-value" "%e %n%c" "category-and-value" "%e %n"))
1952 "Specify how labels are applied and referenced.
1953 This is an alist where each element is of the
1954 form (LABEL-STYLE-NAME LABEL-ATTACH-FMT LABEL-REF-MODE
1957 LABEL-ATTACH-FMT controls how labels and captions are attached to
1958 an entity. It may contain following specifiers - %e, %n and %c.
1959 %e is replaced with the CATEGORY-NAME. %n is replaced with
1960 \"<text:sequence ...> SEQNO </text:sequence>\". %c is replaced
1961 with CAPTION. See `org-odt-format-label-definition'.
1963 LABEL-REF-MODE and LABEL-REF-FMT controls how label references
1964 are generated. The following XML is generated for a label
1965 reference - \"<text:sequence-ref
1966 text:reference-format=\"LABEL-REF-MODE\" ...> LABEL-REF-FMT
1967 </text:sequence-ref>\". LABEL-REF-FMT may contain following
1968 specifiers - %e and %n. %e is replaced with the CATEGORY-NAME.
1969 %n is replaced with SEQNO. See
1970 `org-odt-format-label-reference'.")
1972 (defvar org-odt-category-map-alist
1973 '(("__Table__" "Table" "category-and-value")
1974 ("__Figure__" "Figure" "category-and-value")
1975 ("__MathFormula__" "Equation" "text")
1976 ("__DvipngImage__" "Equation" "category-and-value"))
1977 "Map a CATEGORY-HANDLE to CATEGORY-NAME and LABEL-STYLE.
1978 This is an alist where each element is of the form
1979 \\(CATEGORY-HANDLE CATEGORY-NAME LABEL-STYLE\\). CATEGORY_HANDLE
1980 could either be one of the internal handles (as seen above) or be
1981 derived from the \"#+LABEL:<label-name>\" specification. See
1982 `org-export-odt-get-category-from-label'. CATEGORY-NAME and
1983 LABEL-STYLE are used for generating ODT labels. See
1984 `org-odt-label-styles'.")
1986 (defvar org-export-odt-user-categories
1987 '("Illustration" "Table" "Text" "Drawing" "Equation" "Figure"))
1989 (defvar org-export-odt-get-category-from-label nil
1990 "Should category of label be inferred from label itself.
1991 When this option is non-nil, a label is parsed in to two
1992 component parts delimited by a \":\" (colon) as shown here -
1993 #+LABEL:[CATEGORY-HANDLE:]EXTRA. The CATEGORY-HANDLE is mapped
1994 to a CATEGORY-NAME and LABEL-STYLE using
1995 `org-odt-category-map-alist'. (If no such map is provided and
1996 CATEGORY-NAME is set to CATEGORY-HANDLE and LABEL-STYLE is set to
1997 \"category-and-value\"). If CATEGORY-NAME so obtained is listed
1998 under `org-export-odt-user-categories' then the user specified
1999 styles are used. Otherwise styles as determined by the internal
2000 CATEGORY-HANDLE is used. See
2001 `org-odt-get-label-category-and-style' for details.")
2003 (defun org-odt-get-label-category-and-style (label default-category)
2004 "See `org-export-odt-get-category-from-label'."
2005 (let ((default-category-map
2006 (assoc default-category org-odt-category-map-alist))
2007 user-category user-category-map category)
2009 ((not org-export-odt-get-category-from-label)
2010 default-category-map)
2011 ((not (setq user-category
2013 (and (string-match "\\`\\(.*\\):.+" label)
2014 (match-string 1 label)))))
2015 default-category-map)
2017 (setq user-category-map
2018 (or (assoc user-category org-odt-category-map-alist)
2019 (list nil user-category "category-and-value"))
2020 category (nth 1 user-category-map))
2021 (if (member category org-export-odt-user-categories)
2023 default-category-map)))))
2025 (defun org-odt-add-label-definition (label default-category)
2026 "Create an entry in `org-odt-entity-labels-alist' and return it."
2027 (setq label (substring-no-properties label))
2028 (let* ((label-props (org-odt-get-label-category-and-style
2029 label default-category))
2030 (category (nth 1 label-props))
2032 (label-style (nth 2 label-props))
2033 (sequence-var (intern (mapconcat
2035 (org-split-string counter) "-")))
2036 (seqno (1+ (or (plist-get org-odt-entity-counts-plist sequence-var)
2038 (label-props (list label category seqno label-style)))
2039 (setq org-odt-entity-counts-plist
2040 (plist-put org-odt-entity-counts-plist sequence-var seqno))
2041 (push label-props org-odt-entity-labels-alist)
2044 (defun org-odt-format-label-definition (caption label category seqno label-style)
2047 (cadr (assoc-string label-style org-odt-label-styles t))
2049 (?n . ,(org-odt-format-tags
2050 '("<text:sequence text:ref-name=\"%s\" text:name=\"%s\" text:formula=\"ooow:%s+1\" style:num-format=\"1\">" . "</text:sequence>")
2051 (format "%d" seqno) label category category))
2052 (?c . ,(or (and caption (concat ": " caption)) "")))))
2054 (defun org-odt-format-label-reference (label category seqno label-style)
2057 (let* ((fmt (cddr (assoc-string label-style org-odt-label-styles t)))
2060 (org-odt-format-tags
2061 '("<text:sequence-ref text:reference-format=\"%s\" text:ref-name=\"%s\">"
2062 . "</text:sequence-ref>")
2063 (format-spec fmt2 `((?e . ,category)
2064 (?n . ,(format "%d" seqno)))) fmt1 label))))
2066 (defun org-odt-fixup-label-references ()
2067 (goto-char (point-min))
2068 (while (re-search-forward
2069 "<text:sequence-ref text:ref-name=\"\\([^\"]+\\)\">[ \t\n]*</text:sequence-ref>"
2071 (let* ((label (match-string 1))
2072 (label-def (assoc label org-odt-entity-labels-alist))
2074 (apply 'org-odt-format-label-reference label-def))))
2075 (if rpl (replace-match rpl t t)
2077 (format "Unable to resolve reference to label \"%s\"" label))))))
2079 (defun org-odt-format-entity-caption (label caption category)
2081 (apply 'org-odt-format-label-definition
2082 caption (org-odt-add-label-definition label category)))
2085 (defun org-odt-format-tags (tag text &rest args)
2086 (let ((prefix (when org-lparse-encode-pending "@"))
2087 (suffix (when org-lparse-encode-pending "@")))
2088 (apply 'org-lparse-format-tags tag text prefix suffix args)))
2090 (defvar org-odt-manifest-file-entries nil)
2091 (defun org-odt-init-outfile (filename)
2092 (unless (executable-find "zip")
2093 ;; Not at all OSes ship with zip by default
2094 (error "Executable \"zip\" needed for creating OpenDocument files"))
2096 (let* ((outdir (make-temp-file
2097 (format org-export-odt-tmpdir-prefix org-lparse-backend) t))
2098 (content-file (expand-file-name "content.xml" outdir)))
2101 (with-current-buffer (find-file-noselect content-file t))
2104 (setq org-odt-manifest-file-entries nil
2105 org-odt-embedded-images-count 0
2106 org-odt-embedded-formulas-count 0
2107 org-odt-section-count 0
2108 org-odt-entity-labels-alist nil
2109 org-odt-list-stack-stashed nil
2110 org-odt-entity-counts-plist nil)
2113 (defcustom org-export-odt-prettify-xml nil
2114 "Specify whether or not the xml output should be prettified.
2115 When this option is turned on, `indent-region' is run on all
2116 component xml buffers before they are saved. Turn this off for
2117 regular use. Turn this on if you need to examine the xml
2119 :group 'org-export-odt
2122 (defvar hfy-user-sheet-assoc) ; bound during org-do-lparse
2123 (defun org-odt-save-as-outfile (target opt-plist)
2125 (org-odt-update-meta-file opt-plist)
2127 ;; write styles file
2128 (when (equal org-lparse-backend 'odt)
2129 (org-odt-update-styles-file opt-plist))
2131 ;; create mimetype file
2132 (let ((mimetype (org-odt-write-mimetype-file org-lparse-backend)))
2133 (org-odt-create-manifest-file-entry mimetype "/" "1.2"))
2135 ;; create a manifest entry for content.xml
2136 (org-odt-create-manifest-file-entry "text/xml" "content.xml")
2138 ;; write out the manifest entries before zipping
2139 (org-odt-write-manifest-file)
2141 (let ((xml-files '("mimetype" "META-INF/manifest.xml" "content.xml"
2143 (zipdir default-directory))
2144 (when (equal org-lparse-backend 'odt)
2145 (push "styles.xml" xml-files))
2146 (message "Switching to directory %s" (expand-file-name zipdir))
2148 ;; save all xml files
2149 (mapc (lambda (file)
2150 (with-current-buffer
2151 (find-file-noselect (expand-file-name file) t)
2152 ;; prettify output if needed
2153 (when org-export-odt-prettify-xml
2154 (indent-region (point-min) (point-max)))
2158 (let* ((target-name (file-name-nondirectory target))
2159 (target-dir (file-name-directory target))
2160 (cmds `(("zip" "-mX0" ,target-name "mimetype")
2161 ("zip" "-rmTq" ,target-name "."))))
2162 (when (file-exists-p target)
2163 ;; FIXME: If the file is locked this throws a cryptic error
2164 (delete-file target))
2166 (let ((coding-system-for-write 'no-conversion) exitcode err-string)
2167 (message "Creating odt file...")
2170 (message "Running %s" (mapconcat 'identity cmd " "))
2172 (with-output-to-string
2174 (apply 'call-process (car cmd)
2175 nil standard-output nil (cdr cmd)))))
2176 (or (zerop exitcode)
2177 (ignore (message "%s" err-string))
2178 (error "Unable to create odt file (%S)" exitcode)))
2181 ;; move the file from outdir to target-dir
2182 (rename-file target-name target-dir)
2184 ;; kill all xml buffers
2185 (mapc (lambda (file)
2187 (find-file-noselect (expand-file-name file zipdir) t)))
2190 (delete-directory zipdir)))
2191 (message "Created %s" target)
2192 (set-buffer (find-file-noselect target t)))
2194 (defconst org-odt-manifest-file-entry-tag
2196 <manifest:file-entry manifest:media-type=\"%s\" manifest:full-path=\"%s\"%s/>")
2198 (defun org-odt-create-manifest-file-entry (&rest args)
2199 (push args org-odt-manifest-file-entries))
2201 (defun org-odt-write-manifest-file ()
2202 (make-directory "META-INF")
2203 (let ((manifest-file (expand-file-name "META-INF/manifest.xml")))
2204 (with-current-buffer
2205 (find-file-noselect manifest-file t)
2207 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
2208 <manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"1.2\">\n")
2210 (lambda (file-entry)
2211 (let* ((version (nth 2 file-entry))
2213 (format " manifest:version=\"%s\"" version)
2216 (format org-odt-manifest-file-entry-tag
2217 (nth 0 file-entry) (nth 1 file-entry) extra))))
2218 org-odt-manifest-file-entries)
2219 (insert "\n</manifest:manifest>"))))
2221 (defun org-odt-update-meta-file (opt-plist)
2222 (let ((date (org-odt-format-date (plist-get opt-plist :date)))
2223 (author (or (plist-get opt-plist :author) ""))
2224 (email (plist-get opt-plist :email))
2225 (keywords (plist-get opt-plist :keywords))
2226 (description (plist-get opt-plist :description))
2227 (title (plist-get opt-plist :title)))
2230 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
2231 <office:document-meta
2232 xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"
2233 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2234 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2235 xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"
2236 xmlns:ooo=\"http://openoffice.org/2004/office\"
2237 office:version=\"1.2\">
2239 (org-odt-format-author)
2240 (org-odt-format-tags
2241 '("\n<meta:initial-creator>" . "</meta:initial-creator>") author)
2242 (org-odt-format-tags '("\n<dc:date>" . "</dc:date>") date)
2243 (org-odt-format-tags
2244 '("\n<meta:creation-date>" . "</meta:creation-date>") date)
2245 (org-odt-format-tags '("\n<meta:generator>" . "</meta:generator>")
2246 (when org-export-creator-info
2247 (format "Org-%s/Emacs-%s"
2248 org-version emacs-version)))
2249 (org-odt-format-tags '("\n<meta:keyword>" . "</meta:keyword>") keywords)
2250 (org-odt-format-tags '("\n<dc:subject>" . "</dc:subject>") description)
2251 (org-odt-format-tags '("\n<dc:title>" . "</dc:title>") title)
2253 " </office:meta>" "</office:document-meta>")
2254 nil (expand-file-name "meta.xml")))
2256 ;; create a manifest entry for meta.xml
2257 (org-odt-create-manifest-file-entry "text/xml" "meta.xml"))
2259 (defun org-odt-update-styles-file (opt-plist)
2260 ;; write styles file
2261 (let ((styles-file (plist-get opt-plist :odt-styles-file)))
2262 (org-odt-copy-styles-file (and styles-file
2263 (read (org-trim styles-file)))))
2265 ;; Update styles.xml - take care of outline numbering
2266 (with-current-buffer
2267 (find-file-noselect (expand-file-name "styles.xml") t)
2268 ;; Don't make automatic backup of styles.xml file. This setting
2269 ;; prevents the backedup styles.xml file from being zipped in to
2270 ;; odt file. This is more of a hackish fix. Better alternative
2271 ;; would be to fix the zip command so that the output odt file
2272 ;; includes only the needed files and excludes any auto-generated
2273 ;; extra files like backups and auto-saves etc etc. Note that
2274 ;; currently the zip command zips up the entire temp directory so
2275 ;; that any auto-generated files created under the hood ends up in
2276 ;; the resulting odt file.
2277 (set (make-local-variable 'backup-inhibited) t)
2279 ;; Import local setting of `org-export-with-section-numbers'
2280 (org-lparse-bind-local-variables opt-plist)
2281 (org-odt-configure-outline-numbering
2282 (if org-export-with-section-numbers org-export-headline-levels 0)))
2284 ;; Write custom stlyes for source blocks
2285 (org-odt-insert-custom-styles-for-srcblocks
2288 (format " %s\n" (cddr style)))
2289 hfy-user-sheet-assoc "")))
2291 (defun org-odt-write-mimetype-file (format)
2292 ;; create mimetype file
2295 (odt "application/vnd.oasis.opendocument.text")
2296 (odf "application/vnd.oasis.opendocument.formula")
2297 (t (error "Unknown OpenDocument backend %S" org-lparse-backend)))))
2298 (write-region mimetype nil (expand-file-name "mimetype"))
2301 (defun org-odt-finalize-outfile ()
2302 (org-odt-delete-empty-paragraphs))
2304 (defun org-odt-delete-empty-paragraphs ()
2305 (goto-char (point-min))
2306 (let ((open "<text:p[^>]*>")
2307 (close "</text:p>"))
2308 (while (re-search-forward (format "%s[ \r\n\t]*%s" open close) nil t)
2309 (replace-match ""))))
2311 (defcustom org-export-odt-convert-processes
2312 '(("BasicODConverter"
2313 ("soffice" "-norestore" "-invisible" "-headless"
2314 "\"macro:///BasicODConverter.Main.Convert(%I,%f,%O)\""))
2316 ("unoconv" "-f" "%f" "-o" "%d" "%i")))
2317 "Specify a list of document converters and their usage.
2318 The converters in this list are offered as choices while
2319 customizing `org-export-odt-convert-process'.
2321 This variable is an alist where each element is of the
2322 form (CONVERTER-NAME CONVERTER-PROCESS). CONVERTER-NAME is name
2323 of the converter. CONVERTER-PROCESS specifies the command-line
2324 syntax of the converter and is of the form (CONVERTER-PROGRAM
2325 ARG1 ARG2 ...). CONVERTER-PROGRAM is the name of the executable.
2326 ARG1, ARG2 etc are command line options that are passed to
2327 CONVERTER-PROGRAM. Format specifiers can be used in the ARGs and
2328 they are interpreted as below:
2330 %i input file name in full
2331 %I input file name as a URL
2332 %f format of the output file
2333 %o output file name in full
2334 %O output file name as a URL
2335 %d output dir in full
2336 %D output dir as a URL."
2337 :group 'org-export-odt
2340 (const :tag "None" nil)
2341 (alist :tag "Converters"
2342 :key-type (string :tag "Converter Name")
2343 :value-type (group (cons (string :tag "Executable")
2344 (repeat (string :tag "Command line args")))))))
2346 (defcustom org-export-odt-convert-process nil
2347 "Use this converter to convert from \"odt\" format to other formats.
2348 During customization, the list of converter names are populated
2349 from `org-export-odt-convert-processes'."
2350 :group 'org-export-odt
2351 :type '(choice :convert-widget
2353 (apply 'widget-convert (widget-type w)
2354 (eval (car (widget-get w :args)))))
2355 `((const :tag "None" nil)
2356 ,@(mapcar (lambda (c)
2357 `(const :tag ,(car c) ,(car c)))
2358 org-export-odt-convert-processes))))
2360 (defcustom org-export-odt-convert-capabilities
2362 ("odt" "ott" "doc" "rtf")
2363 (("pdf" "pdf") ("odt" "odt") ("xhtml" "html") ("rtf" "rtf")
2364 ("ott" "ott") ("doc" "doc") ("ooxml" "xml") ("html" "html")))
2366 ("html" "xhtml") (("pdf" "pdf") ("odt" "txt") ("html" "html")))
2368 ("ods" "ots" "xls" "csv")
2369 (("pdf" "pdf") ("ots" "ots") ("html" "html") ("csv" "csv")
2370 ("ods" "ods") ("xls" "xls") ("xhtml" "xhtml") ("ooxml" "xml")))
2373 (("pdf" "pdf") ("swf" "swf") ("odp" "odp") ("xhtml" "xml")
2374 ("otp" "otp") ("ppt" "ppt") ("odg" "odg") ("html" "html"))))
2375 "Specify input and output formats of `org-export-odt-convert-process'.
2376 More correctly, specify the set of input and output formats that
2377 the user is actually interested in.
2379 This variable is an alist where each element is of the
2380 form (DOCUMENT-CLASS INPUT-FMT-LIST OUTPUT-FMT-ALIST).
2381 INPUT-FMT-LIST is a list of INPUT-FMTs. OUTPUT-FMT-ALIST is an
2382 alist where each element is of the form (OUTPUT-FMT
2383 OUTPUT-FILE-EXTENSION).
2385 The variable is interpreted as follows:
2386 `org-export-odt-convert-process' can take any document that is in
2387 INPUT-FMT-LIST and produce any document that is in the
2388 OUTPUT-FMT-LIST. A document converted to OUTPUT-FMT will have
2389 OUTPUT-FILE-EXTENSION as the file name extension. OUTPUT-FMT
2390 serves dual purposes:
2391 - It is used for populating completion candidates during
2392 `org-export-odt-convert' commands.
2393 - It is used as the value of \"%f\" specifier in
2394 `org-export-odt-convert-process'.
2396 DOCUMENT-CLASS is used to group a set of file formats in
2397 INPUT-FMT-LIST in to a single class.
2399 Note that this variable inherently captures how LibreOffice based
2400 converters work. LibreOffice maps documents of various formats
2401 to classes like Text, Web, Spreadsheet, Presentation etc and
2402 allow document of a given class (irrespective of it's source
2403 format) to be converted to any of the export formats associated
2406 See default setting of this variable for an typical
2408 :group 'org-export-odt
2411 (const :tag "None" nil)
2412 (alist :key-type (string :tag "Document Class")
2414 (group (repeat :tag "Input formats" (string :tag "Input format"))
2415 (alist :tag "Output formats"
2416 :key-type (string :tag "Output format")
2418 (group (string :tag "Output file extension")))))))
2420 (declare-function org-create-math-formula "org"
2421 (latex-frag &optional mathml-file))
2424 (defun org-export-odt-convert (&optional in-file out-fmt prefix-arg)
2425 "Convert IN-FILE to format OUT-FMT using a command line converter.
2426 IN-FILE is the file to be converted. If unspecified, it defaults
2427 to variable `buffer-file-name'. OUT-FMT is the desired output
2428 format. Use `org-export-odt-convert-process' as the converter.
2429 If PREFIX-ARG is non-nil then the newly converted file is opened
2430 using `org-open-file'."
2432 (append (org-lparse-convert-read-params) current-prefix-arg))
2433 (org-lparse-do-convert in-file out-fmt prefix-arg))
2435 (defun org-odt-get (what &optional opt-plist)
2438 (EXPORT-DIR (org-export-directory :html opt-plist))
2439 (FILE-NAME-EXTENSION "odt")
2440 (EXPORT-BUFFER-NAME "*Org ODT Export*")
2441 (ENTITY-CONTROL org-odt-entity-control-callbacks-alist)
2442 (ENTITY-FORMAT org-odt-entity-format-callbacks-alist)
2443 (INIT-METHOD 'org-odt-init-outfile)
2444 (FINAL-METHOD 'org-odt-finalize-outfile)
2445 (SAVE-METHOD 'org-odt-save-as-outfile)
2447 (and org-export-odt-convert-process
2448 (cadr (assoc-string org-export-odt-convert-process
2449 org-export-odt-convert-processes t))))
2450 (CONVERT-CAPABILITIES
2451 (and org-export-odt-convert-process
2452 (cadr (assoc-string org-export-odt-convert-process
2453 org-export-odt-convert-processes t))
2454 org-export-odt-convert-capabilities))
2456 (SPECIAL-STRING-REGEXPS org-export-odt-special-string-regexps)
2457 (INLINE-IMAGES 'maybe)
2458 (INLINE-IMAGE-EXTENSIONS '("png" "jpeg" "jpg" "gif" "svg"))
2459 (PLAIN-TEXT-MAP '(("&" . "&") ("<" . "<") (">" . ">")))
2460 (TABLE-FIRST-COLUMN-AS-LABELS nil)
2461 (FOOTNOTE-SEPARATOR (org-lparse-format 'FONTIFY "," 'superscript))
2462 (CODING-SYSTEM-FOR-WRITE 'utf-8)
2463 (CODING-SYSTEM-FOR-SAVE 'utf-8)
2464 (t (error "Unknown property: %s" what))))
2466 (defvar org-lparse-latex-fragment-fallback) ; set by org-do-lparse
2467 (defun org-export-odt-do-preprocess-latex-fragments ()
2468 "Convert LaTeX fragments to images."
2469 (let* ((latex-frag-opt (plist-get org-lparse-opt-plist :LaTeX-fragments))
2470 (latex-frag-opt ; massage the options
2471 (or (and (member latex-frag-opt '(mathjax t))
2472 (not (and (fboundp 'org-format-latex-mathml-available-p)
2473 (org-format-latex-mathml-available-p)))
2474 (prog1 org-lparse-latex-fragment-fallback
2477 "LaTeX to MathML converter not available. "
2478 (format "Using %S instead."
2479 org-lparse-latex-fragment-fallback)))))
2481 cache-dir display-msg)
2483 ((eq latex-frag-opt 'dvipng)
2484 (setq cache-dir "ltxpng/")
2485 (setq display-msg "Creating LaTeX image %s"))
2486 ((member latex-frag-opt '(mathjax t))
2487 (setq latex-frag-opt 'mathml)
2488 (setq cache-dir "ltxmathml/")
2489 (setq display-msg "Creating MathML formula %s")))
2490 (when (and org-current-export-file)
2492 (concat cache-dir (file-name-sans-extension
2493 (file-name-nondirectory org-current-export-file)))
2494 org-current-export-dir nil display-msg
2495 nil nil latex-frag-opt))))
2497 (defadvice org-format-latex-as-mathml
2498 (after org-odt-protect-latex-fragment activate)
2499 "Encode LaTeX fragment as XML.
2500 Do this when translation to MathML fails."
2501 (when (or (not (> (length ad-return-value) 0))
2502 (get-text-property 0 'org-protected ad-return-value))
2503 (setq ad-return-value
2504 (org-propertize (org-odt-encode-plain-text (ad-get-arg 0))
2505 'org-protected t))))
2507 (defun org-export-odt-preprocess-latex-fragments ()
2508 (when (equal org-export-current-backend 'odt)
2509 (org-export-odt-do-preprocess-latex-fragments)))
2511 (defun org-export-odt-preprocess-label-references ()
2512 (goto-char (point-min))
2513 (let (label label-components category value pretty-label)
2514 (while (re-search-forward "\\\\ref{\\([^{}\n]+\\)}" nil t)
2515 (org-if-unprotected-at (match-beginning 1)
2517 (let ((org-lparse-encode-pending t)
2518 (label (match-string 1)))
2519 ;; markup generated below is mostly an eye-candy. At
2520 ;; pre-processing stage, there is no information on which
2521 ;; entity a label reference points to. The actual markup
2522 ;; is generated as part of `org-odt-fixup-label-references'
2523 ;; which gets called at the fag end of export. By this
2524 ;; time we would have seen and collected all the label
2525 ;; definitions in `org-odt-entity-labels-alist'.
2526 (org-odt-format-tags
2527 '("<text:sequence-ref text:ref-name=\"%s\">" .
2528 "</text:sequence-ref>")
2529 "" (org-add-props label '(org-protected t)))) t t)))))
2531 ;; process latex fragments as part of
2532 ;; `org-export-preprocess-after-blockquote-hook'. Note that this hook
2533 ;; is the one that is closest and well before the call to
2534 ;; `org-export-attach-captions-and-attributes' in
2535 ;; `org-export-preprocess-stirng'. The above arrangement permits
2536 ;; captions, labels and attributes to be attached to png images
2537 ;; generated out of latex equations.
2538 (add-hook 'org-export-preprocess-after-blockquote-hook
2539 'org-export-odt-preprocess-latex-fragments)
2541 (defun org-export-odt-preprocess (parameters)
2542 (org-export-odt-preprocess-label-references))
2544 (declare-function archive-zip-extract "arc-mode.el" (archive name))
2545 (defun org-odt-zip-extract-one (archive member &optional target)
2547 (let* ((target (or target default-directory))
2548 (archive (expand-file-name archive))
2549 (archive-zip-extract
2550 (list "unzip" "-qq" "-o" "-d" target))
2551 exit-code command-output)
2552 (setq command-output
2554 (setq exit-code (archive-zip-extract archive member))
2556 (unless (zerop exit-code)
2557 (message command-output)
2558 (error "Extraction failed"))))
2560 (defun org-odt-zip-extract (archive members &optional target)
2561 (when (atom members) (setq members (list members)))
2562 (mapc (lambda (member)
2563 (org-odt-zip-extract-one archive member target))
2566 (defun org-odt-copy-styles-file (&optional styles-file)
2567 ;; Non-availability of styles.xml is not a critical error. For now
2568 ;; throw an error purely for aesthetic reasons.
2569 (setq styles-file (or styles-file
2570 org-export-odt-styles-file
2571 (expand-file-name "OrgOdtStyles.xml"
2573 (error "org-odt: Missing styles file?")))
2575 ((listp styles-file)
2576 (let ((archive (nth 0 styles-file))
2577 (members (nth 1 styles-file)))
2578 (org-odt-zip-extract archive members)
2581 (when (org-file-image-p member)
2582 (let* ((image-type (file-name-extension member))
2583 (media-type (format "image/%s" image-type)))
2584 (org-odt-create-manifest-file-entry media-type member))))
2586 ((and (stringp styles-file) (file-exists-p styles-file))
2587 (let ((styles-file-type (file-name-extension styles-file)))
2589 ((string= styles-file-type "xml")
2590 (copy-file styles-file "styles.xml" t))
2591 ((member styles-file-type '("odt" "ott"))
2592 (org-odt-zip-extract styles-file "styles.xml")))))
2594 (error (format "Invalid specification of styles.xml file: %S"
2595 org-export-odt-styles-file))))
2597 ;; create a manifest entry for styles.xml
2598 (org-odt-create-manifest-file-entry "text/xml" "styles.xml"))
2600 (defvar org-export-odt-factory-settings
2601 "d4328fb9d1b6cb211d4320ff546829f26700dc5e"
2602 "SHA1 hash of OrgOdtStyles.xml.")
2604 (defun org-odt-configure-outline-numbering (level)
2605 "Outline numbering is retained only upto LEVEL.
2606 To disable outline numbering pass a LEVEL of 0."
2607 (goto-char (point-min))
2609 "<text:outline-level-style\\([^>]*\\)text:level=\"\\([^\"]*\\)\"\\([^>]*\\)>")
2611 "<text:outline-level-style\\1text:level=\"\\2\" style:num-format=\"\">"))
2612 (while (re-search-forward regex nil t)
2613 (when (> (string-to-number (match-string 2)) level)
2614 (replace-match replacement t nil))))
2618 (defun org-export-as-odf (latex-frag &optional odf-file)
2619 "Export LATEX-FRAG as OpenDocument formula file ODF-FILE.
2620 Use `org-create-math-formula' to convert LATEX-FRAG first to
2621 MathML. When invoked as an interactive command, use
2622 `org-latex-regexps' to infer LATEX-FRAG from currently active
2623 region. If no LaTeX fragments are found, prompt for it. Push
2624 MathML source to kill ring, if `org-export-copy-to-kill-ring' is
2628 (setq frag (and (setq frag (and (region-active-p)
2629 (buffer-substring (region-beginning)
2631 (loop for e in org-latex-regexps
2632 thereis (when (string-match (nth 1 e) frag)
2633 (match-string (nth 2 e) frag)))))
2634 (read-string "LaTeX Fragment: " frag nil frag))
2635 ,(let ((odf-filename (expand-file-name
2637 (file-name-sans-extension
2638 (or (file-name-nondirectory buffer-file-name)))
2640 (file-name-directory buffer-file-name))))
2641 (message "default val is %s" odf-filename)
2642 (read-file-name "ODF filename: " nil odf-filename nil
2643 (file-name-nondirectory odf-filename)))))
2644 (let* ((org-lparse-backend 'odf)
2645 org-lparse-opt-plist
2646 (filename (or odf-file
2649 (file-name-sans-extension
2650 (or (file-name-nondirectory buffer-file-name)))
2652 (file-name-directory buffer-file-name))))
2653 (buffer (find-file-noselect (org-odt-init-outfile filename)))
2654 (coding-system-for-write 'utf-8)
2655 (save-buffer-coding-system 'utf-8))
2657 (set-buffer-file-coding-system coding-system-for-write)
2658 (let ((mathml (org-create-math-formula latex-frag)))
2659 (unless mathml (error "No Math formula created"))
2661 (or (org-export-push-to-kill-ring
2662 (upcase (symbol-name org-lparse-backend)))
2663 (message "Exporting... done")))
2664 (org-odt-save-as-outfile filename nil)))
2667 (defun org-export-as-odf-and-open ()
2668 "Export LaTeX fragment as OpenDocument formula and immediately open it.
2669 Use `org-export-as-odf' to read LaTeX fragment and OpenDocument
2672 (org-lparse-and-open
2673 nil nil nil (call-interactively 'org-export-as-odf)))
2677 ;;; org-odt.el ends here