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