Add support for embedding an equation via a link to its *.odf file
[org-mode/org-jambu.git] / contrib / lisp / org-odt.el
blob0d53efd71c08959da3b5222cad28a6f3ea849206
1 ;;; org-odt.el --- OpenDocumentText export for Org-mode
3 ;; Copyright (C) 2010-2011 Jambunathan <kjambunathan at gmail dot com>
5 ;; Author: Jambunathan K <kjambunathan at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 0.8
10 ;; This file is not (yet) part of GNU Emacs.
11 ;; However, it is distributed under the same license.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;;; Code:
30 (eval-when-compile (require 'cl))
31 (require 'org-lparse)
33 (defgroup org-export-odt nil
34 "Options specific for ODT export of Org-mode files."
35 :tag "Org Export ODT"
36 :group 'org-export)
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>"
45 nil t)
46 (replace-match ""))
47 (goto-char (point-min))
49 ;; Convert whitespace place holders
50 (goto-char (point-min))
51 (let (beg end n)
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))
55 (goto-char beg)
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 '(("\\\\-" . "&#x00ad;\\1") ; shy
70 ("---\\([^-]\\)" . "&#x2014;\\1") ; mdash
71 ("--\\([^-]\\)" . "&#x2013;\\1") ; ndash
72 ("\\.\\.\\." . "&#x2026;")) ; hellip
73 "Regular expressions for special string conversion.")
75 (defconst org-odt-lib-dir (file-name-directory load-file-name))
76 (defconst org-odt-data-dir
77 (let ((dir1 (expand-file-name "../odt" org-odt-lib-dir)) ; git
78 (dir2 (expand-file-name "./" org-odt-lib-dir))) ; elpa
79 (cond
80 ((file-directory-p dir1) dir1)
81 ((file-directory-p dir2) dir2)
82 (t (error "Cannot find factory styles file. Check package dir layout"))))
83 "Directory that holds auxiliary files used by the ODT exporter.
85 The 'styles' subdir contains the following xml files -
86 'OrgOdtStyles.xml' and 'OrgOdtContentTemplate.xml' - which are
87 used as factory settings of `org-export-odt-styles-file' and
88 `org-export-odt-content-template-file'.
90 The 'etc/schema' subdir contains rnc files for validating of
91 OpenDocument xml files.")
93 (defvar org-odt-file-extensions
94 '(("odt" . "OpenDocument Text")
95 ("ott" . "OpenDocument Text Template")
96 ("odm" . "OpenDocument Master Document")
97 ("ods" . "OpenDocument Spreadsheet")
98 ("ots" . "OpenDocument Spreadsheet Template")
99 ("odg" . "OpenDocument Drawing (Graphics)")
100 ("otg" . "OpenDocument Drawing Template")
101 ("odp" . "OpenDocument Presentation")
102 ("otp" . "OpenDocument Presentation Template")
103 ("odi" . "OpenDocument Image")
104 ("odf" . "OpenDocument Formula")
105 ("odc" . "OpenDocument Chart")
106 ("doc" . "Microsoft Text")
107 ("docx" . "Microsoft Text")
108 ("xls" . "Microsoft Spreadsheet")
109 ("xlsx" . "Microsoft Spreadsheet")
110 ("ppt" . "Microsoft Presentation")
111 ("pptx" . "Microsoft Presentation")))
113 (defvar org-odt-ms-file-extensions
114 '(("doc" . "Microsoft Text")
115 ("docx" . "Microsoft Text")
116 ("xls" . "Microsoft Spreadsheet")
117 ("xlsx" . "Microsoft Spreadsheet")
118 ("ppt" . "Microsoft Presentation")
119 ("pptx" . "Microsoft Presentation")))
121 ;; RelaxNG validation of OpenDocument xml files
122 (eval-after-load 'rng-nxml
123 '(setq rng-nxml-auto-validate-flag t))
125 (eval-after-load 'rng-loc
126 '(add-to-list 'rng-schema-locating-files
127 (expand-file-name "etc/schema/schemas.xml" org-odt-data-dir)))
129 (mapc
130 (lambda (desc)
131 ;; Let Org open all OpenDocument files using system-registered app
132 (add-to-list 'org-file-apps
133 (cons (concat "\\." (car desc) "\\'") 'system))
134 ;; Let Emacs open all OpenDocument files in archive mode
135 (add-to-list 'auto-mode-alist
136 (cons (concat "\\." (car desc) "\\'") 'archive-mode)))
137 org-odt-file-extensions)
139 (mapc
140 (lambda (desc)
141 ;; Let Org open all Microsoft files using system-registered app
142 (add-to-list 'org-file-apps
143 (cons (concat "\\." (car desc) "\\'") 'system)))
144 org-odt-ms-file-extensions)
146 ;; register the odt exporter with the pre-processor
147 (add-to-list 'org-export-backends 'odt)
149 ;; register the odt exporter with org-lparse library
150 (org-lparse-register-backend 'odt)
152 (defun org-odt-unload-function ()
153 (org-lparse-unregister-backend 'odt)
154 (remove-hook 'org-export-preprocess-after-blockquote-hook
155 'org-export-odt-preprocess-latex-fragments)
156 nil)
158 (defcustom org-export-odt-content-template-file nil
159 "Template file for \"content.xml\".
160 The exporter embeds the exported content just before
161 \"</office:text>\" element.
163 If unspecified, the file named \"OrgOdtContentTemplate.xml\"
164 under `org-odt-data-dir' is used."
165 :type 'file
166 :group 'org-export-odt)
168 (defcustom org-export-odt-styles-file nil
169 "Default styles file for use with ODT export.
170 Valid values are one of:
171 1. nil
172 2. path to a styles.xml file
173 3. path to a *.odt or a *.ott file
174 4. list of the form (ODT-OR-OTT-FILE (FILE-MEMBER-1 FILE-MEMBER-2
175 ...))
177 In case of option 1, an in-built styles.xml is used. See
178 `org-odt-data-dir' for more information.
180 In case of option 3, the specified file is unzipped and the
181 styles.xml embedded therein is used.
183 In case of option 4, the specified ODT-OR-OTT-FILE is unzipped
184 and FILE-MEMBER-1, FILE-MEMBER-2 etc are copied in to the
185 generated odt file. Use relative path for specifying the
186 FILE-MEMBERS. styles.xml must be specified as one of the
187 FILE-MEMBERS.
189 Use options 1, 2 or 3 only if styles.xml alone suffices for
190 achieving the desired formatting. Use option 4, if the styles.xml
191 references additional files like header and footer images for
192 achieving the desired formattting.
194 Use \"#+ODT_STYLES_FILE: ...\" directive to set this variable on
195 a per-file basis. For example,
197 #+ODT_STYLES_FILE: \"/path/to/styles.xml\" or
198 #+ODT_STYLES_FILE: (\"/path/to/file.ott\" (\"styles.xml\" \"image/hdr.png\"))."
199 :group 'org-export-odt
200 :type
201 '(choice
202 (const :tag "Factory settings" nil)
203 (file :must-match t :tag "styles.xml")
204 (file :must-match t :tag "ODT or OTT file")
205 (list :tag "ODT or OTT file + Members"
206 (file :must-match t :tag "ODF Text or Text Template file")
207 (cons :tag "Members"
208 (file :tag " Member" "styles.xml")
209 (repeat (file :tag "Member"))))))
211 (eval-after-load 'org-exp
212 '(add-to-list 'org-export-inbuffer-options-extra
213 '("ODT_STYLES_FILE" :odt-styles-file)))
215 (defconst org-export-odt-tmpdir-prefix "%s-")
216 (defconst org-export-odt-bookmark-prefix "OrgXref.")
218 (defvar org-export-odt-embed-images t
219 "Should the images be copied in to the odt file or just linked?")
221 (defvar org-export-odt-inline-images 'maybe) ; counterpart of
222 ; `org-export-html-inline-images'
224 (defcustom org-export-odt-inline-image-extensions
225 '("png" "jpeg" "jpg" "gif")
226 "Extensions of image files that can be inlined into HTML."
227 :type '(repeat (string :tag "Extension"))
228 :group 'org-export-odt)
230 (defcustom org-export-odt-pixels-per-inch display-pixels-per-inch
231 ;; FIXME add docstring
233 :type 'float
234 :group 'org-export-odt)
236 (defvar org-export-odt-default-org-styles-alist
237 '((paragraph . ((default . "Text_20_body")
238 (fixedwidth . "OrgFixedWidthBlock")
239 (verse . "OrgVerse")
240 (quote . "Quotations")
241 (blockquote . "Quotations")
242 (center . "OrgCenter")
243 (left . "OrgLeft")
244 (right . "OrgRight")
245 (title . "Heading_20_1.title")
246 (footnote . "Footnote")
247 (src . "OrgSrcBlock")
248 (illustration . "Illustration")
249 (table . "Table")
250 (definition-term . "Text_20_body_20_bold")
251 (horizontal-line . "Horizontal_20_Line")))
252 (character . ((bold . "Bold")
253 (emphasis . "Emphasis")
254 (code . "OrgCode")
255 (verbatim . "OrgCode")
256 (strike . "Strikethrough")
257 (underline . "Underline")
258 (subscript . "OrgSubscript")
259 (superscript . "OrgSuperscript")))
260 (list . ((ordered . "OrgNumberedList")
261 (unordered . "OrgBulletedList")
262 (description . "OrgDescriptionList"))))
263 "Default styles for various entities.")
265 (defvar org-export-odt-org-styles-alist org-export-odt-default-org-styles-alist)
266 (defun org-odt-get-style-name-for-entity (category &optional entity)
267 (let ((entity (or entity 'default)))
269 (cdr (assoc entity (cdr (assoc category
270 org-export-odt-org-styles-alist))))
271 (cdr (assoc entity (cdr (assoc category
272 org-export-odt-default-org-styles-alist))))
273 (error "Cannot determine style name for entity %s of type %s"
274 entity category))))
276 (defcustom org-export-odt-preferred-output-format nil
277 "Automatically post-process to this format after exporting to \"odt\".
278 Interactive commands `org-export-as-odt' and
279 `org-export-as-odt-and-open' export first to \"odt\" format and
280 then use `org-export-odt-convert-process' to convert the
281 resulting document to this format. During customization of this
282 variable, the list of valid values are populated based on
283 `org-export-odt-convert-capabilities'."
284 :group 'org-export-odt
285 :type '(choice :convert-widget
286 (lambda (w)
287 (apply 'widget-convert (widget-type w)
288 (eval (car (widget-get w :args)))))
289 `((const :tag "None" nil)
290 ,@(mapcar (lambda (c)
291 `(const :tag ,c ,c))
292 (org-lparse-reachable-formats "odt")))))
294 ;;;###autoload
295 (defun org-export-as-odt-and-open (arg)
296 "Export the outline as ODT and immediately open it with a browser.
297 If there is an active region, export only the region.
298 The prefix ARG specifies how many levels of the outline should become
299 headlines. The default is 3. Lower levels will become bulleted lists."
300 (interactive "P")
301 (org-lparse-and-open
302 (or org-export-odt-preferred-output-format "odt") "odt" arg))
304 ;;;###autoload
305 (defun org-export-as-odt-batch ()
306 "Call the function `org-lparse-batch'.
307 This function can be used in batch processing as:
308 emacs --batch
309 --load=$HOME/lib/emacs/org.el
310 --eval \"(setq org-export-headline-levels 2)\"
311 --visit=MyFile --funcall org-export-as-odt-batch"
312 (org-lparse-batch "odt"))
314 ;;;###autoload
315 (defun org-export-as-odt-to-buffer (arg)
316 "Call `org-lparse-odt` with output to a temporary buffer.
317 No file is created. The prefix ARG is passed through to `org-lparse-to-buffer'."
318 (interactive "P")
319 (org-lparse-to-buffer "odt" arg))
321 ;;;###autoload
322 (defun org-replace-region-by-odt (beg end)
323 "Assume the current region has org-mode syntax, and convert it to ODT.
324 This can be used in any buffer. For example, you could write an
325 itemized list in org-mode syntax in an ODT buffer and then use this
326 command to convert it."
327 (interactive "r")
328 (org-replace-region-by "odt" beg end))
330 ;;;###autoload
331 (defun org-export-region-as-odt (beg end &optional body-only buffer)
332 "Convert region from BEG to END in org-mode buffer to ODT.
333 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
334 contents, and only produce the region of converted text, useful for
335 cut-and-paste operations.
336 If BUFFER is a buffer or a string, use/create that buffer as a target
337 of the converted ODT. If BUFFER is the symbol `string', return the
338 produced ODT as a string and leave not buffer behind. For example,
339 a Lisp program could call this function in the following way:
341 (setq odt (org-export-region-as-odt beg end t 'string))
343 When called interactively, the output buffer is selected, and shown
344 in a window. A non-interactive call will only return the buffer."
345 (interactive "r\nP")
346 (org-lparse-region "odt" beg end body-only buffer))
348 ;;; org-export-as-odt
349 ;;;###autoload
350 (defun org-export-as-odt (arg &optional hidden ext-plist
351 to-buffer body-only pub-dir)
352 "Export the outline as a OpenDocumentText file.
353 If there is an active region, export only the region. The prefix
354 ARG specifies how many levels of the outline should become
355 headlines. The default is 3. Lower levels will become bulleted
356 lists. HIDDEN is obsolete and does nothing.
357 EXT-PLIST is a property list with external parameters overriding
358 org-mode's default settings, but still inferior to file-local
359 settings. When TO-BUFFER is non-nil, create a buffer with that
360 name and export to that buffer. If TO-BUFFER is the symbol
361 `string', don't leave any buffer behind but just return the
362 resulting XML as a string. When BODY-ONLY is set, don't produce
363 the file header and footer, simply return the content of
364 <body>...</body>, without even the body tags themselves. When
365 PUB-DIR is set, use this as the publishing directory."
366 (interactive "P")
367 (org-lparse (or org-export-odt-preferred-output-format "odt")
368 "odt" arg hidden ext-plist to-buffer body-only pub-dir))
370 (defvar org-odt-entity-control-callbacks-alist
371 `((EXPORT
372 . (org-odt-begin-export org-odt-end-export))
373 (DOCUMENT-CONTENT
374 . (org-odt-begin-document-content org-odt-end-document-content))
375 (DOCUMENT-BODY
376 . (org-odt-begin-document-body org-odt-end-document-body))
377 (TOC
378 . (org-odt-begin-toc org-odt-end-toc))
379 (ENVIRONMENT
380 . (org-odt-begin-environment org-odt-end-environment))
381 (FOOTNOTE-DEFINITION
382 . (org-odt-begin-footnote-definition org-odt-end-footnote-definition))
383 (TABLE
384 . (org-odt-begin-table org-odt-end-table))
385 (TABLE-ROWGROUP
386 . (org-odt-begin-table-rowgroup org-odt-end-table-rowgroup))
387 (LIST
388 . (org-odt-begin-list org-odt-end-list))
389 (LIST-ITEM
390 . (org-odt-begin-list-item org-odt-end-list-item))
391 (OUTLINE
392 . (org-odt-begin-outline org-odt-end-outline))
393 (OUTLINE-TEXT
394 . (org-odt-begin-outline-text org-odt-end-outline-text))
395 (PARAGRAPH
396 . (org-odt-begin-paragraph org-odt-end-paragraph)))
399 (defvar org-odt-entity-format-callbacks-alist
400 `((EXTRA-TARGETS . org-lparse-format-extra-targets)
401 (ORG-TAGS . org-lparse-format-org-tags)
402 (SECTION-NUMBER . org-lparse-format-section-number)
403 (HEADLINE . org-odt-format-headline)
404 (TOC-ENTRY . org-odt-format-toc-entry)
405 (TOC-ITEM . org-odt-format-toc-item)
406 (TAGS . org-odt-format-tags)
407 (SPACES . org-odt-format-spaces)
408 (TABS . org-odt-format-tabs)
409 (LINE-BREAK . org-odt-format-line-break)
410 (FONTIFY . org-odt-format-fontify)
411 (TODO . org-lparse-format-todo)
412 (LINK . org-odt-format-link)
413 (INLINE-IMAGE . org-odt-format-inline-image)
414 (ORG-LINK . org-odt-format-org-link)
415 (HEADING . org-odt-format-heading)
416 (ANCHOR . org-odt-format-anchor)
417 (TABLE . org-lparse-format-table)
418 (TABLE-ROW . org-odt-format-table-row)
419 (TABLE-CELL . org-odt-format-table-cell)
420 (FOOTNOTES-SECTION . ignore)
421 (FOOTNOTE-REFERENCE . org-odt-format-footnote-reference)
422 (HORIZONTAL-LINE . org-odt-format-horizontal-line)
423 (COMMENT . org-odt-format-comment)
424 (LINE . org-odt-format-line)
425 (ORG-ENTITY . org-odt-format-org-entity))
428 ;;;_. callbacks
429 ;;;_. control callbacks
430 ;;;_ , document body
431 (defun org-odt-begin-office-body ()
432 ;; automatic styles
433 (insert-file-contents
434 (or org-export-odt-content-template-file
435 (expand-file-name "styles/OrgOdtContentTemplate.xml"
436 org-odt-data-dir)))
437 (goto-char (point-min))
438 (re-search-forward "</office:text>" nil nil)
439 (delete-region (match-beginning 0) (point-max)))
441 ;; Following variable is let bound when `org-do-lparse' is in
442 ;; progress. See org-html.el.
443 (defvar org-lparse-toc)
444 (defun org-odt-begin-document-body (opt-plist)
445 (org-odt-begin-office-body)
446 (let ((title (plist-get opt-plist :title)))
447 (when title
448 (insert
449 (org-odt-format-stylized-paragraph 'title title))))
451 ;; insert toc
452 (when org-lparse-toc
453 (insert "\n" org-lparse-toc "\n")))
455 (defvar org-lparse-body-only) ; let bound during org-do-lparse
456 (defvar org-lparse-to-buffer) ; let bound during org-do-lparse
457 (defun org-odt-end-document-body (opt-plist)
458 (unless org-lparse-body-only
459 (org-lparse-insert-tag "</office:text>")
460 (org-lparse-insert-tag "</office:body>")))
462 (defun org-odt-begin-document-content (opt-plist)
463 (ignore))
465 (defun org-odt-end-document-content ()
466 (org-lparse-insert-tag "</office:document-content>"))
468 (defun org-odt-begin-outline (level1 snumber title tags
469 target extra-targets class)
470 (org-lparse-insert
471 'HEADING (org-lparse-format
472 'HEADLINE title extra-targets tags snumber level1)
473 level1 target))
475 (defun org-odt-end-outline ()
476 (ignore))
478 (defun org-odt-begin-outline-text (level1 snumber class)
479 (ignore))
481 (defun org-odt-end-outline-text ()
482 (ignore))
484 (defun org-odt-begin-paragraph (&optional style)
485 (org-lparse-insert-tag
486 "<text:p%s>" (org-odt-get-extra-attrs-for-paragraph-style style)))
488 (defun org-odt-end-paragraph ()
489 (org-lparse-insert-tag "</text:p>"))
491 (defun org-odt-get-extra-attrs-for-paragraph-style (style)
492 (let (style-name)
493 (setq style-name
494 (cond
495 ((stringp style) style)
496 ((symbolp style) (org-odt-get-style-name-for-entity
497 'paragraph style))))
498 (unless style-name
499 (error "Don't know how to handle paragraph style %s" style))
500 (format " text:style-name=\"%s\"" style-name)))
502 (defun org-odt-format-stylized-paragraph (style text)
503 (org-odt-format-tags
504 '("<text:p%s>" . "</text:p>") text
505 (org-odt-get-extra-attrs-for-paragraph-style style)))
507 (defvar org-lparse-opt-plist) ; bound during org-do-lparse
508 (defun org-odt-format-author (&optional author)
509 (when (setq author (or author (plist-get org-lparse-opt-plist :author)))
510 (org-odt-format-tags '("<dc:creator>" . "</dc:creator>") author)))
512 (defun org-odt-iso-date-from-org-timestamp (&optional org-ts)
513 (save-match-data
514 (let* ((time
515 (and (stringp org-ts)
516 (string-match org-ts-regexp0 org-ts)
517 (apply 'encode-time
518 (org-fix-decoded-time
519 (org-parse-time-string (match-string 0 org-ts) t)))))
520 (date (format-time-string "%Y-%m-%dT%H:%M:%S%z" time)))
521 (format "%s:%s" (substring date 0 -2) (substring date -2)))))
523 (defun org-odt-begin-annotation (&optional author date)
524 (org-lparse-insert-tag "<office:annotation>")
525 (when (setq author (org-odt-format-author author))
526 (insert author))
527 (insert (org-odt-format-tags
528 '("<dc:date>" . "</dc:date>")
529 (org-odt-iso-date-from-org-timestamp
530 (or date (plist-get org-lparse-opt-plist :date)))))
531 (org-lparse-begin-paragraph))
533 (defun org-odt-end-annotation ()
534 (org-lparse-insert-tag "</office:annotation>"))
536 (defun org-odt-begin-environment (style env-options-plist)
537 (case style
538 (annotation
539 (org-lparse-stash-save-paragraph-state)
540 (org-odt-begin-annotation (plist-get env-options-plist 'author)
541 (plist-get env-options-plist 'date)))
542 ((blockquote verse center quote)
543 (org-lparse-begin-paragraph style)
544 (list))
545 ((fixedwidth native)
546 (org-lparse-end-paragraph)
547 (list))
548 (t (error "Unknown environment %s" style))))
550 (defun org-odt-end-environment (style env-options-plist)
551 (case style
552 (annotation
553 (org-lparse-end-paragraph)
554 (org-odt-end-annotation)
555 (org-lparse-stash-pop-paragraph-state))
556 ((blockquote verse center quote)
557 (org-lparse-end-paragraph)
558 (list))
559 ((fixedwidth native)
560 (org-lparse-begin-paragraph)
561 (list))
562 (t (error "Unknown environment %s" style))))
564 (defvar org-lparse-list-level) ; dynamically bound in org-do-lparse
565 (defun org-odt-begin-list (ltype)
566 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
567 ltype))
568 (let* ((style-name (org-odt-get-style-name-for-entity 'list ltype))
569 (extra (concat (when (= org-lparse-list-level 1)
570 " text:continue-numbering=\"false\"")
571 (when style-name
572 (format " text:style-name=\"%s\"" style-name)))))
573 (case ltype
574 ((ordered unordered description)
575 (org-lparse-end-paragraph)
576 (org-lparse-insert-tag "<text:list%s>" extra))
577 (t (error "Unknown list type: %s" ltype)))))
579 (defun org-odt-end-list (ltype)
580 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
581 ltype))
582 (if ltype
583 (org-lparse-insert-tag "</text:list>")
584 (error "Unknown list type: %s" ltype)))
586 (defun org-odt-begin-list-item (ltype &optional arg headline)
587 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
588 ltype))
589 (case ltype
590 (ordered
591 (assert (not headline) t)
592 (let* ((counter arg) (extra ""))
593 (org-lparse-insert-tag "<text:list-item>")
594 (org-lparse-begin-paragraph)))
595 (unordered
596 (let* ((id arg) (extra ""))
597 (org-lparse-insert-tag "<text:list-item>")
598 (org-lparse-begin-paragraph)
599 (insert (if headline (org-odt-format-target headline id)
600 (org-odt-format-bookmark "" id)))))
601 (description
602 (assert (not headline) t)
603 (let ((term (or arg "(no term)")))
604 (insert
605 (org-odt-format-tags
606 '("<text:list-item>" . "</text:list-item>")
607 (org-odt-format-stylized-paragraph 'definition-term term)))
608 (org-lparse-begin-list-item 'unordered)
609 (org-lparse-begin-list 'description)
610 (org-lparse-begin-list-item 'unordered)))
611 (t (error "Unknown list type"))))
613 (defun org-odt-end-list-item (ltype)
614 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
615 ltype))
616 (case ltype
617 ((ordered unordered)
618 (org-lparse-insert-tag "</text:list-item>"))
619 (description
620 (org-lparse-end-list-item-1)
621 (org-lparse-end-list 'description)
622 (org-lparse-end-list-item-1))
623 (t (error "Unknown list type"))))
625 ;; Following variables are let bound when table emission is in
626 ;; progress. See org-lparse.el.
627 (defvar org-lparse-table-begin-marker)
628 (defvar org-lparse-table-ncols)
629 (defvar org-lparse-table-rowgrp-open)
630 (defvar org-lparse-table-rownum)
631 (defvar org-lparse-table-cur-rowgrp-is-hdr)
632 (defvar org-lparse-table-is-styled)
633 (defvar org-lparse-table-rowgrp-info)
634 (defvar org-lparse-table-colalign-vector)
636 (defvar org-odt-table-style nil
637 "Table style specified by \"#+ATTR_ODT: <style-name>\" line.
638 This is set during `org-odt-begin-table'.")
640 (defvar org-odt-table-style-spec nil
641 "Entry for `org-odt-table-style' in `org-export-odt-table-styles'.")
643 (defcustom org-export-odt-table-styles
644 '(("OrgEquation" "OrgEquation"
645 ((use-first-column-styles . t)
646 (use-last-column-styles . t))))
647 "Specify how Table Styles should be derived from a Table Template.
648 This is a list where each element is of the
649 form (TABLE-STYLE-NAME TABLE-TEMPLATE-NAME TABLE-CELL-OPTIONS).
651 TABLE-STYLE-NAME is the style associated with the table through
652 `org-odt-table-style'.
654 TABLE-TEMPLATE-NAME is a set of - upto 9 - automatic
655 TABLE-CELL-STYLE-NAMEs and PARAGRAPH-STYLE-NAMEs (as defined
656 below) that is included in
657 `org-export-odt-content-template-file'.
659 TABLE-CELL-STYLE-NAME := TABLE-TEMPLATE-NAME + TABLE-CELL-TYPE +
660 \"TableCell\"
661 PARAGRAPH-STYLE-NAME := TABLE-TEMPLATE-NAME + TABLE-CELL-TYPE +
662 \"TableParagraph\"
663 TABLE-CELL-TYPE := \"FirstRow\" | \"LastColumn\" |
664 \"FirstRow\" | \"LastRow\" |
665 \"EvenRow\" | \"OddRow\" |
666 \"EvenColumn\" | \"OddColumn\" | \"\"
667 where \"+\" above denotes string concatenation.
669 TABLE-CELL-OPTIONS is an alist where each element is of the
670 form (TABLE-CELL-STYLE-SELECTOR . ON-OR-OFF).
671 TABLE-CELL-STYLE-SELECTOR := `use-first-row-styles' |
672 `use-last-row-styles' |
673 `use-first-column-styles' |
674 `use-last-column-styles' |
675 `use-banding-rows-styles' |
676 `use-banding-columns-styles' |
677 `use-first-row-styles'
678 ON-OR-OFF := `t' | `nil'
680 For example, with the following configuration
682 \(setq org-export-odt-table-styles
683 '\(\(\"TableWithHeaderRowsAndColumns\" \"Custom\"
684 \(\(use-first-row-styles . t\)
685 \(use-first-column-styles . t\)\)\)
686 \(\"TableWithHeaderColumns\" \"Custom\"
687 \(\(use-first-column-styles . t\)\)\)\)\)
689 1. A table associated with \"TableWithHeaderRowsAndColumns\"
690 style will use the following table-cell styles -
691 \"CustomFirstRowTableCell\", \"CustomFirstColumnTableCell\",
692 \"CustomTableCell\" and the following paragraph styles
693 \"CustomFirstRowTableParagraph\",
694 \"CustomFirstColumnTableParagraph\", \"CustomTableParagraph\"
695 as appropriate.
697 2. A table associated with \"TableWithHeaderColumns\" style will
698 use the following table-cell styles -
699 \"CustomFirstColumnTableCell\", \"CustomTableCell\" and the
700 following paragraph styles
701 \"CustomFirstColumnTableParagraph\", \"CustomTableParagraph\"
702 as appropriate..
704 Note that TABLE-TEMPLATE-NAME corresponds to the
705 \"<table:table-template>\" elements contained within
706 \"<office:styles>\". The entries (TABLE-STYLE-NAME
707 TABLE-TEMPLATE-NAME TABLE-CELL-OPTIONS) correspond to
708 \"table:template-name\" and \"table:use-first-row-styles\" etc
709 attributes of \"<table:table>\" element. Refer ODF-1.2
710 specification for more information. Also consult the
711 implementation filed under `org-odt-get-table-cell-styles'.
713 The TABLE-STYLE-NAME \"OrgEquation\" is used internally for
714 formatting of numbered display equations. Do not delete this
715 style from the list."
716 :group 'org-export-odt
717 :type '(choice
718 (const :tag "None" nil)
719 (repeat :tag "Table Styles"
720 (list :tag "Table Style Specification"
721 (string :tag "Table Style Name")
722 (string :tag "Table Template Name")
723 (alist :options (use-first-row-styles
724 use-last-row-styles
725 use-first-column-styles
726 use-last-column-styles
727 use-banding-rows-styles
728 use-banding-columns-styles)
729 :key-type symbol
730 :value-type (const :tag "True" t))))))
732 (defun org-odt-begin-table (caption label attributes)
733 (setq org-odt-table-style attributes)
734 (setq org-odt-table-style-spec
735 (assoc org-odt-table-style org-export-odt-table-styles))
736 (when label
737 (insert
738 (org-odt-format-stylized-paragraph
739 'table (org-odt-format-entity-caption label caption "__Table__"))))
740 (org-lparse-insert-tag
741 "<table:table table:name=\"%s\" table:style-name=\"%s\">"
742 (or label "") (or (nth 1 org-odt-table-style-spec) "OrgTable"))
743 (setq org-lparse-table-begin-marker (point)))
745 (defvar org-lparse-table-colalign-info)
746 (defun org-odt-end-table ()
747 (goto-char org-lparse-table-begin-marker)
748 (loop for level from 0 below org-lparse-table-ncols
749 do (let* ((col-cookie (and org-lparse-table-is-styled
750 (cdr (assoc (1+ level)
751 org-lparse-table-colalign-info))))
752 (extra-columns (or (nth 1 col-cookie) 0)))
753 (dotimes (i (1+ extra-columns))
754 (insert
755 (org-odt-format-tags
756 "<table:table-column table:style-name=\"%sColumn\"/>"
757 "" (or (nth 1 org-odt-table-style-spec) "OrgTable"))))
758 (insert "\n")))
759 ;; fill style attributes for table cells
760 (when org-lparse-table-is-styled
761 (while (re-search-forward "@@\\(table-cell:p\\|table-cell:style-name\\)@@\\([0-9]+\\)@@\\([0-9]+\\)@@" nil t)
762 (let* ((spec (match-string 1))
763 (r (string-to-number (match-string 2)))
764 (c (string-to-number (match-string 3)))
765 (cell-styles (org-odt-get-table-cell-styles
766 r c org-odt-table-style-spec))
767 (table-cell-style (car cell-styles))
768 (table-cell-paragraph-style (cdr cell-styles)))
769 (cond
770 ((equal spec "table-cell:p")
771 (replace-match table-cell-paragraph-style t t))
772 ((equal spec "table-cell:style-name")
773 (replace-match table-cell-style t t))))))
774 (goto-char (point-max))
775 (org-lparse-insert-tag "</table:table>"))
777 (defun org-odt-begin-table-rowgroup (&optional is-header-row)
778 (when org-lparse-table-rowgrp-open
779 (org-lparse-end 'TABLE-ROWGROUP))
780 (org-lparse-insert-tag (if is-header-row
781 "<table:table-header-rows>"
782 "<table:table-rows>"))
783 (setq org-lparse-table-rowgrp-open t)
784 (setq org-lparse-table-cur-rowgrp-is-hdr is-header-row))
786 (defun org-odt-end-table-rowgroup ()
787 (when org-lparse-table-rowgrp-open
788 (setq org-lparse-table-rowgrp-open nil)
789 (org-lparse-insert-tag
790 (if org-lparse-table-cur-rowgrp-is-hdr
791 "</table:table-header-rows>" "</table:table-rows>"))))
793 (defun org-odt-format-table-row (row)
794 (org-odt-format-tags
795 '("<table:table-row>" . "</table:table-row>") row))
797 (defun org-odt-get-table-cell-styles (r c &optional style-spec)
798 "Retrieve styles applicable to a table cell.
799 R and C are (zero-based) row and column numbers of the table
800 cell. STYLE-SPEC is an entry in `org-export-odt-table-styles'
801 applicable to the current table. It is `nil' if the table is not
802 associated with any style attributes.
804 Return a cons of (TABLE-CELL-STYLE-NAME . PARAGRAPH-STYLE-NAME).
806 When STYLE-SPEC is nil, style the table cell the conventional way
807 - choose cell borders based on row and column groupings and
808 choose paragraph alignment based on `org-col-cookies' text
809 property. See also
810 `org-odt-get-paragraph-style-cookie-for-table-cell'.
812 When STYLE-SPEC is non-nil, ignore the above cookie and return
813 styles congruent with the ODF-1.2 specification."
814 (cond
815 (style-spec
817 ;; LibreOffice - particularly the Writer - honors neither table
818 ;; templates nor custom table-cell styles. Inorder to retain
819 ;; inter-operability with LibreOffice, only automatic styles are
820 ;; used for styling of table-cells. The current implementation is
821 ;; congruent with ODF-1.2 specification and hence is
822 ;; future-compatible.
824 ;; Additional Note: LibreOffice's AutoFormat facility for tables -
825 ;; which recognizes as many as 16 different cell types - is much
826 ;; richer. Unfortunately it is NOT amenable to easy configuration
827 ;; by hand.
829 (let* ((template-name (nth 1 style-spec))
830 (cell-style-selectors (nth 2 style-spec))
831 (cell-type
832 (cond
833 ((and (cdr (assoc 'use-first-column-styles cell-style-selectors))
834 (= c 0)) "FirstColumn")
835 ((and (cdr (assoc 'use-last-column-styles cell-style-selectors))
836 (= c (1- org-lparse-table-ncols))) "LastColumn")
837 ((and (cdr (assoc 'use-first-row-styles cell-style-selectors))
838 (= r 0)) "FirstRow")
839 ((and (cdr (assoc 'use-last-row-styles cell-style-selectors))
840 (= r org-lparse-table-rownum))
841 "LastRow")
842 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
843 (= (% r 2) 1)) "EvenRow")
844 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
845 (= (% r 2) 0)) "OddRow")
846 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
847 (= (% c 2) 1)) "EvenColumn")
848 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
849 (= (% c 2) 0)) "OddColumn")
850 (t ""))))
851 (cons
852 (concat template-name cell-type "TableCell")
853 (concat template-name cell-type "TableParagraph"))))
855 (cons
856 (concat
857 "OrgTblCell"
858 (cond
859 ((= r 0) "T")
860 ((eq (cdr (assoc r org-lparse-table-rowgrp-info)) :start) "T")
861 (t ""))
862 (when (= r org-lparse-table-rownum) "B")
863 (cond
864 ((= c 0) "")
865 ((or (memq (nth c org-table-colgroup-info) '(:start :startend))
866 (memq (nth (1- c) org-table-colgroup-info) '(:end :startend))) "L")
867 (t "")))
868 (capitalize (aref org-lparse-table-colalign-vector c))))))
870 (defun org-odt-get-paragraph-style-cookie-for-table-cell (r c)
871 (concat
872 (and (not org-odt-table-style-spec)
873 (cond
874 (org-lparse-table-cur-rowgrp-is-hdr "OrgTableHeading")
875 ((and (= c 0) (org-lparse-get 'TABLE-FIRST-COLUMN-AS-LABELS))
876 "OrgTableHeading")
877 (t "OrgTableContents")))
878 (and org-lparse-table-is-styled
879 (format "@@table-cell:p@@%03d@@%03d@@" r c))))
881 (defun org-odt-get-style-name-cookie-for-table-cell (r c)
882 (when org-lparse-table-is-styled
883 (format "@@table-cell:style-name@@%03d@@%03d@@" r c)))
885 (defun org-odt-format-table-cell (data r c horiz-span)
886 (concat
887 (let* ((paragraph-style-cookie
888 (org-odt-get-paragraph-style-cookie-for-table-cell r c))
889 (style-name-cookie
890 (org-odt-get-style-name-cookie-for-table-cell r c))
891 (extra (and style-name-cookie
892 (format " table:style-name=\"%s\"" style-name-cookie)))
893 (extra (concat extra
894 (and (> horiz-span 0)
895 (format " table:number-columns-spanned=\"%d\""
896 (1+ horiz-span))))))
897 (org-odt-format-tags
898 '("<table:table-cell%s>" . "</table:table-cell>")
899 (if org-lparse-list-table-p data
900 (org-odt-format-stylized-paragraph paragraph-style-cookie data)) extra))
901 (let (s)
902 (dotimes (i horiz-span)
903 (setq s (concat s "\n<table:covered-table-cell/>"))) s)
904 "\n"))
906 (defun org-odt-begin-footnote-definition (n)
907 (org-lparse-begin-paragraph 'footnote))
909 (defun org-odt-end-footnote-definition (n)
910 (org-lparse-end-paragraph))
912 (defun org-odt-begin-toc (lang-specific-heading)
913 (insert
914 (format "
915 <text:table-of-content text:style-name=\"Sect2\" text:protected=\"true\" text:name=\"Table of Contents1\">
916 <text:table-of-content-source text:outline-level=\"10\">
917 <text:index-title-template text:style-name=\"Contents_20_Heading\">%s</text:index-title-template>
918 " lang-specific-heading))
920 (loop for level from 1 upto 10
921 do (insert (format
923 <text:table-of-content-entry-template text:outline-level=\"%d\" text:style-name=\"Contents_20_%d\">
924 <text:index-entry-link-start text:style-name=\"Internet_20_link\"/>
925 <text:index-entry-chapter/>
926 <text:index-entry-text/>
927 <text:index-entry-link-end/>
928 </text:table-of-content-entry-template>
929 " level level)))
931 (insert
932 (format "
933 </text:table-of-content-source>
935 <text:index-body>
936 <text:index-title text:style-name=\"Sect1\" text:name=\"Table of Contents1_Head\">
937 <text:p text:style-name=\"Contents_20_Heading\">%s</text:p>
938 </text:index-title>
939 " lang-specific-heading)))
941 (defun org-odt-end-toc ()
942 (insert "
943 </text:index-body>
944 </text:table-of-content>
947 (defun org-odt-format-toc-entry (snumber todo headline tags href)
948 (setq headline (concat
949 (and org-export-with-section-numbers
950 (concat snumber ". "))
951 headline
952 (and tags
953 (concat
954 (org-lparse-format 'SPACES 3)
955 (org-lparse-format 'FONTIFY tags "tag")))))
956 (when todo
957 (setq headline (org-lparse-format 'FONTIFY headline "todo")))
959 (let ((org-odt-suppress-xref t))
960 (org-odt-format-link headline (concat "#" href))))
962 (defun org-odt-format-toc-item (toc-entry level org-last-level)
963 (let ((style (format "Contents_20_%d"
964 (+ level (or (org-lparse-get 'TOPLEVEL-HLEVEL) 1) -1))))
965 (insert "\n" (org-odt-format-stylized-paragraph style toc-entry) "\n")))
967 ;; Following variable is let bound during 'ORG-LINK callback. See
968 ;; org-html.el
969 (defvar org-lparse-link-description-is-image nil)
970 (defun org-odt-format-link (desc href &optional attr)
971 (cond
972 ((and (= (string-to-char href) ?#) (not org-odt-suppress-xref))
973 (setq href (concat org-export-odt-bookmark-prefix (substring href 1)))
974 (let ((xref-format "text"))
975 (when (numberp desc)
976 (setq desc (format "%d" desc) xref-format "number"))
977 (org-odt-format-tags
978 '("<text:bookmark-ref text:reference-format=\"%s\" text:ref-name=\"%s\">" .
979 "</text:bookmark-ref>")
980 desc xref-format href)))
981 (org-lparse-link-description-is-image
982 (org-odt-format-tags
983 '("<draw:a xlink:type=\"simple\" xlink:href=\"%s\" %s>" . "</draw:a>")
984 desc href (or attr "")))
986 (org-odt-format-tags
987 '("<text:a xlink:type=\"simple\" xlink:href=\"%s\" %s>" . "</text:a>")
988 desc href (or attr "")))))
990 (defun org-odt-format-spaces (n)
991 (cond
992 ((= n 1) " ")
993 ((> n 1) (concat
994 " " (org-odt-format-tags "<text:s text:c=\"%d\"/>" "" (1- n))))
995 (t "")))
997 (defun org-odt-format-tabs (&optional n)
998 (let ((tab "<text:tab/>")
999 (n (or n 1)))
1000 (insert tab)))
1002 (defun org-odt-format-line-break ()
1003 (org-odt-format-tags "<text:line-break/>" ""))
1005 (defun org-odt-format-horizontal-line ()
1006 (org-odt-format-stylized-paragraph 'horizontal-line ""))
1008 (defun org-odt-encode-plain-text (line &optional no-whitespace-filling)
1009 (setq line (org-xml-encode-plain-text line))
1010 (if no-whitespace-filling line
1011 (org-odt-fill-tabs-and-spaces line)))
1013 (defun org-odt-format-line (line)
1014 (case org-lparse-dyn-current-environment
1015 (fixedwidth (concat
1016 (org-odt-format-stylized-paragraph
1017 'fixedwidth (org-odt-encode-plain-text line)) "\n"))
1018 (t (concat line "\n"))))
1020 (defun org-odt-format-comment (fmt &rest args)
1021 (let ((comment (apply 'format fmt args)))
1022 (format "\n<!-- %s -->\n" comment)))
1024 (defun org-odt-format-org-entity (wd)
1025 (org-entity-get-representation wd 'utf8))
1027 (defun org-odt-fill-tabs-and-spaces (line)
1028 (replace-regexp-in-string
1029 "\\([\t]\\|\\([ ]+\\)\\)" (lambda (s)
1030 (cond
1031 ((string= s "\t") (org-odt-format-tabs))
1032 (t (org-odt-format-spaces (length s))))) line))
1034 (defcustom org-export-odt-fontify-srcblocks t
1035 "Specify whether or not source blocks need to be fontified.
1036 Turn this option on if you want to colorize the source code
1037 blocks in the exported file. For colorization to work, you need
1038 to make available an enhanced version of `htmlfontify' library."
1039 :type 'boolean
1040 :group 'org-export-odt)
1042 (defun org-odt-format-source-line-with-line-number-and-label
1043 (line rpllbl num fontifier par-style)
1045 (let ((keep-label (not (numberp rpllbl)))
1046 (ref (org-find-text-property-in-string 'org-coderef line)))
1047 (setq line (concat line (and keep-label ref (format "(%s)" ref))))
1048 (setq line (funcall fontifier line))
1049 (when ref
1050 (setq line (org-odt-format-target line (concat "coderef-" ref))))
1051 (setq line (org-odt-format-stylized-paragraph par-style line))
1052 (if (not num) line
1053 (org-odt-format-tags '("<text:list-item>" . "</text:list-item>") line))))
1055 (defun org-odt-format-source-code-or-example-plain
1056 (lines lang caption textareap cols rows num cont rpllbl fmt)
1057 "Format source or example blocks much like fixedwidth blocks.
1058 Use this when `org-export-odt-fontify-srcblocks' option is turned
1059 off."
1060 (let* ((lines (org-split-string lines "[\r\n]"))
1061 (line-count (length lines))
1062 (i 0))
1063 (mapconcat
1064 (lambda (line)
1065 (incf i)
1066 (org-odt-format-source-line-with-line-number-and-label
1067 line rpllbl num 'org-odt-encode-plain-text
1068 (if (= i line-count) "OrgFixedWidthBlockLastLine"
1069 "OrgFixedWidthBlock")))
1070 lines "\n")))
1072 (defvar org-src-block-paragraph-format
1073 "<style:style style:name=\"OrgSrcBlock\" style:family=\"paragraph\" style:parent-style-name=\"Preformatted_20_Text\">
1074 <style:paragraph-properties fo:background-color=\"%s\" fo:padding=\"0.049cm\" fo:border=\"0.51pt solid #000000\" style:shadow=\"none\">
1075 <style:background-image/>
1076 </style:paragraph-properties>
1077 <style:text-properties fo:color=\"%s\"/>
1078 </style:style>"
1079 "Custom paragraph style for colorized source and example blocks.
1080 This style is much the same as that of \"OrgFixedWidthBlock\"
1081 except that the foreground and background colors are set
1082 according to the default face identified by the `htmlfontify'.")
1084 (defun org-odt-hfy-face-to-css (fn)
1085 "Create custom style for face FN.
1086 When FN is the default face, use it's foreground and background
1087 properties to create \"OrgSrcBlock\" paragraph style. Otherwise
1088 use it's color attribute to create a character style whose name
1089 is obtained from FN. Currently all attributes of FN other than
1090 color are ignored.
1092 The style name for a face FN is derived using the following
1093 operations on the face name in that order - de-dash, CamelCase
1094 and prefix with \"OrgSrc\". For example,
1095 `font-lock-function-name-face' is associated with
1096 \"OrgSrcFontLockFunctionNameFace\"."
1097 (let* ((css-list (hfy-face-to-style fn))
1098 (style-name ((lambda (fn)
1099 (concat "OrgSrc"
1100 (mapconcat
1101 'capitalize (split-string
1102 (hfy-face-or-def-to-name fn) "-")
1103 ""))) fn))
1104 (color-val (cdr (assoc "color" css-list)))
1105 (background-color-val (cdr (assoc "background" css-list)))
1106 (style (and org-export-odt-create-custom-styles-for-srcblocks
1107 (cond
1108 ((eq fn 'default)
1109 (format org-src-block-paragraph-format
1110 background-color-val color-val))
1112 (format
1114 <style:style style:name=\"%s\" style:family=\"text\">
1115 <style:text-properties fo:color=\"%s\"/>
1116 </style:style>" style-name color-val))))))
1117 (cons style-name style)))
1119 (defcustom org-export-odt-create-custom-styles-for-srcblocks t
1120 "Whether custom styles for colorized source blocks be automatically created.
1121 When this option is turned on, the exporter creates custom styles
1122 for source blocks based on the advice of `htmlfontify'. Creation
1123 of custom styles happen as part of `org-odt-hfy-face-to-css'.
1125 When this option is turned off exporter does not create such
1126 styles.
1128 Use the latter option if you do not want the custom styles to be
1129 based on your current display settings. It is necessary that the
1130 styles.xml already contains needed styles for colorizing to work.
1132 This variable is effective only if
1133 `org-export-odt-fontify-srcblocks' is turned on."
1134 :group 'org-export-odt
1135 :type 'boolean)
1137 (defun org-odt-insert-custom-styles-for-srcblocks (styles)
1138 "Save STYLES used for colorizing of source blocks.
1139 Update styles.xml with styles that were collected as part of
1140 `org-odt-hfy-face-to-css' callbacks."
1141 (when styles
1142 (with-current-buffer
1143 (find-file-noselect (expand-file-name "styles.xml") t)
1144 (goto-char (point-min))
1145 (when (re-search-forward "</office:styles>" nil t)
1146 (goto-char (match-beginning 0))
1147 (insert "\n<!-- Org Htmlfontify Styles -->\n" styles "\n")))))
1149 (defun org-odt-format-source-code-or-example-colored
1150 (lines lang caption textareap cols rows num cont rpllbl fmt)
1151 "Format source or example blocks using `htmlfontify-string'.
1152 Use this routine when `org-export-odt-fontify-srcblocks' option
1153 is turned on."
1154 (let* ((lang-m (and lang (or (cdr (assoc lang org-src-lang-modes)) lang)))
1155 (mode (and lang-m (intern (concat (if (symbolp lang-m)
1156 (symbol-name lang-m)
1157 lang-m) "-mode"))))
1158 (org-inhibit-startup t)
1159 (org-startup-folded nil)
1160 (lines (with-temp-buffer
1161 (insert lines)
1162 (if (functionp mode) (funcall mode) (fundamental-mode))
1163 (font-lock-fontify-buffer)
1164 (buffer-string)))
1165 (hfy-html-quote-regex "\\([<\"&> ]\\)")
1166 (hfy-html-quote-map '(("\"" "&quot;")
1167 ("<" "&lt;")
1168 ("&" "&amp;")
1169 (">" "&gt;")
1170 (" " "<text:s/>")
1171 (" " "<text:tab/>")))
1172 (hfy-face-to-css 'org-odt-hfy-face-to-css)
1173 (hfy-optimisations-1 (copy-seq hfy-optimisations))
1174 (hfy-optimisations (add-to-list 'hfy-optimisations-1
1175 'body-text-only))
1176 (hfy-begin-span-handler
1177 (lambda (style text-block text-id text-begins-block-p)
1178 (insert (format "<text:span text:style-name=\"%s\">" style))))
1179 (hfy-end-span-handler (lambda nil (insert "</text:span>"))))
1180 (when (fboundp 'htmlfontify-string)
1181 (let* ((lines (org-split-string lines "[\r\n]"))
1182 (line-count (length lines))
1183 (i 0))
1184 (mapconcat
1185 (lambda (line)
1186 (incf i)
1187 (org-odt-format-source-line-with-line-number-and-label
1188 line rpllbl num 'htmlfontify-string
1189 (if (= i line-count) "OrgSrcBlockLastLine" "OrgSrcBlock")))
1190 lines "\n")))))
1192 (defun org-odt-format-source-code-or-example (lines lang caption textareap
1193 cols rows num cont
1194 rpllbl fmt)
1195 "Format source or example blocks for export.
1196 Use `org-odt-format-source-code-or-example-plain' or
1197 `org-odt-format-source-code-or-example-colored' depending on the
1198 value of `org-export-odt-fontify-srcblocks."
1199 (setq lines (org-export-number-lines
1200 lines 0 0 num cont rpllbl fmt 'preprocess)
1201 lines (funcall
1202 (or (and org-export-odt-fontify-srcblocks
1203 (or (featurep 'htmlfontify)
1204 (require 'htmlfontify))
1205 (fboundp 'htmlfontify-string)
1206 'org-odt-format-source-code-or-example-colored)
1207 'org-odt-format-source-code-or-example-plain)
1208 lines lang caption textareap cols rows num cont rpllbl fmt))
1209 (if (not num) lines
1210 (let ((extra (format " text:continue-numbering=\"%s\""
1211 (if cont "true" "false"))))
1212 (org-odt-format-tags
1213 '("<text:list text:style-name=\"OrgSrcBlockNumberedLine\"%s>"
1214 . "</text:list>") lines extra))))
1216 (defun org-odt-remap-stylenames (style-name)
1218 (cdr (assoc style-name '(("timestamp-wrapper" . "OrgTimestampWrapper")
1219 ("timestamp" . "OrgTimestamp")
1220 ("timestamp-kwd" . "OrgTimestampKeyword")
1221 ("tag" . "OrgTag")
1222 ("todo" . "OrgTodo")
1223 ("done" . "OrgDone")
1224 ("target" . "OrgTarget"))))
1225 style-name))
1227 (defun org-odt-format-fontify (text style &optional id)
1228 (let* ((style-name
1229 (cond
1230 ((stringp style)
1231 (org-odt-remap-stylenames style))
1232 ((symbolp style)
1233 (org-odt-get-style-name-for-entity 'character style))
1234 ((listp style)
1235 (assert (< 1 (length style)))
1236 (let ((parent-style (pop style)))
1237 (mapconcat (lambda (s)
1238 ;; (assert (stringp s) t)
1239 (org-odt-remap-stylenames s)) style "")
1240 (org-odt-remap-stylenames parent-style)))
1241 (t (error "Don't how to handle style %s" style)))))
1242 (org-odt-format-tags
1243 '("<text:span text:style-name=\"%s\">" . "</text:span>")
1244 text style-name)))
1246 (defun org-odt-relocate-relative-path (path dir)
1247 (if (file-name-absolute-p path) path
1248 (file-relative-name (expand-file-name path dir)
1249 (expand-file-name "eyecandy" dir))))
1251 (defun org-odt-format-inline-image (thefile)
1252 (let* ((thelink (if (file-name-absolute-p thefile) thefile
1253 (org-xml-format-href
1254 (org-odt-relocate-relative-path
1255 thefile org-current-export-file))))
1256 (href
1257 (org-odt-format-tags
1258 "<draw:image xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>" ""
1259 (if org-export-odt-embed-images
1260 (org-odt-copy-image-file thefile) thelink))))
1261 (org-export-odt-format-image thefile href)))
1263 (defun org-export-odt-format-formula (src href &optional embed-as)
1264 "Create image tag with source and attributes."
1265 (save-match-data
1266 (let* ((caption (org-find-text-property-in-string 'org-caption src))
1267 (caption (and caption (org-xml-format-desc caption)))
1268 (label (org-find-text-property-in-string 'org-label src))
1269 (latex-frag (org-find-text-property-in-string 'org-latex-src src))
1270 (embed-as (or embed-as
1271 (and latex-frag
1272 (org-find-text-property-in-string
1273 'org-latex-src-embed-type src))
1274 (if (or caption label) 'paragraph 'character)))
1275 width height)
1276 (when latex-frag
1277 (setq href (org-propertize href :title "LaTeX Fragment"
1278 :description latex-frag)))
1279 (cond
1280 ((eq embed-as 'character)
1281 (org-odt-format-entity "InlineFormula" href width height))
1283 (org-lparse-end-paragraph)
1284 (org-lparse-insert-list-table
1285 `((,(org-odt-format-entity
1286 (if caption "CaptionedDisplayFormula" "DisplayFormula")
1287 href width height caption nil)
1288 ,(if (not label) ""
1289 (org-odt-format-entity-caption label nil "__MathFormula__"))))
1290 nil nil nil "OrgEquation" nil '((1 "c" 8) (2 "c" 1)))
1291 (throw 'nextline nil))))))
1293 (defvar org-odt-embedded-formulas-count 0)
1294 (defun org-odt-copy-formula-file (path)
1295 "Returns the internal name of the file"
1296 (let* ((src-file (expand-file-name
1297 path (file-name-directory org-current-export-file)))
1298 (target-dir (format "Formula-%04d/"
1299 (incf org-odt-embedded-formulas-count)))
1300 (target-file (concat target-dir "content.xml")))
1301 (when (not org-lparse-to-buffer)
1302 (message "Embedding %s as %s ..."
1303 (substring-no-properties path) target-file)
1305 (make-directory target-dir)
1306 (org-odt-create-manifest-file-entry
1307 "application/vnd.oasis.opendocument.formula" target-dir "1.2")
1309 (case (org-odt-is-formula-link-p src-file)
1310 (mathml
1311 (copy-file src-file target-file 'overwrite))
1312 (odf
1313 (org-odt-zip-extract-one src-file "content.xml" target-dir))
1315 (error "%s is not a formula file" src-file)))
1317 (org-odt-create-manifest-file-entry "text/xml" target-file))
1318 target-file))
1320 (defun org-odt-format-inline-formula (thefile)
1321 (let* ((thelink (if (file-name-absolute-p thefile) thefile
1322 (org-xml-format-href
1323 (org-odt-relocate-relative-path
1324 thefile org-current-export-file))))
1325 (href
1326 (org-odt-format-tags
1327 "<draw:object xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>" ""
1328 (file-name-directory (org-odt-copy-formula-file thefile)))))
1329 (org-export-odt-format-formula thefile href)))
1331 (defun org-odt-is-formula-link-p (file)
1332 (let ((case-fold-search nil))
1333 (cond
1334 ((string-match "\\.\\(mathml\\|mml\\)\\'" file)
1335 'mathml)
1336 ((string-match "\\.odf\\'" file)
1337 'odf))))
1339 (defun org-odt-format-org-link (opt-plist type-1 path fragment desc attr
1340 descp)
1341 "Make an HTML link.
1342 OPT-PLIST is an options list.
1343 TYPE is the device-type of the link (THIS://foo.html)
1344 PATH is the path of the link (http://THIS#locationx)
1345 FRAGMENT is the fragment part of the link, if any (foo.html#THIS)
1346 DESC is the link description, if any.
1347 ATTR is a string of other attributes of the a element.
1348 MAY-INLINE-P allows inlining it as an image."
1349 (declare (special org-lparse-par-open))
1350 (save-match-data
1351 (let* ((may-inline-p
1352 (and (member type-1 '("http" "https" "file"))
1353 (org-lparse-should-inline-p path descp)
1354 (not fragment)))
1355 (type (if (equal type-1 "id") "file" type-1))
1356 (filename path)
1357 (thefile path))
1358 (cond
1359 ;; check for inlined images
1360 ((and (member type '("file"))
1361 (not fragment)
1362 (org-file-image-p
1363 filename org-export-odt-inline-image-extensions)
1364 (or (eq t org-export-odt-inline-images)
1365 (and org-export-odt-inline-images (not descp))))
1366 (org-odt-format-inline-image thefile))
1367 ;; check for embedded formulas
1368 ((and (member type '("file"))
1369 (not fragment)
1370 (org-odt-is-formula-link-p filename)
1371 (or (not descp)))
1372 (org-odt-format-inline-formula thefile))
1373 ((string= type "coderef")
1374 (let* ((ref fragment)
1375 (lineno-or-ref (cdr (assoc ref org-export-code-refs)))
1376 (desc (and descp desc))
1377 (org-odt-suppress-xref nil)
1378 (href (org-xml-format-href (concat "#coderef-" ref))))
1379 (cond
1380 ((and (numberp lineno-or-ref) (not desc))
1381 (org-odt-format-link lineno-or-ref href))
1382 ((and (numberp lineno-or-ref) desc
1383 (string-match (regexp-quote (concat "(" ref ")")) desc))
1384 (format (replace-match "%s" t t desc)
1385 (org-odt-format-link lineno-or-ref href)))
1387 (setq desc (format
1388 (if (and desc (string-match
1389 (regexp-quote (concat "(" ref ")"))
1390 desc))
1391 (replace-match "%s" t t desc)
1392 (or desc "%s"))
1393 lineno-or-ref))
1394 (org-odt-format-link (org-xml-format-desc desc) href)))))
1396 (when (string= type "file")
1397 (setq thefile
1398 (cond
1399 ((file-name-absolute-p path)
1400 (concat "file://" (expand-file-name path)))
1401 (t (org-odt-relocate-relative-path
1402 thefile org-current-export-file)))))
1404 (when (and (member type '("" "http" "https" "file")) fragment)
1405 (setq thefile (concat thefile "#" fragment)))
1407 (setq thefile (org-xml-format-href thefile))
1409 (when (not (member type '("" "file")))
1410 (setq thefile (concat type ":" thefile)))
1412 (let ((org-odt-suppress-xref nil))
1413 (org-odt-format-link
1414 (org-xml-format-desc desc) thefile attr)))))))
1416 (defun org-odt-format-heading (text level &optional id)
1417 (let* ((text (if id (org-odt-format-target text id) text)))
1418 (org-odt-format-tags
1419 '("<text:h text:style-name=\"Heading_20_%s\" text:outline-level=\"%s\">" .
1420 "</text:h>") text level level)))
1422 (defun org-odt-format-headline (title extra-targets tags
1423 &optional snumber level)
1424 (concat
1425 (org-lparse-format 'EXTRA-TARGETS extra-targets)
1427 ;; No need to generate section numbers. They are auto-generated by
1428 ;; the application
1430 ;; (concat (org-lparse-format 'SECTION-NUMBER snumber level) " ")
1431 title
1432 (and tags (concat (org-lparse-format 'SPACES 3)
1433 (org-lparse-format 'ORG-TAGS tags)))))
1435 (defun org-odt-format-anchor (text name &optional class)
1436 (org-odt-format-target text name))
1438 (defun org-odt-format-bookmark (text id)
1439 (if id
1440 (org-odt-format-tags "<text:bookmark text:name=\"%s\"/>" text id)
1441 text))
1443 (defun org-odt-format-target (text id)
1444 (let ((name (concat org-export-odt-bookmark-prefix id)))
1445 (concat
1446 (and id (org-odt-format-tags
1447 "<text:bookmark-start text:name=\"%s\"/>" "" name))
1448 (org-odt-format-bookmark text id)
1449 (and id (org-odt-format-tags
1450 "<text:bookmark-end text:name=\"%s\"/>" "" name)))))
1452 (defun org-odt-format-footnote (n def)
1453 (let ((id (concat "fn" n))
1454 (note-class "footnote")
1455 (par-style "Footnote"))
1456 (org-odt-format-tags
1457 '("<text:note text:id=\"%s\" text:note-class=\"%s\">" .
1458 "</text:note>")
1459 (concat
1460 (org-odt-format-tags
1461 '("<text:note-citation>" . "</text:note-citation>")
1463 (org-odt-format-tags
1464 '("<text:note-body>" . "</text:note-body>")
1465 def))
1466 id note-class)))
1468 (defun org-odt-format-footnote-reference (n def refcnt)
1469 (if (= refcnt 1)
1470 (org-odt-format-footnote n def)
1471 (org-odt-format-footnote-ref n)))
1473 (defun org-odt-format-footnote-ref (n)
1474 (let ((note-class "footnote")
1475 (ref-format "text")
1476 (ref-name (concat "fn" n)))
1477 (org-odt-format-tags
1478 '("<text:span text:style-name=\"%s\">" . "</text:span>")
1479 (org-odt-format-tags
1480 '("<text:note-ref text:note-class=\"%s\" text:reference-format=\"%s\" text:ref-name=\"%s\">" . "</text:note-ref>")
1481 n note-class ref-format ref-name)
1482 "OrgSuperscript")))
1484 (defun org-odt-get-image-name (file-name)
1485 (require 'sha1)
1486 (file-relative-name
1487 (expand-file-name
1488 (concat (sha1 file-name) "." (file-name-extension file-name)) "Pictures")))
1490 (defun org-export-odt-format-image (src href &optional embed-as)
1491 "Create image tag with source and attributes."
1492 (save-match-data
1493 (let* ((caption (org-find-text-property-in-string 'org-caption src))
1494 (caption (and caption (org-xml-format-desc caption)))
1495 (attr (org-find-text-property-in-string 'org-attributes src))
1496 (label (org-find-text-property-in-string 'org-label src))
1497 (latex-frag (org-find-text-property-in-string
1498 'org-latex-src src))
1499 (category (and latex-frag "__DvipngImage__"))
1500 (embed-as (or embed-as
1501 (if latex-frag
1502 (or (org-find-text-property-in-string
1503 'org-latex-src-embed-type src) 'character)
1504 'paragraph)))
1505 (attr-plist (org-lparse-get-block-params attr))
1506 (size (org-odt-image-size-from-file
1507 src (plist-get attr-plist :width)
1508 (plist-get attr-plist :height)
1509 (plist-get attr-plist :scale) nil embed-as))
1510 (width (car size)) (height (cdr size)))
1511 (when latex-frag
1512 (setq href (org-propertize href :title "LaTeX Fragment"
1513 :description latex-frag)))
1514 (cond
1515 ((not (or caption label))
1516 (case embed-as
1517 (paragraph (org-odt-format-entity "DisplayImage" href width height))
1518 (character (org-odt-format-entity "InlineImage" href width height))
1519 (t (error "Unknown value for embed-as %S" embed-as))))
1521 (org-odt-format-entity
1522 "CaptionedDisplayImage" href width height caption label category))))))
1524 (defun org-odt-format-object-description (title description)
1525 (concat (and title (org-odt-format-tags
1526 '("<svg:title>" . "</svg:title>")
1527 (org-odt-encode-plain-text title t)))
1528 (and description (org-odt-format-tags
1529 '("<svg:desc>" . "</svg:desc>")
1530 (org-odt-encode-plain-text description t)))))
1532 (defun org-odt-format-frame (text width height style &optional
1533 extra anchor-type)
1534 (let ((frame-attrs
1535 (concat
1536 (if width (format " svg:width=\"%0.2fcm\"" width) "")
1537 (if height (format " svg:height=\"%0.2fcm\"" height) "")
1538 extra
1539 (format " text:anchor-type=\"%s\"" (or anchor-type "paragraph")))))
1540 (org-odt-format-tags
1541 '("<draw:frame draw:style-name=\"%s\"%s>" . "</draw:frame>")
1542 (concat text (org-odt-format-object-description
1543 (get-text-property 0 :title text)
1544 (get-text-property 0 :description text)))
1545 style frame-attrs)))
1547 (defun org-odt-format-textbox (text width height style &optional
1548 extra anchor-type)
1549 (org-odt-format-frame
1550 (org-odt-format-tags
1551 '("<draw:text-box %s>" . "</draw:text-box>")
1552 text (concat (format " fo:min-height=\"%0.2fcm\"" (or height .2))
1553 (format " fo:min-width=\"%0.2fcm\"" (or width .2))))
1554 width nil style extra anchor-type))
1556 (defun org-odt-format-inlinetask (heading content
1557 &optional todo priority tags)
1558 (org-odt-format-stylized-paragraph
1559 nil (org-odt-format-textbox
1560 (concat (org-odt-format-stylized-paragraph
1561 "OrgInlineTaskHeading"
1562 (org-lparse-format
1563 'HEADLINE (concat (org-lparse-format-todo todo) " " heading)
1564 nil tags))
1565 content) nil nil "OrgInlineTaskFrame" " style:rel-width=\"100%\"")))
1567 (defvar org-odt-entity-frame-styles
1568 '(("InlineImage" "__Figure__" ("OrgInlineImage" nil "as-char"))
1569 ("DisplayImage" "__Figure__" ("OrgDisplayImage" nil "paragraph"))
1570 ("CaptionedDisplayImage" "__Figure__"
1571 ("OrgCaptionedImage"
1572 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
1573 ("OrgImageCaptionFrame"))
1574 ("InlineFormula" "__MathFormula__" ("OrgInlineFormula" nil "as-char"))
1575 ("DisplayFormula" "__MathFormula__" ("OrgDisplayFormula" nil "as-char"))
1576 ("CaptionedDisplayFormula" "__MathFormula__"
1577 ("OrgCaptionedFormula" nil "paragraph")
1578 ("OrgFormulaCaptionFrame" nil "as-char"))))
1580 (defun org-odt-format-entity (entity href width height
1581 &optional caption label category)
1582 (let* ((entity-style (assoc entity org-odt-entity-frame-styles))
1583 (entity-frame (apply 'org-odt-format-frame
1584 href width height (nth 2 entity-style))))
1585 (if (not (or caption label)) entity-frame
1586 (apply 'org-odt-format-textbox
1587 (org-odt-format-stylized-paragraph
1588 'illustration
1589 (concat entity-frame
1590 (org-odt-format-entity-caption
1591 label caption (or category (nth 1 entity-style)))))
1592 width height (nth 3 entity-style)))))
1594 (defvar org-odt-embedded-images-count 0)
1595 (defun org-odt-copy-image-file (path)
1596 "Returns the internal name of the file"
1597 (let* ((image-type (file-name-extension path))
1598 (media-type (format "image/%s" image-type))
1599 (src-file (expand-file-name
1600 path (file-name-directory org-current-export-file)))
1601 (target-dir "Images/")
1602 (target-file
1603 (format "%s%04d.%s" target-dir
1604 (incf org-odt-embedded-images-count) image-type)))
1605 (when (not org-lparse-to-buffer)
1606 (message "Embedding %s as %s ..."
1607 (substring-no-properties path) target-file)
1609 (when (= 1 org-odt-embedded-images-count)
1610 (make-directory target-dir)
1611 (org-odt-create-manifest-file-entry "" target-dir))
1613 (copy-file src-file target-file 'overwrite)
1614 (org-odt-create-manifest-file-entry media-type target-file))
1615 target-file))
1617 (defvar org-export-odt-image-size-probe-method
1618 '(emacs imagemagick force)
1619 "Ordered list of methods by for determining size of an embedded
1620 image.")
1622 (defvar org-export-odt-default-image-sizes-alist
1623 '(("character" . (5 . 0.4))
1624 ("paragraph" . (5 . 5)))
1625 "Hardcoded image dimensions one for each of the anchor
1626 methods.")
1628 (defun org-odt-do-image-size (probe-method file &optional dpi anchor-type)
1629 (setq dpi (or dpi org-export-odt-pixels-per-inch))
1630 (setq anchor-type (or anchor-type "paragraph"))
1631 (flet ((size-in-cms (size-in-pixels)
1632 (flet ((pixels-to-cms (pixels)
1633 (let* ((cms-per-inch 2.54)
1634 (inches (/ pixels dpi)))
1635 (* cms-per-inch inches))))
1636 (and size-in-pixels
1637 (cons (pixels-to-cms (car size-in-pixels))
1638 (pixels-to-cms (cdr size-in-pixels)))))))
1639 (case probe-method
1640 (emacs
1641 (size-in-cms (ignore-errors (image-size (create-image file) 'pixels))))
1642 (imagemagick
1643 (size-in-cms
1644 (let ((dim (shell-command-to-string
1645 (format "identify -format \"%%w:%%h\" \"%s\"" file))))
1646 (when (string-match "\\([0-9]+\\):\\([0-9]+\\)" dim)
1647 (cons (string-to-number (match-string 1 dim))
1648 (string-to-number (match-string 2 dim)))))))
1650 (cdr (assoc-string anchor-type
1651 org-export-odt-default-image-sizes-alist))))))
1653 (defun org-odt-image-size-from-file (file &optional user-width
1654 user-height scale dpi embed-as)
1655 (unless (file-name-absolute-p file)
1656 (setq file (expand-file-name
1657 file (file-name-directory org-current-export-file))))
1658 (let* (size width height)
1659 (unless (and user-height user-width)
1660 (loop for probe-method in org-export-odt-image-size-probe-method
1661 until size
1662 do (setq size (org-odt-do-image-size
1663 probe-method file dpi embed-as)))
1664 (or size (error "Cannot determine Image size. Aborting ..."))
1665 (setq width (car size) height (cdr size)))
1666 (cond
1667 (scale
1668 (setq width (* width scale) height (* height scale)))
1669 ((and user-height user-width)
1670 (setq width user-width height user-height))
1671 (user-height
1672 (setq width (* user-height (/ width height)) height user-height))
1673 (user-width
1674 (setq height (* user-width (/ height width)) width user-width))
1675 (t (ignore)))
1676 (cons width height)))
1678 (defvar org-odt-entity-labels-alist nil
1679 "Associate Labels with the Labelled entities.
1680 Each element of the alist is of the form (LABEL-NAME
1681 CATEGORY-NAME SEQNO LABEL-STYLE-NAME). LABEL-NAME is same as
1682 that specified by \"#+LABEL: ...\" line. CATEGORY-NAME is the
1683 type of the entity that LABEL-NAME is attached to. CATEGORY-NAME
1684 can be one of \"Table\", \"Figure\" or \"Equation\". SEQNO is
1685 the unique number assigned to the referenced entity on a
1686 per-CATEGORY basis. It is generated sequentially and is 1-based.
1687 LABEL-STYLE-NAME is a key `org-odt-label-styles'.
1689 See `org-odt-add-label-definition' and
1690 `org-odt-fixup-label-references'.")
1692 (defvar org-odt-entity-counts-plist nil
1693 "Plist of running counters of SEQNOs for each of the CATEGORY-NAMEs.
1694 See `org-odt-entity-labels-alist' for known CATEGORY-NAMEs.")
1696 (defvar org-odt-label-styles
1697 '(("text" "(%n)" "text" "(%n)")
1698 ("category-and-value" "%e %n%c" "category-and-value" "%e %n"))
1699 "Specify how labels are applied and referenced.
1700 This is an alist where each element is of the
1701 form (LABEL-STYLE-NAME LABEL-ATTACH-FMT LABEL-REF-MODE
1702 LABEL-REF-FMT).
1704 LABEL-ATTACH-FMT controls how labels and captions are attached to
1705 an entity. It may contain following specifiers - %e, %n and %c.
1706 %e is replaced with the CATEGORY-NAME. %n is replaced with
1707 \"<text:sequence ...> SEQNO </text:sequence>\". %c is replaced
1708 with CAPTION. See `org-odt-format-label-definition'.
1710 LABEL-REF-MODE and LABEL-REF-FMT controls how label references
1711 are generated. The following XML is generated for a label
1712 reference - \"<text:sequence-ref
1713 text:reference-format=\"LABEL-REF-MODE\" ...> LABEL-REF-FMT
1714 </text:sequence-ref>\". LABEL-REF-FMT may contain following
1715 specifiers - %e and %n. %e is replaced with the CATEGORY-NAME.
1716 %n is replaced with SEQNO. See
1717 `org-odt-format-label-reference'.")
1719 (defvar org-odt-category-map-alist
1720 '(("__Table__" "Table" "category-and-value")
1721 ("__Figure__" "Figure" "category-and-value")
1722 ("__MathFormula__" "Equation" "text")
1723 ("__DvipngImage__" "Equation" "category-and-value"))
1724 "Map a CATEGORY-HANDLE to CATEGORY-NAME and LABEL-STYLE.
1725 This is an alist where each element is of the form
1726 \\(CATEGORY-HANDLE CATEGORY-NAME LABEL-STYLE\\). CATEGORY_HANDLE
1727 could either be one of the internal handles (as seen above) or be
1728 derived from the \"#+LABEL:<label-name>\" specification. See
1729 `org-export-odt-get-category-from-label'. CATEGORY-NAME and
1730 LABEL-STYLE are used for generating ODT labels. See
1731 `org-odt-label-styles'.")
1733 (defvar org-export-odt-user-categories
1734 '("Illustration" "Table" "Text" "Drawing" "Equation" "Figure"))
1736 (defvar org-export-odt-get-category-from-label nil
1737 "Should category of label be inferred from label itself.
1738 When this option is non-nil, a label is parsed in to two
1739 component parts delimited by a \":\" (colon) as shown here -
1740 #+LABEL:[CATEGORY-HANDLE:]EXTRA. The CATEGORY-HANDLE is mapped
1741 to a CATEGORY-NAME and LABEL-STYLE using
1742 `org-odt-category-map-alist'. (If no such map is provided and
1743 CATEGORY-NAME is set to CATEGORY-HANDLE and LABEL-STYLE is set to
1744 \"category-and-value\"). If CATEGORY-NAME so obtained is listed
1745 under `org-export-odt-user-categories' then the user specified
1746 styles are used. Otherwise styles as determined by the internal
1747 CATEGORY-HANDLE is used. See
1748 `org-odt-get-label-category-and-style' for details.")
1750 (defun org-odt-get-label-category-and-style (label default-category)
1751 "See `org-export-odt-get-category-from-label'."
1752 (let ((default-category-map
1753 (assoc default-category org-odt-category-map-alist))
1754 user-category user-category-map category)
1755 (cond
1756 ((not org-export-odt-get-category-from-label)
1757 default-category-map)
1758 ((not (setq user-category
1759 (save-match-data
1760 (and (string-match "\\`\\(.*\\):.+" label)
1761 (match-string 1 label)))))
1762 default-category-map)
1764 (setq user-category-map
1765 (or (assoc user-category org-odt-category-map-alist)
1766 (list nil user-category "category-and-value"))
1767 category (nth 1 user-category-map))
1768 (if (member category org-export-odt-user-categories)
1769 user-category-map
1770 default-category-map)))))
1772 (defun org-odt-add-label-definition (label default-category)
1773 "Create an entry in `org-odt-entity-labels-alist' and return it."
1774 (setq label (substring-no-properties label))
1775 (let* ((label-props (org-odt-get-label-category-and-style
1776 label default-category))
1777 (category (nth 1 label-props))
1778 (counter category)
1779 (label-style (nth 2 label-props))
1780 (sequence-var (intern (mapconcat
1781 'downcase
1782 (org-split-string counter) "-")))
1783 (seqno (1+ (or (plist-get org-odt-entity-counts-plist sequence-var)
1784 0)))
1785 (label-props (list label category seqno label-style)))
1786 (setq org-odt-entity-counts-plist
1787 (plist-put org-odt-entity-counts-plist sequence-var seqno))
1788 (push label-props org-odt-entity-labels-alist)
1789 label-props))
1791 (defun org-odt-format-label-definition (caption label category seqno label-style)
1792 (assert label)
1793 (format-spec
1794 (cadr (assoc-string label-style org-odt-label-styles t))
1795 `((?e . ,category)
1796 (?n . ,(org-odt-format-tags
1797 '("<text:sequence text:ref-name=\"%s\" text:name=\"%s\" text:formula=\"ooow:%s+1\" style:num-format=\"1\">" . "</text:sequence>")
1798 (format "%d" seqno) label category category))
1799 (?c . ,(or (and caption (concat ": " caption)) "")))))
1801 (defun org-odt-format-label-reference (label category seqno label-style)
1802 (assert label)
1803 (save-match-data
1804 (let* ((fmt (cddr (assoc-string label-style org-odt-label-styles t)))
1805 (fmt1 (car fmt))
1806 (fmt2 (cadr fmt)))
1807 (org-odt-format-tags
1808 '("<text:sequence-ref text:reference-format=\"%s\" text:ref-name=\"%s\">"
1809 . "</text:sequence-ref>")
1810 (format-spec fmt2 `((?e . ,category)
1811 (?n . ,(format "%d" seqno)))) fmt1 label))))
1813 (defun org-odt-fixup-label-references ()
1814 (goto-char (point-min))
1815 (while (re-search-forward
1816 "<text:sequence-ref text:ref-name=\"\\([^\"]+\\)\"/>" nil t)
1817 (let* ((label (match-string 1))
1818 (label-def (assoc label org-odt-entity-labels-alist))
1819 (rpl (and label-def
1820 (apply 'org-odt-format-label-reference label-def))))
1821 (if rpl (replace-match rpl t t)
1822 (org-lparse-warn
1823 (format "Unable to resolve reference to label \"%s\"" label))))))
1825 (defun org-odt-format-entity-caption (label caption category)
1826 (or (and label
1827 (apply 'org-odt-format-label-definition
1828 caption (org-odt-add-label-definition label category)))
1829 caption ""))
1831 (defun org-odt-format-tags (tag text &rest args)
1832 (let ((prefix (when org-lparse-encode-pending "@"))
1833 (suffix (when org-lparse-encode-pending "@")))
1834 (apply 'org-lparse-format-tags tag text prefix suffix args)))
1836 (defun org-odt-init-outfile (filename)
1837 (unless (executable-find "zip")
1838 ;; Not at all OSes ship with zip by default
1839 (error "Executable \"zip\" needed for creating OpenDocument files"))
1841 (let* ((outdir (make-temp-file
1842 (format org-export-odt-tmpdir-prefix org-lparse-backend) t))
1843 (content-file (expand-file-name "content.xml" outdir)))
1845 ;; init conten.xml
1846 (with-current-buffer (find-file-noselect content-file t))
1848 ;; reset variables
1849 (setq org-odt-manifest-file-entries nil
1850 org-odt-embedded-images-count 0
1851 org-odt-embedded-formulas-count 0
1852 org-odt-entity-labels-alist nil
1853 org-odt-entity-counts-plist nil)
1854 content-file))
1856 (defcustom org-export-odt-prettify-xml nil
1857 "Specify whether or not the xml output should be prettified.
1858 When this option is turned on, `indent-region' is run on all
1859 component xml buffers before they are saved. Turn this off for
1860 regular use. Turn this on if you need to examine the xml
1861 visually."
1862 :group 'org-export-odt
1863 :type 'boolean)
1865 (defvar hfy-user-sheet-assoc) ; bound during org-do-lparse
1866 (defun org-odt-save-as-outfile (target opt-plist)
1867 ;; write meta file
1868 (org-odt-update-meta-file opt-plist)
1870 ;; write styles file
1871 (when (equal org-lparse-backend 'odt)
1872 (org-odt-update-styles-file opt-plist))
1874 ;; create mimetype file
1875 (let ((mimetype (org-odt-write-mimetype-file org-lparse-backend)))
1876 (org-odt-create-manifest-file-entry mimetype "/" "1.2"))
1878 ;; create a manifest entry for content.xml
1879 (org-odt-create-manifest-file-entry "text/xml" "content.xml")
1881 ;; write out the manifest entries before zipping
1882 (org-odt-write-manifest-file)
1884 (let ((xml-files '("mimetype" "META-INF/manifest.xml" "content.xml"
1885 "meta.xml"))
1886 (zipdir default-directory))
1887 (when (equal org-lparse-backend 'odt)
1888 (push "styles.xml" xml-files))
1889 (message "Switching to directory %s" (expand-file-name zipdir))
1891 ;; save all xml files
1892 (mapc (lambda (file)
1893 (with-current-buffer
1894 (find-file-noselect (expand-file-name file) t)
1895 ;; prettify output if needed
1896 (when org-export-odt-prettify-xml
1897 (indent-region (point-min) (point-max)))
1898 (save-buffer 0)))
1899 xml-files)
1901 (let* ((target-name (file-name-nondirectory target))
1902 (target-dir (file-name-directory target))
1903 (cmds `(("zip" "-mX0" ,target-name "mimetype")
1904 ("zip" "-rmTq" ,target-name "."))))
1905 (when (file-exists-p target)
1906 ;; FIXME: If the file is locked this throws a cryptic error
1907 (delete-file target))
1909 (let ((coding-system-for-write 'no-conversion) exitcode err-string)
1910 (message "Creating odt file...")
1911 (mapc
1912 (lambda (cmd)
1913 (message "Running %s" (mapconcat 'identity cmd " "))
1914 (setq err-string
1915 (with-output-to-string
1916 (setq exitcode
1917 (apply 'call-process (car cmd)
1918 nil standard-output nil (cdr cmd)))))
1919 (or (zerop exitcode)
1920 (ignore (message "%s" err-string))
1921 (error "Unable to create odt file (%S)" exitcode)))
1922 cmds))
1924 ;; move the file from outdir to target-dir
1925 (rename-file target-name target-dir)
1927 ;; kill all xml buffers
1928 (mapc (lambda (file)
1929 (kill-buffer
1930 (find-file-noselect (expand-file-name file zipdir) t)))
1931 xml-files)
1933 (delete-directory zipdir)))
1934 (message "Created %s" target)
1935 (set-buffer (find-file-noselect target t)))
1937 (defconst org-odt-manifest-file-entry-tag
1939 <manifest:file-entry manifest:media-type=\"%s\" manifest:full-path=\"%s\"%s/>")
1941 (defvar org-odt-manifest-file-entries nil)
1943 (defun org-odt-create-manifest-file-entry (&rest args)
1944 (push args org-odt-manifest-file-entries))
1946 (defun org-odt-write-manifest-file ()
1947 (make-directory "META-INF")
1948 (let ((manifest-file (expand-file-name "META-INF/manifest.xml")))
1949 (write-region
1950 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
1951 <manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"1.2\">\n"
1952 nil manifest-file)
1953 (mapc
1954 (lambda (file-entry)
1955 (let* ((version (nth 2 file-entry))
1956 (extra (if version
1957 (format " manifest:version=\"%s\"" version)
1958 "")))
1959 (write-region
1960 (format org-odt-manifest-file-entry-tag
1961 (nth 0 file-entry) (nth 1 file-entry) extra)
1962 nil manifest-file t))) org-odt-manifest-file-entries)
1963 (write-region "\n</manifest:manifest>" nil manifest-file t)))
1965 (defun org-odt-update-meta-file (opt-plist)
1966 (let ((date (org-odt-iso-date-from-org-timestamp
1967 (plist-get opt-plist :date)))
1968 (author (or (plist-get opt-plist :author) ""))
1969 (email (plist-get opt-plist :email))
1970 (keywords (plist-get opt-plist :keywords))
1971 (description (plist-get opt-plist :description))
1972 (title (plist-get opt-plist :title)))
1973 (write-region
1974 (concat
1975 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
1976 <office:document-meta
1977 xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"
1978 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
1979 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
1980 xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"
1981 xmlns:ooo=\"http://openoffice.org/2004/office\"
1982 office:version=\"1.2\">
1983 <office:meta>" "\n"
1984 (org-odt-format-author)
1985 (org-odt-format-tags
1986 '("\n<meta:initial-creator>" . "</meta:initial-creator>") author)
1987 (org-odt-format-tags '("\n<dc:date>" . "</dc:date>") date)
1988 (org-odt-format-tags
1989 '("\n<meta:creation-date>" . "</meta:creation-date>") date)
1990 (org-odt-format-tags '("\n<meta:generator>" . "</meta:generator>")
1991 (when org-export-creator-info
1992 (format "Org-%s/Emacs-%s"
1993 org-version emacs-version)))
1994 (org-odt-format-tags '("\n<meta:keyword>" . "</meta:keyword>") keywords)
1995 (org-odt-format-tags '("\n<dc:subject>" . "</dc:subject>") description)
1996 (org-odt-format-tags '("\n<dc:title>" . "</dc:title>") title)
1997 "\n"
1998 " </office:meta>" "</office:document-meta>")
1999 nil (expand-file-name "meta.xml")))
2001 ;; create a manifest entry for meta.xml
2002 (org-odt-create-manifest-file-entry "text/xml" "meta.xml"))
2004 (defun org-odt-update-styles-file (opt-plist)
2005 ;; write styles file
2006 (let ((styles-file (plist-get opt-plist :odt-styles-file)))
2007 (org-odt-copy-styles-file (and styles-file
2008 (read (org-trim styles-file)))))
2010 ;; Update styles.xml - take care of outline numbering
2011 (with-current-buffer
2012 (find-file-noselect (expand-file-name "styles.xml") t)
2013 ;; Don't make automatic backup of styles.xml file. This setting
2014 ;; prevents the backedup styles.xml file from being zipped in to
2015 ;; odt file. This is more of a hackish fix. Better alternative
2016 ;; would be to fix the zip command so that the output odt file
2017 ;; includes only the needed files and excludes any auto-generated
2018 ;; extra files like backups and auto-saves etc etc. Note that
2019 ;; currently the zip command zips up the entire temp directory so
2020 ;; that any auto-generated files created under the hood ends up in
2021 ;; the resulting odt file.
2022 (set (make-local-variable 'backup-inhibited) t)
2024 ;; Import local setting of `org-export-with-section-numbers'
2025 (org-lparse-bind-local-variables opt-plist)
2026 (org-odt-configure-outline-numbering
2027 (if org-export-with-section-numbers org-export-headline-levels 0)))
2029 ;; Write custom stlyes for source blocks
2030 (org-odt-insert-custom-styles-for-srcblocks
2031 (mapconcat
2032 (lambda (style)
2033 (format " %s\n" (cddr style)))
2034 hfy-user-sheet-assoc "")))
2036 (defun org-odt-write-mimetype-file (format)
2037 ;; create mimetype file
2038 (let ((mimetype
2039 (case format
2040 (odt "application/vnd.oasis.opendocument.text")
2041 (odf "application/vnd.oasis.opendocument.formula")
2042 (t (error "Unknown OpenDocument backend %S" org-lparse-backend)))))
2043 (write-region mimetype nil (expand-file-name "mimetype"))
2044 mimetype))
2046 (defun org-odt-finalize-outfile ()
2047 (org-odt-delete-empty-paragraphs))
2049 (defun org-odt-delete-empty-paragraphs ()
2050 (goto-char (point-min))
2051 (let ((open "<text:p[^>]*>")
2052 (close "</text:p>"))
2053 (while (re-search-forward (format "%s[ \r\n\t]*%s" open close) nil t)
2054 (replace-match ""))))
2056 (defcustom org-export-odt-convert-processes
2057 '(("BasicODConverter"
2058 ("soffice" "-norestore" "-invisible" "-headless"
2059 "\"macro:///BasicODConverter.Main.Convert(%I,%f,%O)\""))
2060 ("unoconv"
2061 ("unoconv" "-f" "%f" "-o" "%d" "%i")))
2062 "Specify a list of document converters and their usage.
2063 The converters in this list are offered as choices while
2064 customizing `org-export-odt-convert-process'.
2066 This variable is an alist where each element is of the
2067 form (CONVERTER-NAME CONVERTER-PROCESS). CONVERTER-NAME is name
2068 of the converter. CONVERTER-PROCESS specifies the command-line
2069 syntax of the converter and is of the form (CONVERTER-PROGRAM
2070 ARG1 ARG2 ...). CONVERTER-PROGRAM is the name of the executable.
2071 ARG1, ARG2 etc are command line options that are passed to
2072 CONVERTER-PROGRAM. Format specifiers can be used in the ARGs and
2073 they are interpreted as below:
2075 %i input file name in full
2076 %I input file name as a URL
2077 %f format of the output file
2078 %o output file name in full
2079 %O output file name as a URL
2080 %d output dir in full
2081 %D output dir as a URL."
2082 :group 'org-export-odt
2083 :type
2084 '(choice
2085 (const :tag "None" nil)
2086 (alist :tag "Converters"
2087 :key-type (string :tag "Converter Name")
2088 :value-type (group (cons (string :tag "Executable")
2089 (repeat (string :tag "Command line args")))))))
2091 (defcustom org-export-odt-convert-process nil
2092 "Use this converter to convert from \"odt\" format to other formats.
2093 During customization, the list of converter names are populated
2094 from `org-export-odt-convert-processes'."
2095 :group 'org-export-odt
2096 :type '(choice :convert-widget
2097 (lambda (w)
2098 (apply 'widget-convert (widget-type w)
2099 (eval (car (widget-get w :args)))))
2100 `((const :tag "None" nil)
2101 ,@(mapcar (lambda (c)
2102 `(const :tag ,(car c) ,(car c)))
2103 org-export-odt-convert-processes))))
2105 (defcustom org-export-odt-convert-capabilities
2106 '(("Text"
2107 ("odt" "ott" "doc" "rtf")
2108 (("pdf" "pdf") ("odt" "odt") ("xhtml" "html") ("rtf" "rtf")
2109 ("ott" "ott") ("doc" "doc") ("ooxml" "xml") ("html" "html")))
2110 ("Web"
2111 ("html" "xhtml") (("pdf" "pdf") ("odt" "txt") ("html" "html")))
2112 ("Spreadsheet"
2113 ("ods" "ots" "xls" "csv")
2114 (("pdf" "pdf") ("ots" "ots") ("html" "html") ("csv" "csv")
2115 ("ods" "ods") ("xls" "xls") ("xhtml" "xhtml") ("ooxml" "xml")))
2116 ("Presentation"
2117 ("odp" "otp" "ppt")
2118 (("pdf" "pdf") ("swf" "swf") ("odp" "odp") ("xhtml" "xml")
2119 ("otp" "otp") ("ppt" "ppt") ("odg" "odg") ("html" "html"))))
2120 "Specify input and output formats of `org-export-odt-convert-process'.
2121 More correctly, specify the set of input and output formats that
2122 the user is actually interested in.
2124 This variable is an alist where each element is of the
2125 form (DOCUMENT-CLASS INPUT-FMT-LIST OUTPUT-FMT-ALIST).
2126 INPUT-FMT-LIST is a list of INPUT-FMTs. OUTPUT-FMT-ALIST is an
2127 alist where each element is of the form (OUTPUT-FMT
2128 OUTPUT-FILE-EXTENSION).
2130 The variable is interpreted as follows:
2131 `org-export-odt-convert-process' can take any document that is in
2132 INPUT-FMT-LIST and produce any document that is in the
2133 OUTPUT-FMT-LIST. A document converted to OUTPUT-FMT will have
2134 OUTPUT-FILE-EXTENSION as the file name extension. OUTPUT-FMT
2135 serves dual purposes:
2136 - It is used for populating completion candidates during
2137 `org-export-odt-convert' commands.
2138 - It is used as the value of \"%f\" specifier in
2139 `org-export-odt-convert-process'.
2141 DOCUMENT-CLASS is used to group a set of file formats in
2142 INPUT-FMT-LIST in to a single class.
2144 Note that this variable inherently captures how LibreOffice based
2145 converters work. LibreOffice maps documents of various formats
2146 to classes like Text, Web, Spreadsheet, Presentation etc and
2147 allow document of a given class (irrespective of it's source
2148 format) to be converted to any of the export formats associated
2149 with that class.
2151 See default setting of this variable for an typical
2152 configuration."
2153 :group 'org-export-odt
2154 :type
2155 '(choice
2156 (const :tag "None" nil)
2157 (alist :key-type (string :tag "Document Class")
2158 :value-type
2159 (group (repeat :tag "Input formats" (string :tag "Input format"))
2160 (alist :tag "Output formats"
2161 :key-type (string :tag "Output format")
2162 :value-type
2163 (group (string :tag "Output file extension")))))))
2165 ;;;###autoload
2166 (defun org-export-odt-convert (&optional in-file out-fmt prefix-arg)
2167 "Convert IN-FILE to format OUT-FMT using a command line converter.
2168 IN-FILE is the file to be converted. If unspecified, it defaults
2169 to variable `buffer-file-name'. OUT-FMT is the desired output
2170 format. Use `org-export-odt-convert-process' as the converter.
2171 If PREFIX-ARG is non-nil then the newly converted file is opened
2172 using `org-open-file'."
2173 (interactive
2174 (append (org-lparse-convert-read-params) current-prefix-arg))
2175 (org-lparse-do-convert in-file out-fmt prefix-arg))
2177 (defun org-odt-get (what &optional opt-plist)
2178 (case what
2179 (BACKEND 'odt)
2180 (EXPORT-DIR (org-export-directory :html opt-plist))
2181 (FILE-NAME-EXTENSION "odt")
2182 (EXPORT-BUFFER-NAME "*Org ODT Export*")
2183 (ENTITY-CONTROL org-odt-entity-control-callbacks-alist)
2184 (ENTITY-FORMAT org-odt-entity-format-callbacks-alist)
2185 (INIT-METHOD 'org-odt-init-outfile)
2186 (FINAL-METHOD 'org-odt-finalize-outfile)
2187 (SAVE-METHOD 'org-odt-save-as-outfile)
2188 (CONVERT-METHOD
2189 (and org-export-odt-convert-process
2190 (cadr (assoc-string org-export-odt-convert-process
2191 org-export-odt-convert-processes t))))
2192 (CONVERT-CAPABILITIES
2193 (and org-export-odt-convert-process
2194 (cadr (assoc-string org-export-odt-convert-process
2195 org-export-odt-convert-processes t))
2196 org-export-odt-convert-capabilities))
2197 (TOPLEVEL-HLEVEL 1)
2198 (SPECIAL-STRING-REGEXPS org-export-odt-special-string-regexps)
2199 (INLINE-IMAGES 'maybe)
2200 (INLINE-IMAGE-EXTENSIONS '("png" "jpeg" "jpg" "gif" "svg"))
2201 (PLAIN-TEXT-MAP '(("&" . "&amp;") ("<" . "&lt;") (">" . "&gt;")))
2202 (TABLE-FIRST-COLUMN-AS-LABELS nil)
2203 (FOOTNOTE-SEPARATOR (org-lparse-format 'FONTIFY "," 'superscript))
2204 (CODING-SYSTEM-FOR-WRITE 'utf-8)
2205 (CODING-SYSTEM-FOR-SAVE 'utf-8)
2206 (t (error "Unknown property: %s" what))))
2208 (defvar org-lparse-latex-fragment-fallback) ; set by org-do-lparse
2209 (defun org-export-odt-do-preprocess-latex-fragments ()
2210 "Convert LaTeX fragments to images."
2211 (let* ((latex-frag-opt (plist-get org-lparse-opt-plist :LaTeX-fragments))
2212 (latex-frag-opt ; massage the options
2213 (or (and (member latex-frag-opt '(mathjax t))
2214 (not (and (fboundp 'org-format-latex-mathml-available-p)
2215 (org-format-latex-mathml-available-p)))
2216 (prog1 org-lparse-latex-fragment-fallback
2217 (org-lparse-warn
2218 (concat
2219 "LaTeX to MathML converter not available. "
2220 (format "Using %S instead."
2221 org-lparse-latex-fragment-fallback)))))
2222 latex-frag-opt))
2223 cache-dir display-msg)
2224 (cond
2225 ((eq latex-frag-opt 'dvipng)
2226 (setq cache-dir "ltxpng/")
2227 (setq display-msg "Creating LaTeX image %s"))
2228 ((member latex-frag-opt '(mathjax t))
2229 (setq latex-frag-opt 'mathml)
2230 (setq cache-dir "ltxmathml/")
2231 (setq display-msg "Creating MathML formula %s")))
2232 (when (and org-current-export-file)
2233 (org-format-latex
2234 (concat cache-dir (file-name-sans-extension
2235 (file-name-nondirectory org-current-export-file)))
2236 org-current-export-dir nil display-msg
2237 nil nil latex-frag-opt))))
2239 (defadvice org-format-latex-as-mathml
2240 (after org-odt-protect-latex-fragment activate)
2241 "Encode LaTeX fragment as XML.
2242 Do this when translation to MathML fails."
2243 (when (or (not (> (length ad-return-value) 0))
2244 (get-text-property 0 'org-protected ad-return-value))
2245 (setq ad-return-value
2246 (org-propertize (org-odt-encode-plain-text (ad-get-arg 0))
2247 'org-protected t))))
2249 (defun org-export-odt-preprocess-latex-fragments ()
2250 (when (equal org-export-current-backend 'odt)
2251 (org-export-odt-do-preprocess-latex-fragments)))
2253 (defun org-export-odt-preprocess-label-references ()
2254 (goto-char (point-min))
2255 (let (label label-components category value pretty-label)
2256 (while (re-search-forward "\\\\ref{\\([^{}\n]+\\)}" nil t)
2257 (org-if-unprotected-at (match-beginning 1)
2258 (replace-match
2259 (let ((org-lparse-encode-pending t)
2260 (label (match-string 1)))
2261 ;; markup generated below is mostly an eye-candy. At
2262 ;; pre-processing stage, there is no information on which
2263 ;; entity a label reference points to. The actual markup
2264 ;; is generated as part of `org-odt-fixup-label-references'
2265 ;; which gets called at the fag end of export. By this
2266 ;; time we would have seen and collected all the label
2267 ;; definitions in `org-odt-entity-labels-alist'.
2268 (org-odt-format-tags
2269 "<text:sequence-ref text:ref-name=\"%s\"/>" ""
2270 (org-add-props label '(org-protected t)))) t t)))))
2272 ;; process latex fragments as part of
2273 ;; `org-export-preprocess-after-blockquote-hook'. Note that this hook
2274 ;; is the one that is closest and well before the call to
2275 ;; `org-export-attach-captions-and-attributes' in
2276 ;; `org-export-preprocess-stirng'. The above arrangement permits
2277 ;; captions, labels and attributes to be attached to png images
2278 ;; generated out of latex equations.
2279 (add-hook 'org-export-preprocess-after-blockquote-hook
2280 'org-export-odt-preprocess-latex-fragments)
2282 (defun org-export-odt-preprocess (parameters)
2283 (org-export-odt-preprocess-label-references))
2285 (declare-function archive-zip-extract "arc-mode.el" (archive name))
2286 (defun org-odt-zip-extract-one (archive member &optional target)
2287 (require 'arc-mode)
2288 (let* ((target (or target default-directory))
2289 (archive (expand-file-name archive))
2290 (archive-zip-extract
2291 (list "unzip" "-qq" "-o" "-d" target))
2292 exit-code command-output)
2293 (setq command-output
2294 (with-temp-buffer
2295 (setq exit-code (archive-zip-extract archive member))
2296 (buffer-string)))
2297 (unless (zerop exit-code)
2298 (message command-output)
2299 (error "Extraction failed"))))
2301 (defun org-odt-zip-extract (archive members &optional target)
2302 (when (atom members) (setq members (list members)))
2303 (mapc (lambda (member)
2304 (org-odt-zip-extract-one archive member target))
2305 members))
2307 (defun org-odt-copy-styles-file (&optional styles-file)
2308 ;; Non-availability of styles.xml is not a critical error. For now
2309 ;; throw an error purely for aesthetic reasons.
2310 (setq styles-file (or styles-file
2311 org-export-odt-styles-file
2312 (expand-file-name "styles/OrgOdtStyles.xml"
2313 org-odt-data-dir)
2314 (error "org-odt: Missing styles file?")))
2315 (cond
2316 ((listp styles-file)
2317 (let ((archive (nth 0 styles-file))
2318 (members (nth 1 styles-file)))
2319 (org-odt-zip-extract archive members)
2320 (mapc
2321 (lambda (member)
2322 (when (org-file-image-p member)
2323 (let* ((image-type (file-name-extension member))
2324 (media-type (format "image/%s" image-type)))
2325 (org-odt-create-manifest-file-entry media-type member))))
2326 members)))
2327 ((and (stringp styles-file) (file-exists-p styles-file))
2328 (let ((styles-file-type (file-name-extension styles-file)))
2329 (cond
2330 ((string= styles-file-type "xml")
2331 (copy-file styles-file "styles.xml" t))
2332 ((member styles-file-type '("odt" "ott"))
2333 (org-odt-zip-extract styles-file "styles.xml")))))
2335 (error (format "Invalid specification of styles.xml file: %S"
2336 org-export-odt-styles-file))))
2338 ;; create a manifest entry for styles.xml
2339 (org-odt-create-manifest-file-entry "text/xml" "styles.xml"))
2341 (defvar org-export-odt-factory-settings
2342 "d4328fb9d1b6cb211d4320ff546829f26700dc5e"
2343 "SHA1 hash of OrgOdtStyles.xml.")
2345 (defun org-odt-configure-outline-numbering (level)
2346 "Outline numbering is retained only upto LEVEL.
2347 To disable outline numbering pass a LEVEL of 0."
2348 (goto-char (point-min))
2349 (let ((regex
2350 "<text:outline-level-style\\([^>]*\\)text:level=\"\\([^\"]*\\)\"\\([^>]*\\)>")
2351 (replacement
2352 "<text:outline-level-style\\1text:level=\"\\2\" style:num-format=\"\">"))
2353 (while (re-search-forward regex nil t)
2354 (when (> (string-to-number (match-string 2)) level)
2355 (replace-match replacement t nil))))
2356 (save-buffer 0))
2358 ;;;###autoload
2359 (defun org-export-as-odf (latex-frag &optional odf-file)
2360 "Export LATEX-FRAG as OpenDocument formula file ODF-FILE.
2361 Use `org-create-math-formula' to convert LATEX-FRAG first to
2362 MathML. When invoked as an interactive command, use
2363 `org-latex-regexps' to infer LATEX-FRAG from currently active
2364 region. If no LaTeX fragments are found, prompt for it. Push
2365 MathML source to kill ring, if `org-export-copy-to-kill-ring' is
2366 non-nil."
2367 (interactive
2368 `(,(let (frag)
2369 (setq frag (and (setq frag (and (region-active-p)
2370 (buffer-substring (region-beginning)
2371 (region-end))))
2372 (loop for e in org-latex-regexps
2373 thereis (when (string-match (nth 1 e) frag)
2374 (match-string (nth 2 e) frag)))))
2375 (read-string "LaTeX Fragment: " frag nil frag))
2376 ,(let ((odf-filename (expand-file-name
2377 (concat
2378 (file-name-sans-extension
2379 (or (file-name-nondirectory buffer-file-name)))
2380 "." "odf")
2381 (file-name-directory buffer-file-name))))
2382 (message "default val is %s" odf-filename)
2383 (read-file-name "ODF filename: " nil odf-filename nil
2384 (file-name-nondirectory odf-filename)))))
2385 (let* ((org-lparse-backend 'odf)
2386 org-lparse-opt-plist
2387 (filename (or odf-file
2388 (expand-file-name
2389 (concat
2390 (file-name-sans-extension
2391 (or (file-name-nondirectory buffer-file-name)))
2392 "." "odf")
2393 (file-name-directory buffer-file-name))))
2394 (buffer (find-file-noselect (org-odt-init-outfile filename)))
2395 (coding-system-for-write 'utf-8)
2396 (save-buffer-coding-system 'utf-8))
2397 (set-buffer buffer)
2398 (set-buffer-file-coding-system coding-system-for-write)
2399 (let ((mathml (org-create-math-formula latex-frag)))
2400 (unless mathml (error "No Math formula created"))
2401 (insert mathml)
2402 (or (org-export-push-to-kill-ring
2403 (upcase (symbol-name org-lparse-backend)))
2404 (message "Exporting... done")))
2405 (org-odt-save-as-outfile filename nil)))
2407 ;;;###autoload
2408 (defun org-export-as-odf-and-open ()
2409 "Export LaTeX fragment as OpenDocument formula and immediately open it.
2410 Use `org-export-as-odf' to read LaTeX fragment and OpenDocument
2411 formula file."
2412 (interactive)
2413 (org-lparse-and-open
2414 nil nil nil (call-interactively 'org-export-as-odf)))
2416 (provide 'org-odt)
2418 ;;; org-odt.el ends here