Add command to export LaTeX fragments to OpenDocument formula file
[org-mode/org-jambu.git] / contrib / lisp / org-odt.el
blob2d4b4fcf278e3e3e132467aa276067b92bf9a46e
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 'paragraph))
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 (copy-file src-file target-file 'overwrite)
1310 (org-odt-create-manifest-file-entry "text/xml" target-file))
1311 target-file))
1313 (defun org-odt-format-inline-formula (thefile)
1314 (let* ((thelink (if (file-name-absolute-p thefile) thefile
1315 (org-xml-format-href
1316 (org-odt-relocate-relative-path
1317 thefile org-current-export-file))))
1318 (href
1319 (org-odt-format-tags
1320 "<draw:object xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>" ""
1321 (file-name-directory (org-odt-copy-formula-file thefile)))))
1322 (org-export-odt-format-formula thefile href)))
1324 (defun org-odt-is-formula-link-p (file)
1325 (let ((case-fold-search nil))
1326 (string-match "\\.mathml\\'" file)))
1328 (defun org-odt-format-org-link (opt-plist type-1 path fragment desc attr
1329 descp)
1330 "Make an HTML link.
1331 OPT-PLIST is an options list.
1332 TYPE is the device-type of the link (THIS://foo.html)
1333 PATH is the path of the link (http://THIS#locationx)
1334 FRAGMENT is the fragment part of the link, if any (foo.html#THIS)
1335 DESC is the link description, if any.
1336 ATTR is a string of other attributes of the a element.
1337 MAY-INLINE-P allows inlining it as an image."
1338 (declare (special org-lparse-par-open))
1339 (save-match-data
1340 (let* ((may-inline-p
1341 (and (member type-1 '("http" "https" "file"))
1342 (org-lparse-should-inline-p path descp)
1343 (not fragment)))
1344 (type (if (equal type-1 "id") "file" type-1))
1345 (filename path)
1346 (thefile path))
1347 (cond
1348 ;; check for inlined images
1349 ((and (member type '("file"))
1350 (not fragment)
1351 (org-file-image-p
1352 filename org-export-odt-inline-image-extensions)
1353 (or (eq t org-export-odt-inline-images)
1354 (and org-export-odt-inline-images (not descp))))
1355 (org-odt-format-inline-image thefile))
1356 ;; check for embedded formulas
1357 ((and (member type '("file"))
1358 (not fragment)
1359 (org-odt-is-formula-link-p filename)
1360 (or (not descp)))
1361 (org-odt-format-inline-formula thefile))
1362 ((string= type "coderef")
1363 (let* ((ref fragment)
1364 (lineno-or-ref (cdr (assoc ref org-export-code-refs)))
1365 (desc (and descp desc))
1366 (org-odt-suppress-xref nil)
1367 (href (org-xml-format-href (concat "#coderef-" ref))))
1368 (cond
1369 ((and (numberp lineno-or-ref) (not desc))
1370 (org-odt-format-link lineno-or-ref href))
1371 ((and (numberp lineno-or-ref) desc
1372 (string-match (regexp-quote (concat "(" ref ")")) desc))
1373 (format (replace-match "%s" t t desc)
1374 (org-odt-format-link lineno-or-ref href)))
1376 (setq desc (format
1377 (if (and desc (string-match
1378 (regexp-quote (concat "(" ref ")"))
1379 desc))
1380 (replace-match "%s" t t desc)
1381 (or desc "%s"))
1382 lineno-or-ref))
1383 (org-odt-format-link (org-xml-format-desc desc) href)))))
1385 (when (string= type "file")
1386 (setq thefile
1387 (cond
1388 ((file-name-absolute-p path)
1389 (concat "file://" (expand-file-name path)))
1390 (t (org-odt-relocate-relative-path
1391 thefile org-current-export-file)))))
1393 (when (and (member type '("" "http" "https" "file")) fragment)
1394 (setq thefile (concat thefile "#" fragment)))
1396 (setq thefile (org-xml-format-href thefile))
1398 (when (not (member type '("" "file")))
1399 (setq thefile (concat type ":" thefile)))
1401 (let ((org-odt-suppress-xref nil))
1402 (org-odt-format-link
1403 (org-xml-format-desc desc) thefile attr)))))))
1405 (defun org-odt-format-heading (text level &optional id)
1406 (let* ((text (if id (org-odt-format-target text id) text)))
1407 (org-odt-format-tags
1408 '("<text:h text:style-name=\"Heading_20_%s\" text:outline-level=\"%s\">" .
1409 "</text:h>") text level level)))
1411 (defun org-odt-format-headline (title extra-targets tags
1412 &optional snumber level)
1413 (concat
1414 (org-lparse-format 'EXTRA-TARGETS extra-targets)
1416 ;; No need to generate section numbers. They are auto-generated by
1417 ;; the application
1419 ;; (concat (org-lparse-format 'SECTION-NUMBER snumber level) " ")
1420 title
1421 (and tags (concat (org-lparse-format 'SPACES 3)
1422 (org-lparse-format 'ORG-TAGS tags)))))
1424 (defun org-odt-format-anchor (text name &optional class)
1425 (org-odt-format-target text name))
1427 (defun org-odt-format-bookmark (text id)
1428 (if id
1429 (org-odt-format-tags "<text:bookmark text:name=\"%s\"/>" text id)
1430 text))
1432 (defun org-odt-format-target (text id)
1433 (let ((name (concat org-export-odt-bookmark-prefix id)))
1434 (concat
1435 (and id (org-odt-format-tags
1436 "<text:bookmark-start text:name=\"%s\"/>" "" name))
1437 (org-odt-format-bookmark text id)
1438 (and id (org-odt-format-tags
1439 "<text:bookmark-end text:name=\"%s\"/>" "" name)))))
1441 (defun org-odt-format-footnote (n def)
1442 (let ((id (concat "fn" n))
1443 (note-class "footnote")
1444 (par-style "Footnote"))
1445 (org-odt-format-tags
1446 '("<text:note text:id=\"%s\" text:note-class=\"%s\">" .
1447 "</text:note>")
1448 (concat
1449 (org-odt-format-tags
1450 '("<text:note-citation>" . "</text:note-citation>")
1452 (org-odt-format-tags
1453 '("<text:note-body>" . "</text:note-body>")
1454 def))
1455 id note-class)))
1457 (defun org-odt-format-footnote-reference (n def refcnt)
1458 (if (= refcnt 1)
1459 (org-odt-format-footnote n def)
1460 (org-odt-format-footnote-ref n)))
1462 (defun org-odt-format-footnote-ref (n)
1463 (let ((note-class "footnote")
1464 (ref-format "text")
1465 (ref-name (concat "fn" n)))
1466 (org-odt-format-tags
1467 '("<text:span text:style-name=\"%s\">" . "</text:span>")
1468 (org-odt-format-tags
1469 '("<text:note-ref text:note-class=\"%s\" text:reference-format=\"%s\" text:ref-name=\"%s\">" . "</text:note-ref>")
1470 n note-class ref-format ref-name)
1471 "OrgSuperscript")))
1473 (defun org-odt-get-image-name (file-name)
1474 (require 'sha1)
1475 (file-relative-name
1476 (expand-file-name
1477 (concat (sha1 file-name) "." (file-name-extension file-name)) "Pictures")))
1479 (defun org-export-odt-format-image (src href &optional embed-as)
1480 "Create image tag with source and attributes."
1481 (save-match-data
1482 (let* ((caption (org-find-text-property-in-string 'org-caption src))
1483 (caption (and caption (org-xml-format-desc caption)))
1484 (attr (org-find-text-property-in-string 'org-attributes src))
1485 (label (org-find-text-property-in-string 'org-label src))
1486 (latex-frag (org-find-text-property-in-string
1487 'org-latex-src src))
1488 (category (and latex-frag "__DvipngImage__"))
1489 (embed-as (or embed-as
1490 (if latex-frag
1491 (or (org-find-text-property-in-string
1492 'org-latex-src-embed-type src) 'character)
1493 'paragraph)))
1494 (attr-plist (org-lparse-get-block-params attr))
1495 (size (org-odt-image-size-from-file
1496 src (plist-get attr-plist :width)
1497 (plist-get attr-plist :height)
1498 (plist-get attr-plist :scale) nil embed-as))
1499 (width (car size)) (height (cdr size)))
1500 (when latex-frag
1501 (setq href (org-propertize href :title "LaTeX Fragment"
1502 :description latex-frag)))
1503 (cond
1504 ((not (or caption label))
1505 (case embed-as
1506 (paragraph (org-odt-format-entity "DisplayImage" href width height))
1507 (character (org-odt-format-entity "InlineImage" href width height))
1508 (t (error "Unknown value for embed-as %S" embed-as))))
1510 (org-odt-format-entity
1511 "CaptionedDisplayImage" href width height caption label category))))))
1513 (defun org-odt-format-object-description (title description)
1514 (concat (and title (org-odt-format-tags
1515 '("<svg:title>" . "</svg:title>")
1516 (org-odt-encode-plain-text title t)))
1517 (and description (org-odt-format-tags
1518 '("<svg:desc>" . "</svg:desc>")
1519 (org-odt-encode-plain-text description t)))))
1521 (defun org-odt-format-frame (text width height style &optional
1522 extra anchor-type)
1523 (let ((frame-attrs
1524 (concat
1525 (if width (format " svg:width=\"%0.2fcm\"" width) "")
1526 (if height (format " svg:height=\"%0.2fcm\"" height) "")
1527 extra
1528 (format " text:anchor-type=\"%s\"" (or anchor-type "paragraph")))))
1529 (org-odt-format-tags
1530 '("<draw:frame draw:style-name=\"%s\"%s>" . "</draw:frame>")
1531 (concat text (org-odt-format-object-description
1532 (get-text-property 0 :title text)
1533 (get-text-property 0 :description text)))
1534 style frame-attrs)))
1536 (defun org-odt-format-textbox (text width height style &optional
1537 extra anchor-type)
1538 (org-odt-format-frame
1539 (org-odt-format-tags
1540 '("<draw:text-box %s>" . "</draw:text-box>")
1541 text (concat (format " fo:min-height=\"%0.2fcm\"" (or height .2))
1542 (format " fo:min-width=\"%0.2fcm\"" (or width .2))))
1543 width nil style extra anchor-type))
1545 (defun org-odt-format-inlinetask (heading content
1546 &optional todo priority tags)
1547 (org-odt-format-stylized-paragraph
1548 nil (org-odt-format-textbox
1549 (concat (org-odt-format-stylized-paragraph
1550 "OrgInlineTaskHeading"
1551 (org-lparse-format
1552 'HEADLINE (concat (org-lparse-format-todo todo) " " heading)
1553 nil tags))
1554 content) nil nil "OrgInlineTaskFrame" " style:rel-width=\"100%\"")))
1556 (defvar org-odt-entity-frame-styles
1557 '(("InlineImage" "__Figure__" ("OrgInlineImage" nil "as-char"))
1558 ("DisplayImage" "__Figure__" ("OrgDisplayImage" nil "paragraph"))
1559 ("CaptionedDisplayImage" "__Figure__"
1560 ("OrgCaptionedImage"
1561 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
1562 ("OrgImageCaptionFrame"))
1563 ("InlineFormula" "__MathFormula__" ("OrgInlineFormula" nil "as-char"))
1564 ("DisplayFormula" "__MathFormula__" ("OrgDisplayFormula" nil "as-char"))
1565 ("CaptionedDisplayFormula" "__MathFormula__"
1566 ("OrgCaptionedFormula" nil "paragraph")
1567 ("OrgFormulaCaptionFrame" nil "as-char"))))
1569 (defun org-odt-format-entity (entity href width height
1570 &optional caption label category)
1571 (let* ((entity-style (assoc entity org-odt-entity-frame-styles))
1572 (entity-frame (apply 'org-odt-format-frame
1573 href width height (nth 2 entity-style))))
1574 (if (not (or caption label)) entity-frame
1575 (apply 'org-odt-format-textbox
1576 (org-odt-format-stylized-paragraph
1577 'illustration
1578 (concat entity-frame
1579 (org-odt-format-entity-caption
1580 label caption (or category (nth 1 entity-style)))))
1581 width height (nth 3 entity-style)))))
1583 (defvar org-odt-embedded-images-count 0)
1584 (defun org-odt-copy-image-file (path)
1585 "Returns the internal name of the file"
1586 (let* ((image-type (file-name-extension path))
1587 (media-type (format "image/%s" image-type))
1588 (src-file (expand-file-name
1589 path (file-name-directory org-current-export-file)))
1590 (target-dir "Images/")
1591 (target-file
1592 (format "%s%04d.%s" target-dir
1593 (incf org-odt-embedded-images-count) image-type)))
1594 (when (not org-lparse-to-buffer)
1595 (message "Embedding %s as %s ..."
1596 (substring-no-properties path) target-file)
1598 (when (= 1 org-odt-embedded-images-count)
1599 (make-directory target-dir)
1600 (org-odt-create-manifest-file-entry "" target-dir))
1602 (copy-file src-file target-file 'overwrite)
1603 (org-odt-create-manifest-file-entry media-type target-file))
1604 target-file))
1606 (defvar org-export-odt-image-size-probe-method
1607 '(emacs imagemagick force)
1608 "Ordered list of methods by for determining size of an embedded
1609 image.")
1611 (defvar org-export-odt-default-image-sizes-alist
1612 '(("character" . (5 . 0.4))
1613 ("paragraph" . (5 . 5)))
1614 "Hardcoded image dimensions one for each of the anchor
1615 methods.")
1617 (defun org-odt-do-image-size (probe-method file &optional dpi anchor-type)
1618 (setq dpi (or dpi org-export-odt-pixels-per-inch))
1619 (setq anchor-type (or anchor-type "paragraph"))
1620 (flet ((size-in-cms (size-in-pixels)
1621 (flet ((pixels-to-cms (pixels)
1622 (let* ((cms-per-inch 2.54)
1623 (inches (/ pixels dpi)))
1624 (* cms-per-inch inches))))
1625 (and size-in-pixels
1626 (cons (pixels-to-cms (car size-in-pixels))
1627 (pixels-to-cms (cdr size-in-pixels)))))))
1628 (case probe-method
1629 (emacs
1630 (size-in-cms (ignore-errors (image-size (create-image file) 'pixels))))
1631 (imagemagick
1632 (size-in-cms
1633 (let ((dim (shell-command-to-string
1634 (format "identify -format \"%%w:%%h\" \"%s\"" file))))
1635 (when (string-match "\\([0-9]+\\):\\([0-9]+\\)" dim)
1636 (cons (string-to-number (match-string 1 dim))
1637 (string-to-number (match-string 2 dim)))))))
1639 (cdr (assoc-string anchor-type
1640 org-export-odt-default-image-sizes-alist))))))
1642 (defun org-odt-image-size-from-file (file &optional user-width
1643 user-height scale dpi embed-as)
1644 (unless (file-name-absolute-p file)
1645 (setq file (expand-file-name
1646 file (file-name-directory org-current-export-file))))
1647 (let* (size width height)
1648 (unless (and user-height user-width)
1649 (loop for probe-method in org-export-odt-image-size-probe-method
1650 until size
1651 do (setq size (org-odt-do-image-size
1652 probe-method file dpi embed-as)))
1653 (or size (error "Cannot determine Image size. Aborting ..."))
1654 (setq width (car size) height (cdr size)))
1655 (cond
1656 (scale
1657 (setq width (* width scale) height (* height scale)))
1658 ((and user-height user-width)
1659 (setq width user-width height user-height))
1660 (user-height
1661 (setq width (* user-height (/ width height)) height user-height))
1662 (user-width
1663 (setq height (* user-width (/ height width)) width user-width))
1664 (t (ignore)))
1665 (cons width height)))
1667 (defvar org-odt-entity-labels-alist nil
1668 "Associate Labels with the Labelled entities.
1669 Each element of the alist is of the form (LABEL-NAME
1670 CATEGORY-NAME SEQNO LABEL-STYLE-NAME). LABEL-NAME is same as
1671 that specified by \"#+LABEL: ...\" line. CATEGORY-NAME is the
1672 type of the entity that LABEL-NAME is attached to. CATEGORY-NAME
1673 can be one of \"Table\", \"Figure\" or \"Equation\". SEQNO is
1674 the unique number assigned to the referenced entity on a
1675 per-CATEGORY basis. It is generated sequentially and is 1-based.
1676 LABEL-STYLE-NAME is a key `org-odt-label-styles'.
1678 See `org-odt-add-label-definition' and
1679 `org-odt-fixup-label-references'.")
1681 (defvar org-odt-entity-counts-plist nil
1682 "Plist of running counters of SEQNOs for each of the CATEGORY-NAMEs.
1683 See `org-odt-entity-labels-alist' for known CATEGORY-NAMEs.")
1685 (defvar org-odt-label-styles
1686 '(("text" "(%n)" "text" "(%n)")
1687 ("category-and-value" "%e %n%c" "category-and-value" "%e %n"))
1688 "Specify how labels are applied and referenced.
1689 This is an alist where each element is of the
1690 form (LABEL-STYLE-NAME LABEL-ATTACH-FMT LABEL-REF-MODE
1691 LABEL-REF-FMT).
1693 LABEL-ATTACH-FMT controls how labels and captions are attached to
1694 an entity. It may contain following specifiers - %e, %n and %c.
1695 %e is replaced with the CATEGORY-NAME. %n is replaced with
1696 \"<text:sequence ...> SEQNO </text:sequence>\". %c is replaced
1697 with CAPTION. See `org-odt-format-label-definition'.
1699 LABEL-REF-MODE and LABEL-REF-FMT controls how label references
1700 are generated. The following XML is generated for a label
1701 reference - \"<text:sequence-ref
1702 text:reference-format=\"LABEL-REF-MODE\" ...> LABEL-REF-FMT
1703 </text:sequence-ref>\". LABEL-REF-FMT may contain following
1704 specifiers - %e and %n. %e is replaced with the CATEGORY-NAME.
1705 %n is replaced with SEQNO. See
1706 `org-odt-format-label-reference'.")
1708 (defvar org-odt-category-map-alist
1709 '(("__Table__" "Table" "category-and-value")
1710 ("__Figure__" "Figure" "category-and-value")
1711 ("__MathFormula__" "Equation" "text")
1712 ("__DvipngImage__" "Equation" "category-and-value"))
1713 "Map a CATEGORY-HANDLE to CATEGORY-NAME and LABEL-STYLE.
1714 This is an alist where each element is of the form
1715 \\(CATEGORY-HANDLE CATEGORY-NAME LABEL-STYLE\\). CATEGORY_HANDLE
1716 could either be one of the internal handles (as seen above) or be
1717 derived from the \"#+LABEL:<label-name>\" specification. See
1718 `org-export-odt-get-category-from-label'. CATEGORY-NAME and
1719 LABEL-STYLE are used for generating ODT labels. See
1720 `org-odt-label-styles'.")
1722 (defvar org-export-odt-user-categories
1723 '("Illustration" "Table" "Text" "Drawing" "Equation" "Figure"))
1725 (defvar org-export-odt-get-category-from-label nil
1726 "Should category of label be inferred from label itself.
1727 When this option is non-nil, a label is parsed in to two
1728 component parts delimited by a \":\" (colon) as shown here -
1729 #+LABEL:[CATEGORY-HANDLE:]EXTRA. The CATEGORY-HANDLE is mapped
1730 to a CATEGORY-NAME and LABEL-STYLE using
1731 `org-odt-category-map-alist'. (If no such map is provided and
1732 CATEGORY-NAME is set to CATEGORY-HANDLE and LABEL-STYLE is set to
1733 \"category-and-value\"). If CATEGORY-NAME so obtained is listed
1734 under `org-export-odt-user-categories' then the user specified
1735 styles are used. Otherwise styles as determined by the internal
1736 CATEGORY-HANDLE is used. See
1737 `org-odt-get-label-category-and-style' for details.")
1739 (defun org-odt-get-label-category-and-style (label default-category)
1740 "See `org-export-odt-get-category-from-label'."
1741 (let ((default-category-map
1742 (assoc default-category org-odt-category-map-alist))
1743 user-category user-category-map category)
1744 (cond
1745 ((not org-export-odt-get-category-from-label)
1746 default-category-map)
1747 ((not (setq user-category
1748 (save-match-data
1749 (and (string-match "\\`\\(.*\\):.+" label)
1750 (match-string 1 label)))))
1751 default-category-map)
1753 (setq user-category-map
1754 (or (assoc user-category org-odt-category-map-alist)
1755 (list nil user-category "category-and-value"))
1756 category (nth 1 user-category-map))
1757 (if (member category org-export-odt-user-categories)
1758 user-category-map
1759 default-category-map)))))
1761 (defun org-odt-add-label-definition (label default-category)
1762 "Create an entry in `org-odt-entity-labels-alist' and return it."
1763 (setq label (substring-no-properties label))
1764 (let* ((label-props (org-odt-get-label-category-and-style
1765 label default-category))
1766 (category (nth 1 label-props))
1767 (counter category)
1768 (label-style (nth 2 label-props))
1769 (sequence-var (intern (mapconcat
1770 'downcase
1771 (org-split-string counter) "-")))
1772 (seqno (1+ (or (plist-get org-odt-entity-counts-plist sequence-var)
1773 0)))
1774 (label-props (list label category seqno label-style)))
1775 (setq org-odt-entity-counts-plist
1776 (plist-put org-odt-entity-counts-plist sequence-var seqno))
1777 (push label-props org-odt-entity-labels-alist)
1778 label-props))
1780 (defun org-odt-format-label-definition (caption label category seqno label-style)
1781 (assert label)
1782 (format-spec
1783 (cadr (assoc-string label-style org-odt-label-styles t))
1784 `((?e . ,category)
1785 (?n . ,(org-odt-format-tags
1786 '("<text:sequence text:ref-name=\"%s\" text:name=\"%s\" text:formula=\"ooow:%s+1\" style:num-format=\"1\">" . "</text:sequence>")
1787 (format "%d" seqno) label category category))
1788 (?c . ,(or (and caption (concat ": " caption)) "")))))
1790 (defun org-odt-format-label-reference (label category seqno label-style)
1791 (assert label)
1792 (save-match-data
1793 (let* ((fmt (cddr (assoc-string label-style org-odt-label-styles t)))
1794 (fmt1 (car fmt))
1795 (fmt2 (cadr fmt)))
1796 (org-odt-format-tags
1797 '("<text:sequence-ref text:reference-format=\"%s\" text:ref-name=\"%s\">"
1798 . "</text:sequence-ref>")
1799 (format-spec fmt2 `((?e . ,category)
1800 (?n . ,(format "%d" seqno)))) fmt1 label))))
1802 (defun org-odt-fixup-label-references ()
1803 (goto-char (point-min))
1804 (while (re-search-forward
1805 "<text:sequence-ref text:ref-name=\"\\([^\"]+\\)\"/>" nil t)
1806 (let* ((label (match-string 1))
1807 (label-def (assoc label org-odt-entity-labels-alist))
1808 (rpl (and label-def
1809 (apply 'org-odt-format-label-reference label-def))))
1810 (if rpl (replace-match rpl t t)
1811 (org-lparse-warn
1812 (format "Unable to resolve reference to label \"%s\"" label))))))
1814 (defun org-odt-format-entity-caption (label caption category)
1815 (or (and label
1816 (apply 'org-odt-format-label-definition
1817 caption (org-odt-add-label-definition label category)))
1818 caption ""))
1820 (defun org-odt-format-tags (tag text &rest args)
1821 (let ((prefix (when org-lparse-encode-pending "@"))
1822 (suffix (when org-lparse-encode-pending "@")))
1823 (apply 'org-lparse-format-tags tag text prefix suffix args)))
1825 (defun org-odt-init-outfile (filename)
1826 (unless (executable-find "zip")
1827 ;; Not at all OSes ship with zip by default
1828 (error "Executable \"zip\" needed for creating OpenDocument files"))
1830 (let* ((outdir (make-temp-file
1831 (format org-export-odt-tmpdir-prefix org-lparse-backend) t))
1832 (content-file (expand-file-name "content.xml" outdir)))
1834 ;; init conten.xml
1835 (with-current-buffer (find-file-noselect content-file t))
1837 ;; reset variables
1838 (setq org-odt-manifest-file-entries nil
1839 org-odt-embedded-images-count 0
1840 org-odt-embedded-formulas-count 0
1841 org-odt-entity-labels-alist nil
1842 org-odt-entity-counts-plist nil)
1843 content-file))
1845 (defcustom org-export-odt-prettify-xml nil
1846 "Specify whether or not the xml output should be prettified.
1847 When this option is turned on, `indent-region' is run on all
1848 component xml buffers before they are saved. Turn this off for
1849 regular use. Turn this on if you need to examine the xml
1850 visually."
1851 :group 'org-export-odt
1852 :type 'boolean)
1854 (defvar hfy-user-sheet-assoc) ; bound during org-do-lparse
1855 (defun org-odt-save-as-outfile (target opt-plist)
1856 ;; write meta file
1857 (org-odt-update-meta-file opt-plist)
1859 ;; write styles file
1860 (when (equal org-lparse-backend 'odt)
1861 (org-odt-update-styles-file opt-plist))
1863 ;; create mimetype file
1864 (let ((mimetype (org-odt-write-mimetype-file org-lparse-backend)))
1865 (org-odt-create-manifest-file-entry mimetype "/" "1.2"))
1867 ;; create a manifest entry for content.xml
1868 (org-odt-create-manifest-file-entry "text/xml" "content.xml")
1870 ;; write out the manifest entries before zipping
1871 (org-odt-write-manifest-file)
1873 (let ((xml-files '("mimetype" "META-INF/manifest.xml" "content.xml"
1874 "meta.xml"))
1875 (zipdir default-directory))
1876 (when (equal org-lparse-backend 'odt)
1877 (push "styles.xml" xml-files))
1878 (message "Switching to directory %s" (expand-file-name zipdir))
1880 ;; save all xml files
1881 (mapc (lambda (file)
1882 (with-current-buffer
1883 (find-file-noselect (expand-file-name file) t)
1884 ;; prettify output if needed
1885 (when org-export-odt-prettify-xml
1886 (indent-region (point-min) (point-max)))
1887 (save-buffer 0)))
1888 xml-files)
1890 (let* ((target-name (file-name-nondirectory target))
1891 (target-dir (file-name-directory target))
1892 (cmds `(("zip" "-mX0" ,target-name "mimetype")
1893 ("zip" "-rmTq" ,target-name "."))))
1894 (when (file-exists-p target)
1895 ;; FIXME: If the file is locked this throws a cryptic error
1896 (delete-file target))
1898 (let ((coding-system-for-write 'no-conversion) exitcode err-string)
1899 (message "Creating odt file...")
1900 (mapc
1901 (lambda (cmd)
1902 (message "Running %s" (mapconcat 'identity cmd " "))
1903 (setq err-string
1904 (with-output-to-string
1905 (setq exitcode
1906 (apply 'call-process (car cmd)
1907 nil standard-output nil (cdr cmd)))))
1908 (or (zerop exitcode)
1909 (ignore (message "%s" err-string))
1910 (error "Unable to create odt file (%S)" exitcode)))
1911 cmds))
1913 ;; move the file from outdir to target-dir
1914 (rename-file target-name target-dir)
1916 ;; kill all xml buffers
1917 (mapc (lambda (file)
1918 (kill-buffer
1919 (find-file-noselect (expand-file-name file zipdir) t)))
1920 xml-files)
1922 (delete-directory zipdir)))
1923 (message "Created %s" target)
1924 (set-buffer (find-file-noselect target t)))
1926 (defconst org-odt-manifest-file-entry-tag
1928 <manifest:file-entry manifest:media-type=\"%s\" manifest:full-path=\"%s\"%s/>")
1930 (defvar org-odt-manifest-file-entries nil)
1932 (defun org-odt-create-manifest-file-entry (&rest args)
1933 (push args org-odt-manifest-file-entries))
1935 (defun org-odt-write-manifest-file ()
1936 (make-directory "META-INF")
1937 (let ((manifest-file (expand-file-name "META-INF/manifest.xml")))
1938 (write-region
1939 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
1940 <manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"1.2\">\n"
1941 nil manifest-file)
1942 (mapc
1943 (lambda (file-entry)
1944 (let* ((version (nth 2 file-entry))
1945 (extra (if version
1946 (format " manifest:version=\"%s\"" version)
1947 "")))
1948 (write-region
1949 (format org-odt-manifest-file-entry-tag
1950 (nth 0 file-entry) (nth 1 file-entry) extra)
1951 nil manifest-file t))) org-odt-manifest-file-entries)
1952 (write-region "\n</manifest:manifest>" nil manifest-file t)))
1954 (defun org-odt-update-meta-file (opt-plist)
1955 (let ((date (org-odt-iso-date-from-org-timestamp
1956 (plist-get opt-plist :date)))
1957 (author (or (plist-get opt-plist :author) ""))
1958 (email (plist-get opt-plist :email))
1959 (keywords (plist-get opt-plist :keywords))
1960 (description (plist-get opt-plist :description))
1961 (title (plist-get opt-plist :title)))
1962 (write-region
1963 (concat
1964 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
1965 <office:document-meta
1966 xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"
1967 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
1968 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
1969 xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"
1970 xmlns:ooo=\"http://openoffice.org/2004/office\"
1971 office:version=\"1.2\">
1972 <office:meta>" "\n"
1973 (org-odt-format-author)
1974 (org-odt-format-tags
1975 '("\n<meta:initial-creator>" . "</meta:initial-creator>") author)
1976 (org-odt-format-tags '("\n<dc:date>" . "</dc:date>") date)
1977 (org-odt-format-tags
1978 '("\n<meta:creation-date>" . "</meta:creation-date>") date)
1979 (org-odt-format-tags '("\n<meta:generator>" . "</meta:generator>")
1980 (when org-export-creator-info
1981 (format "Org-%s/Emacs-%s"
1982 org-version emacs-version)))
1983 (org-odt-format-tags '("\n<meta:keyword>" . "</meta:keyword>") keywords)
1984 (org-odt-format-tags '("\n<dc:subject>" . "</dc:subject>") description)
1985 (org-odt-format-tags '("\n<dc:title>" . "</dc:title>") title)
1986 "\n"
1987 " </office:meta>" "</office:document-meta>")
1988 nil (expand-file-name "meta.xml")))
1990 ;; create a manifest entry for meta.xml
1991 (org-odt-create-manifest-file-entry "text/xml" "meta.xml"))
1993 (defun org-odt-update-styles-file (opt-plist)
1994 ;; write styles file
1995 (let ((styles-file (plist-get opt-plist :odt-styles-file)))
1996 (org-odt-copy-styles-file (and styles-file
1997 (read (org-trim styles-file)))))
1999 ;; Update styles.xml - take care of outline numbering
2000 (with-current-buffer
2001 (find-file-noselect (expand-file-name "styles.xml") t)
2002 ;; Don't make automatic backup of styles.xml file. This setting
2003 ;; prevents the backedup styles.xml file from being zipped in to
2004 ;; odt file. This is more of a hackish fix. Better alternative
2005 ;; would be to fix the zip command so that the output odt file
2006 ;; includes only the needed files and excludes any auto-generated
2007 ;; extra files like backups and auto-saves etc etc. Note that
2008 ;; currently the zip command zips up the entire temp directory so
2009 ;; that any auto-generated files created under the hood ends up in
2010 ;; the resulting odt file.
2011 (set (make-local-variable 'backup-inhibited) t)
2013 ;; Import local setting of `org-export-with-section-numbers'
2014 (org-lparse-bind-local-variables opt-plist)
2015 (org-odt-configure-outline-numbering
2016 (if org-export-with-section-numbers org-export-headline-levels 0)))
2018 ;; Write custom stlyes for source blocks
2019 (org-odt-insert-custom-styles-for-srcblocks
2020 (mapconcat
2021 (lambda (style)
2022 (format " %s\n" (cddr style)))
2023 hfy-user-sheet-assoc "")))
2025 (defun org-odt-write-mimetype-file (format)
2026 ;; create mimetype file
2027 (let ((mimetype
2028 (case format
2029 (odt "application/vnd.oasis.opendocument.text")
2030 (odf "application/vnd.oasis.opendocument.formula")
2031 (t (error "Unknown OpenDocument backend %S" org-lparse-backend)))))
2032 (write-region mimetype nil (expand-file-name "mimetype"))
2033 mimetype))
2035 (defun org-odt-finalize-outfile ()
2036 (org-odt-delete-empty-paragraphs))
2038 (defun org-odt-delete-empty-paragraphs ()
2039 (goto-char (point-min))
2040 (let ((open "<text:p[^>]*>")
2041 (close "</text:p>"))
2042 (while (re-search-forward (format "%s[ \r\n\t]*%s" open close) nil t)
2043 (replace-match ""))))
2045 (defcustom org-export-odt-convert-processes
2046 '(("BasicODConverter"
2047 ("soffice" "-norestore" "-invisible" "-headless"
2048 "\"macro:///BasicODConverter.Main.Convert(%I,%f,%O)\""))
2049 ("unoconv"
2050 ("unoconv" "-f" "%f" "-o" "%d" "%i")))
2051 "Specify a list of document converters and their usage.
2052 The converters in this list are offered as choices while
2053 customizing `org-export-odt-convert-process'.
2055 This variable is an alist where each element is of the
2056 form (CONVERTER-NAME CONVERTER-PROCESS). CONVERTER-NAME is name
2057 of the converter. CONVERTER-PROCESS specifies the command-line
2058 syntax of the converter and is of the form (CONVERTER-PROGRAM
2059 ARG1 ARG2 ...). CONVERTER-PROGRAM is the name of the executable.
2060 ARG1, ARG2 etc are command line options that are passed to
2061 CONVERTER-PROGRAM. Format specifiers can be used in the ARGs and
2062 they are interpreted as below:
2064 %i input file name in full
2065 %I input file name as a URL
2066 %f format of the output file
2067 %o output file name in full
2068 %O output file name as a URL
2069 %d output dir in full
2070 %D output dir as a URL."
2071 :group 'org-export-odt
2072 :type
2073 '(choice
2074 (const :tag "None" nil)
2075 (alist :tag "Converters"
2076 :key-type (string :tag "Converter Name")
2077 :value-type (group (cons (string :tag "Executable")
2078 (repeat (string :tag "Command line args")))))))
2080 (defcustom org-export-odt-convert-process nil
2081 "Use this converter to convert from \"odt\" format to other formats.
2082 During customization, the list of converter names are populated
2083 from `org-export-odt-convert-processes'."
2084 :group 'org-export-odt
2085 :type '(choice :convert-widget
2086 (lambda (w)
2087 (apply 'widget-convert (widget-type w)
2088 (eval (car (widget-get w :args)))))
2089 `((const :tag "None" nil)
2090 ,@(mapcar (lambda (c)
2091 `(const :tag ,(car c) ,(car c)))
2092 org-export-odt-convert-processes))))
2094 (defcustom org-export-odt-convert-capabilities
2095 '(("Text"
2096 ("odt" "ott" "doc" "rtf")
2097 (("pdf" "pdf") ("odt" "odt") ("xhtml" "html") ("rtf" "rtf")
2098 ("ott" "ott") ("doc" "doc") ("ooxml" "xml") ("html" "html")))
2099 ("Web"
2100 ("html" "xhtml") (("pdf" "pdf") ("odt" "txt") ("html" "html")))
2101 ("Spreadsheet"
2102 ("ods" "ots" "xls" "csv")
2103 (("pdf" "pdf") ("ots" "ots") ("html" "html") ("csv" "csv")
2104 ("ods" "ods") ("xls" "xls") ("xhtml" "xhtml") ("ooxml" "xml")))
2105 ("Presentation"
2106 ("odp" "otp" "ppt")
2107 (("pdf" "pdf") ("swf" "swf") ("odp" "odp") ("xhtml" "xml")
2108 ("otp" "otp") ("ppt" "ppt") ("odg" "odg") ("html" "html"))))
2109 "Specify input and output formats of `org-export-odt-convert-process'.
2110 More correctly, specify the set of input and output formats that
2111 the user is actually interested in.
2113 This variable is an alist where each element is of the
2114 form (DOCUMENT-CLASS INPUT-FMT-LIST OUTPUT-FMT-ALIST).
2115 INPUT-FMT-LIST is a list of INPUT-FMTs. OUTPUT-FMT-ALIST is an
2116 alist where each element is of the form (OUTPUT-FMT
2117 OUTPUT-FILE-EXTENSION).
2119 The variable is interpreted as follows:
2120 `org-export-odt-convert-process' can take any document that is in
2121 INPUT-FMT-LIST and produce any document that is in the
2122 OUTPUT-FMT-LIST. A document converted to OUTPUT-FMT will have
2123 OUTPUT-FILE-EXTENSION as the file name extension. OUTPUT-FMT
2124 serves dual purposes:
2125 - It is used for populating completion candidates during
2126 `org-export-odt-convert' commands.
2127 - It is used as the value of \"%f\" specifier in
2128 `org-export-odt-convert-process'.
2130 DOCUMENT-CLASS is used to group a set of file formats in
2131 INPUT-FMT-LIST in to a single class.
2133 Note that this variable inherently captures how LibreOffice based
2134 converters work. LibreOffice maps documents of various formats
2135 to classes like Text, Web, Spreadsheet, Presentation etc and
2136 allow document of a given class (irrespective of it's source
2137 format) to be converted to any of the export formats associated
2138 with that class.
2140 See default setting of this variable for an typical
2141 configuration."
2142 :group 'org-export-odt
2143 :type
2144 '(choice
2145 (const :tag "None" nil)
2146 (alist :key-type (string :tag "Document Class")
2147 :value-type
2148 (group (repeat :tag "Input formats" (string :tag "Input format"))
2149 (alist :tag "Output formats"
2150 :key-type (string :tag "Output format")
2151 :value-type
2152 (group (string :tag "Output file extension")))))))
2154 ;;;###autoload
2155 (defun org-export-odt-convert (&optional in-file out-fmt prefix-arg)
2156 "Convert IN-FILE to format OUT-FMT using a command line converter.
2157 IN-FILE is the file to be converted. If unspecified, it defaults
2158 to variable `buffer-file-name'. OUT-FMT is the desired output
2159 format. Use `org-export-odt-convert-process' as the converter.
2160 If PREFIX-ARG is non-nil then the newly converted file is opened
2161 using `org-open-file'."
2162 (interactive
2163 (append (org-lparse-convert-read-params) current-prefix-arg))
2164 (org-lparse-do-convert in-file out-fmt prefix-arg))
2166 (defun org-odt-get (what &optional opt-plist)
2167 (case what
2168 (BACKEND 'odt)
2169 (EXPORT-DIR (org-export-directory :html opt-plist))
2170 (FILE-NAME-EXTENSION "odt")
2171 (EXPORT-BUFFER-NAME "*Org ODT Export*")
2172 (ENTITY-CONTROL org-odt-entity-control-callbacks-alist)
2173 (ENTITY-FORMAT org-odt-entity-format-callbacks-alist)
2174 (INIT-METHOD 'org-odt-init-outfile)
2175 (FINAL-METHOD 'org-odt-finalize-outfile)
2176 (SAVE-METHOD 'org-odt-save-as-outfile)
2177 (CONVERT-METHOD
2178 (and org-export-odt-convert-process
2179 (cadr (assoc-string org-export-odt-convert-process
2180 org-export-odt-convert-processes t))))
2181 (CONVERT-CAPABILITIES
2182 (and org-export-odt-convert-process
2183 (cadr (assoc-string org-export-odt-convert-process
2184 org-export-odt-convert-processes t))
2185 org-export-odt-convert-capabilities))
2186 (TOPLEVEL-HLEVEL 1)
2187 (SPECIAL-STRING-REGEXPS org-export-odt-special-string-regexps)
2188 (INLINE-IMAGES 'maybe)
2189 (INLINE-IMAGE-EXTENSIONS '("png" "jpeg" "jpg" "gif" "svg"))
2190 (PLAIN-TEXT-MAP '(("&" . "&amp;") ("<" . "&lt;") (">" . "&gt;")))
2191 (TABLE-FIRST-COLUMN-AS-LABELS nil)
2192 (FOOTNOTE-SEPARATOR (org-lparse-format 'FONTIFY "," 'superscript))
2193 (CODING-SYSTEM-FOR-WRITE 'utf-8)
2194 (CODING-SYSTEM-FOR-SAVE 'utf-8)
2195 (t (error "Unknown property: %s" what))))
2197 (defvar org-lparse-latex-fragment-fallback) ; set by org-do-lparse
2198 (defun org-export-odt-do-preprocess-latex-fragments ()
2199 "Convert LaTeX fragments to images."
2200 (let* ((latex-frag-opt (plist-get org-lparse-opt-plist :LaTeX-fragments))
2201 (latex-frag-opt ; massage the options
2202 (or (and (member latex-frag-opt '(mathjax t))
2203 (not (and (fboundp 'org-format-latex-mathml-available-p)
2204 (org-format-latex-mathml-available-p)))
2205 (prog1 org-lparse-latex-fragment-fallback
2206 (org-lparse-warn
2207 (concat
2208 "LaTeX to MathML converter not available. "
2209 (format "Using %S instead."
2210 org-lparse-latex-fragment-fallback)))))
2211 latex-frag-opt))
2212 cache-dir display-msg)
2213 (cond
2214 ((eq latex-frag-opt 'dvipng)
2215 (setq cache-dir "ltxpng/")
2216 (setq display-msg "Creating LaTeX image %s"))
2217 ((member latex-frag-opt '(mathjax t))
2218 (setq latex-frag-opt 'mathml)
2219 (setq cache-dir "ltxmathml/")
2220 (setq display-msg "Creating MathML formula %s")))
2221 (when (and org-current-export-file)
2222 (org-format-latex
2223 (concat cache-dir (file-name-sans-extension
2224 (file-name-nondirectory org-current-export-file)))
2225 org-current-export-dir nil display-msg
2226 nil nil latex-frag-opt))))
2228 (defadvice org-format-latex-as-mathml
2229 (after org-odt-protect-latex-fragment activate)
2230 "Encode LaTeX fragment as XML.
2231 Do this when translation to MathML fails."
2232 (when (or (not (> (length ad-return-value) 0))
2233 (get-text-property 0 'org-protected ad-return-value))
2234 (setq ad-return-value
2235 (org-propertize (org-odt-encode-plain-text (ad-get-arg 0))
2236 'org-protected t))))
2238 (defun org-export-odt-preprocess-latex-fragments ()
2239 (when (equal org-export-current-backend 'odt)
2240 (org-export-odt-do-preprocess-latex-fragments)))
2242 (defun org-export-odt-preprocess-label-references ()
2243 (goto-char (point-min))
2244 (let (label label-components category value pretty-label)
2245 (while (re-search-forward "\\\\ref{\\([^{}\n]+\\)}" nil t)
2246 (org-if-unprotected-at (match-beginning 1)
2247 (replace-match
2248 (let ((org-lparse-encode-pending t)
2249 (label (match-string 1)))
2250 ;; markup generated below is mostly an eye-candy. At
2251 ;; pre-processing stage, there is no information on which
2252 ;; entity a label reference points to. The actual markup
2253 ;; is generated as part of `org-odt-fixup-label-references'
2254 ;; which gets called at the fag end of export. By this
2255 ;; time we would have seen and collected all the label
2256 ;; definitions in `org-odt-entity-labels-alist'.
2257 (org-odt-format-tags
2258 "<text:sequence-ref text:ref-name=\"%s\"/>" ""
2259 (org-add-props label '(org-protected t)))) t t)))))
2261 ;; process latex fragments as part of
2262 ;; `org-export-preprocess-after-blockquote-hook'. Note that this hook
2263 ;; is the one that is closest and well before the call to
2264 ;; `org-export-attach-captions-and-attributes' in
2265 ;; `org-export-preprocess-stirng'. The above arrangement permits
2266 ;; captions, labels and attributes to be attached to png images
2267 ;; generated out of latex equations.
2268 (add-hook 'org-export-preprocess-after-blockquote-hook
2269 'org-export-odt-preprocess-latex-fragments)
2271 (defun org-export-odt-preprocess (parameters)
2272 (org-export-odt-preprocess-label-references))
2274 (declare-function archive-zip-extract "arc-mode.el" (archive name))
2275 (defun org-odt-zip-extract-one (archive member &optional target)
2276 (require 'arc-mode)
2277 (let* ((target (or target default-directory))
2278 (archive (expand-file-name archive))
2279 (archive-zip-extract
2280 (list "unzip" "-qq" "-o" "-d" target))
2281 exit-code command-output)
2282 (setq command-output
2283 (with-temp-buffer
2284 (setq exit-code (archive-zip-extract archive member))
2285 (buffer-string)))
2286 (unless (zerop exit-code)
2287 (message command-output)
2288 (error "Extraction failed"))))
2290 (defun org-odt-zip-extract (archive members &optional target)
2291 (when (atom members) (setq members (list members)))
2292 (mapc (lambda (member)
2293 (org-odt-zip-extract-one archive member target))
2294 members))
2296 (defun org-odt-copy-styles-file (&optional styles-file)
2297 ;; Non-availability of styles.xml is not a critical error. For now
2298 ;; throw an error purely for aesthetic reasons.
2299 (setq styles-file (or styles-file
2300 org-export-odt-styles-file
2301 (expand-file-name "styles/OrgOdtStyles.xml"
2302 org-odt-data-dir)
2303 (error "org-odt: Missing styles file?")))
2304 (cond
2305 ((listp styles-file)
2306 (let ((archive (nth 0 styles-file))
2307 (members (nth 1 styles-file)))
2308 (org-odt-zip-extract archive members)
2309 (mapc
2310 (lambda (member)
2311 (when (org-file-image-p member)
2312 (let* ((image-type (file-name-extension member))
2313 (media-type (format "image/%s" image-type)))
2314 (org-odt-create-manifest-file-entry media-type member))))
2315 members)))
2316 ((and (stringp styles-file) (file-exists-p styles-file))
2317 (let ((styles-file-type (file-name-extension styles-file)))
2318 (cond
2319 ((string= styles-file-type "xml")
2320 (copy-file styles-file "styles.xml" t))
2321 ((member styles-file-type '("odt" "ott"))
2322 (org-odt-zip-extract styles-file "styles.xml")))))
2324 (error (format "Invalid specification of styles.xml file: %S"
2325 org-export-odt-styles-file))))
2327 ;; create a manifest entry for styles.xml
2328 (org-odt-create-manifest-file-entry "text/xml" "styles.xml"))
2330 (defvar org-export-odt-factory-settings
2331 "d4328fb9d1b6cb211d4320ff546829f26700dc5e"
2332 "SHA1 hash of OrgOdtStyles.xml.")
2334 (defun org-odt-configure-outline-numbering (level)
2335 "Outline numbering is retained only upto LEVEL.
2336 To disable outline numbering pass a LEVEL of 0."
2337 (goto-char (point-min))
2338 (let ((regex
2339 "<text:outline-level-style\\([^>]*\\)text:level=\"\\([^\"]*\\)\"\\([^>]*\\)>")
2340 (replacement
2341 "<text:outline-level-style\\1text:level=\"\\2\" style:num-format=\"\">"))
2342 (while (re-search-forward regex nil t)
2343 (when (> (string-to-number (match-string 2)) level)
2344 (replace-match replacement t nil))))
2345 (save-buffer 0))
2347 ;;;###autoload
2348 (defun org-export-as-odf (latex-frag &optional odf-file)
2349 "Export LATEX-FRAG as OpenDocument formula file ODF-FILE.
2350 Use `org-create-math-formula' to convert LATEX-FRAG first to
2351 MathML. When invoked as an interactive command, use
2352 `org-latex-regexps' to infer LATEX-FRAG from currently active
2353 region. If no LaTeX fragments are found, prompt for it. Push
2354 MathML source to kill ring, if `org-export-copy-to-kill-ring' is
2355 non-nil."
2356 (interactive
2357 `(,(let (frag)
2358 (setq frag (and (setq frag (and (region-active-p)
2359 (buffer-substring (region-beginning)
2360 (region-end))))
2361 (loop for e in org-latex-regexps
2362 thereis (when (string-match (nth 1 e) frag)
2363 (match-string (nth 2 e) frag)))))
2364 (read-string "LaTeX Fragment: " frag nil frag))
2365 ,(let ((odf-filename (expand-file-name
2366 (concat
2367 (file-name-sans-extension
2368 (or (file-name-nondirectory buffer-file-name)))
2369 "." "odf")
2370 (file-name-directory buffer-file-name))))
2371 (message "default val is %s" odf-filename)
2372 (read-file-name "ODF filename: " nil odf-filename nil
2373 (file-name-nondirectory odf-filename)))))
2374 (let* ((org-lparse-backend 'odf)
2375 org-lparse-opt-plist
2376 (filename (or odf-file
2377 (expand-file-name
2378 (concat
2379 (file-name-sans-extension
2380 (or (file-name-nondirectory buffer-file-name)))
2381 "." "odf")
2382 (file-name-directory buffer-file-name))))
2383 (buffer (find-file-noselect (org-odt-init-outfile filename)))
2384 (coding-system-for-write 'utf-8)
2385 (save-buffer-coding-system 'utf-8))
2386 (set-buffer buffer)
2387 (set-buffer-file-coding-system coding-system-for-write)
2388 (let ((mathml (org-create-math-formula latex-frag)))
2389 (unless mathml (error "No Math formula created"))
2390 (insert mathml)
2391 (or (org-export-push-to-kill-ring
2392 (upcase (symbol-name org-lparse-backend)))
2393 (message "Exporting... done")))
2394 (org-odt-save-as-outfile filename nil)))
2396 ;;;###autoload
2397 (defun org-export-as-odf-and-open ()
2398 "Export LaTeX fragment as OpenDocument formula and immediately open it.
2399 Use `org-export-as-odf' to read LaTeX fragment and OpenDocument
2400 formula file."
2401 (interactive)
2402 (org-lparse-and-open
2403 nil nil nil (call-interactively 'org-export-as-odf)))
2405 (provide 'org-odt)
2407 ;;; org-odt.el ends here