Move contrib/odt/styles/*.xml to etc/styles
[org-mode.git] / contrib / lisp / org-odt.el
blobcdfb0237a260593425280f67c2016d0502600ed0
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 max-level)
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=\"%d\">
916 <text:index-title-template text:style-name=\"Contents_20_Heading\">%s</text:index-title-template>
917 " max-level lang-specific-heading))
918 (loop for level from 1 upto 10
919 do (insert (format
921 <text:table-of-content-entry-template text:outline-level=\"%d\" text:style-name=\"Contents_20_%d\">
922 <text:index-entry-link-start text:style-name=\"Internet_20_link\"/>
923 <text:index-entry-chapter/>
924 <text:index-entry-text/>
925 <text:index-entry-link-end/>
926 </text:table-of-content-entry-template>
927 " level level)))
929 (insert
930 (format "
931 </text:table-of-content-source>
933 <text:index-body>
934 <text:index-title text:style-name=\"Sect1\" text:name=\"Table of Contents1_Head\">
935 <text:p text:style-name=\"Contents_20_Heading\">%s</text:p>
936 </text:index-title>
937 " lang-specific-heading)))
939 (defun org-odt-end-toc ()
940 (insert "
941 </text:index-body>
942 </text:table-of-content>
945 (defun org-odt-format-toc-entry (snumber todo headline tags href)
946 (setq headline (concat
947 (and org-export-with-section-numbers
948 (concat snumber ". "))
949 headline
950 (and tags
951 (concat
952 (org-lparse-format 'SPACES 3)
953 (org-lparse-format 'FONTIFY tags "tag")))))
954 (when todo
955 (setq headline (org-lparse-format 'FONTIFY headline "todo")))
957 (let ((org-odt-suppress-xref t))
958 (org-odt-format-link headline (concat "#" href))))
960 (defun org-odt-format-toc-item (toc-entry level org-last-level)
961 (let ((style (format "Contents_20_%d"
962 (+ level (or (org-lparse-get 'TOPLEVEL-HLEVEL) 1) -1))))
963 (insert "\n" (org-odt-format-stylized-paragraph style toc-entry) "\n")))
965 ;; Following variable is let bound during 'ORG-LINK callback. See
966 ;; org-html.el
967 (defvar org-lparse-link-description-is-image nil)
968 (defun org-odt-format-link (desc href &optional attr)
969 (cond
970 ((and (= (string-to-char href) ?#) (not org-odt-suppress-xref))
971 (setq href (concat org-export-odt-bookmark-prefix (substring href 1)))
972 (let ((xref-format "text"))
973 (when (numberp desc)
974 (setq desc (format "%d" desc) xref-format "number"))
975 (org-odt-format-tags
976 '("<text:bookmark-ref text:reference-format=\"%s\" text:ref-name=\"%s\">" .
977 "</text:bookmark-ref>")
978 desc xref-format href)))
979 (org-lparse-link-description-is-image
980 (org-odt-format-tags
981 '("<draw:a xlink:type=\"simple\" xlink:href=\"%s\" %s>" . "</draw:a>")
982 desc href (or attr "")))
984 (org-odt-format-tags
985 '("<text:a xlink:type=\"simple\" xlink:href=\"%s\" %s>" . "</text:a>")
986 desc href (or attr "")))))
988 (defun org-odt-format-spaces (n)
989 (cond
990 ((= n 1) " ")
991 ((> n 1) (concat
992 " " (org-odt-format-tags "<text:s text:c=\"%d\"/>" "" (1- n))))
993 (t "")))
995 (defun org-odt-format-tabs (&optional n)
996 (let ((tab "<text:tab/>")
997 (n (or n 1)))
998 (insert tab)))
1000 (defun org-odt-format-line-break ()
1001 (org-odt-format-tags "<text:line-break/>" ""))
1003 (defun org-odt-format-horizontal-line ()
1004 (org-odt-format-stylized-paragraph 'horizontal-line ""))
1006 (defun org-odt-encode-plain-text (line &optional no-whitespace-filling)
1007 (setq line (org-xml-encode-plain-text line))
1008 (if no-whitespace-filling line
1009 (org-odt-fill-tabs-and-spaces line)))
1011 (defun org-odt-format-line (line)
1012 (case org-lparse-dyn-current-environment
1013 (fixedwidth (concat
1014 (org-odt-format-stylized-paragraph
1015 'fixedwidth (org-odt-encode-plain-text line)) "\n"))
1016 (t (concat line "\n"))))
1018 (defun org-odt-format-comment (fmt &rest args)
1019 (let ((comment (apply 'format fmt args)))
1020 (format "\n<!-- %s -->\n" comment)))
1022 (defun org-odt-format-org-entity (wd)
1023 (org-entity-get-representation wd 'utf8))
1025 (defun org-odt-fill-tabs-and-spaces (line)
1026 (replace-regexp-in-string
1027 "\\([\t]\\|\\([ ]+\\)\\)" (lambda (s)
1028 (cond
1029 ((string= s "\t") (org-odt-format-tabs))
1030 (t (org-odt-format-spaces (length s))))) line))
1032 (defcustom org-export-odt-fontify-srcblocks t
1033 "Specify whether or not source blocks need to be fontified.
1034 Turn this option on if you want to colorize the source code
1035 blocks in the exported file. For colorization to work, you need
1036 to make available an enhanced version of `htmlfontify' library."
1037 :type 'boolean
1038 :group 'org-export-odt)
1040 (defun org-odt-format-source-line-with-line-number-and-label
1041 (line rpllbl num fontifier par-style)
1043 (let ((keep-label (not (numberp rpllbl)))
1044 (ref (org-find-text-property-in-string 'org-coderef line)))
1045 (setq line (concat line (and keep-label ref (format "(%s)" ref))))
1046 (setq line (funcall fontifier line))
1047 (when ref
1048 (setq line (org-odt-format-target line (concat "coderef-" ref))))
1049 (setq line (org-odt-format-stylized-paragraph par-style line))
1050 (if (not num) line
1051 (org-odt-format-tags '("<text:list-item>" . "</text:list-item>") line))))
1053 (defun org-odt-format-source-code-or-example-plain
1054 (lines lang caption textareap cols rows num cont rpllbl fmt)
1055 "Format source or example blocks much like fixedwidth blocks.
1056 Use this when `org-export-odt-fontify-srcblocks' option is turned
1057 off."
1058 (let* ((lines (org-split-string lines "[\r\n]"))
1059 (line-count (length lines))
1060 (i 0))
1061 (mapconcat
1062 (lambda (line)
1063 (incf i)
1064 (org-odt-format-source-line-with-line-number-and-label
1065 line rpllbl num 'org-odt-encode-plain-text
1066 (if (= i line-count) "OrgFixedWidthBlockLastLine"
1067 "OrgFixedWidthBlock")))
1068 lines "\n")))
1070 (defvar org-src-block-paragraph-format
1071 "<style:style style:name=\"OrgSrcBlock\" style:family=\"paragraph\" style:parent-style-name=\"Preformatted_20_Text\">
1072 <style:paragraph-properties fo:background-color=\"%s\" fo:padding=\"0.049cm\" fo:border=\"0.51pt solid #000000\" style:shadow=\"none\">
1073 <style:background-image/>
1074 </style:paragraph-properties>
1075 <style:text-properties fo:color=\"%s\"/>
1076 </style:style>"
1077 "Custom paragraph style for colorized source and example blocks.
1078 This style is much the same as that of \"OrgFixedWidthBlock\"
1079 except that the foreground and background colors are set
1080 according to the default face identified by the `htmlfontify'.")
1082 (defun org-odt-hfy-face-to-css (fn)
1083 "Create custom style for face FN.
1084 When FN is the default face, use it's foreground and background
1085 properties to create \"OrgSrcBlock\" paragraph style. Otherwise
1086 use it's color attribute to create a character style whose name
1087 is obtained from FN. Currently all attributes of FN other than
1088 color are ignored.
1090 The style name for a face FN is derived using the following
1091 operations on the face name in that order - de-dash, CamelCase
1092 and prefix with \"OrgSrc\". For example,
1093 `font-lock-function-name-face' is associated with
1094 \"OrgSrcFontLockFunctionNameFace\"."
1095 (let* ((css-list (hfy-face-to-style fn))
1096 (style-name ((lambda (fn)
1097 (concat "OrgSrc"
1098 (mapconcat
1099 'capitalize (split-string
1100 (hfy-face-or-def-to-name fn) "-")
1101 ""))) fn))
1102 (color-val (cdr (assoc "color" css-list)))
1103 (background-color-val (cdr (assoc "background" css-list)))
1104 (style (and org-export-odt-create-custom-styles-for-srcblocks
1105 (cond
1106 ((eq fn 'default)
1107 (format org-src-block-paragraph-format
1108 background-color-val color-val))
1110 (format
1112 <style:style style:name=\"%s\" style:family=\"text\">
1113 <style:text-properties fo:color=\"%s\"/>
1114 </style:style>" style-name color-val))))))
1115 (cons style-name style)))
1117 (defcustom org-export-odt-create-custom-styles-for-srcblocks t
1118 "Whether custom styles for colorized source blocks be automatically created.
1119 When this option is turned on, the exporter creates custom styles
1120 for source blocks based on the advice of `htmlfontify'. Creation
1121 of custom styles happen as part of `org-odt-hfy-face-to-css'.
1123 When this option is turned off exporter does not create such
1124 styles.
1126 Use the latter option if you do not want the custom styles to be
1127 based on your current display settings. It is necessary that the
1128 styles.xml already contains needed styles for colorizing to work.
1130 This variable is effective only if
1131 `org-export-odt-fontify-srcblocks' is turned on."
1132 :group 'org-export-odt
1133 :type 'boolean)
1135 (defun org-odt-insert-custom-styles-for-srcblocks (styles)
1136 "Save STYLES used for colorizing of source blocks.
1137 Update styles.xml with styles that were collected as part of
1138 `org-odt-hfy-face-to-css' callbacks."
1139 (when styles
1140 (with-current-buffer
1141 (find-file-noselect (expand-file-name "styles.xml") t)
1142 (goto-char (point-min))
1143 (when (re-search-forward "</office:styles>" nil t)
1144 (goto-char (match-beginning 0))
1145 (insert "\n<!-- Org Htmlfontify Styles -->\n" styles "\n")))))
1147 (defun org-odt-format-source-code-or-example-colored
1148 (lines lang caption textareap cols rows num cont rpllbl fmt)
1149 "Format source or example blocks using `htmlfontify-string'.
1150 Use this routine when `org-export-odt-fontify-srcblocks' option
1151 is turned on."
1152 (let* ((lang-m (and lang (or (cdr (assoc lang org-src-lang-modes)) lang)))
1153 (mode (and lang-m (intern (concat (if (symbolp lang-m)
1154 (symbol-name lang-m)
1155 lang-m) "-mode"))))
1156 (org-inhibit-startup t)
1157 (org-startup-folded nil)
1158 (lines (with-temp-buffer
1159 (insert lines)
1160 (if (functionp mode) (funcall mode) (fundamental-mode))
1161 (font-lock-fontify-buffer)
1162 (buffer-string)))
1163 (hfy-html-quote-regex "\\([<\"&> ]\\)")
1164 (hfy-html-quote-map '(("\"" "&quot;")
1165 ("<" "&lt;")
1166 ("&" "&amp;")
1167 (">" "&gt;")
1168 (" " "<text:s/>")
1169 (" " "<text:tab/>")))
1170 (hfy-face-to-css 'org-odt-hfy-face-to-css)
1171 (hfy-optimisations-1 (copy-seq hfy-optimisations))
1172 (hfy-optimisations (add-to-list 'hfy-optimisations-1
1173 'body-text-only))
1174 (hfy-begin-span-handler
1175 (lambda (style text-block text-id text-begins-block-p)
1176 (insert (format "<text:span text:style-name=\"%s\">" style))))
1177 (hfy-end-span-handler (lambda nil (insert "</text:span>"))))
1178 (when (fboundp 'htmlfontify-string)
1179 (let* ((lines (org-split-string lines "[\r\n]"))
1180 (line-count (length lines))
1181 (i 0))
1182 (mapconcat
1183 (lambda (line)
1184 (incf i)
1185 (org-odt-format-source-line-with-line-number-and-label
1186 line rpllbl num 'htmlfontify-string
1187 (if (= i line-count) "OrgSrcBlockLastLine" "OrgSrcBlock")))
1188 lines "\n")))))
1190 (defun org-odt-format-source-code-or-example (lines lang caption textareap
1191 cols rows num cont
1192 rpllbl fmt)
1193 "Format source or example blocks for export.
1194 Use `org-odt-format-source-code-or-example-plain' or
1195 `org-odt-format-source-code-or-example-colored' depending on the
1196 value of `org-export-odt-fontify-srcblocks."
1197 (setq lines (org-export-number-lines
1198 lines 0 0 num cont rpllbl fmt 'preprocess)
1199 lines (funcall
1200 (or (and org-export-odt-fontify-srcblocks
1201 (or (featurep 'htmlfontify)
1202 (require 'htmlfontify))
1203 (fboundp 'htmlfontify-string)
1204 'org-odt-format-source-code-or-example-colored)
1205 'org-odt-format-source-code-or-example-plain)
1206 lines lang caption textareap cols rows num cont rpllbl fmt))
1207 (if (not num) lines
1208 (let ((extra (format " text:continue-numbering=\"%s\""
1209 (if cont "true" "false"))))
1210 (org-odt-format-tags
1211 '("<text:list text:style-name=\"OrgSrcBlockNumberedLine\"%s>"
1212 . "</text:list>") lines extra))))
1214 (defun org-odt-remap-stylenames (style-name)
1216 (cdr (assoc style-name '(("timestamp-wrapper" . "OrgTimestampWrapper")
1217 ("timestamp" . "OrgTimestamp")
1218 ("timestamp-kwd" . "OrgTimestampKeyword")
1219 ("tag" . "OrgTag")
1220 ("todo" . "OrgTodo")
1221 ("done" . "OrgDone")
1222 ("target" . "OrgTarget"))))
1223 style-name))
1225 (defun org-odt-format-fontify (text style &optional id)
1226 (let* ((style-name
1227 (cond
1228 ((stringp style)
1229 (org-odt-remap-stylenames style))
1230 ((symbolp style)
1231 (org-odt-get-style-name-for-entity 'character style))
1232 ((listp style)
1233 (assert (< 1 (length style)))
1234 (let ((parent-style (pop style)))
1235 (mapconcat (lambda (s)
1236 ;; (assert (stringp s) t)
1237 (org-odt-remap-stylenames s)) style "")
1238 (org-odt-remap-stylenames parent-style)))
1239 (t (error "Don't how to handle style %s" style)))))
1240 (org-odt-format-tags
1241 '("<text:span text:style-name=\"%s\">" . "</text:span>")
1242 text style-name)))
1244 (defun org-odt-relocate-relative-path (path dir)
1245 (if (file-name-absolute-p path) path
1246 (file-relative-name (expand-file-name path dir)
1247 (expand-file-name "eyecandy" dir))))
1249 (defun org-odt-format-inline-image (thefile)
1250 (let* ((thelink (if (file-name-absolute-p thefile) thefile
1251 (org-xml-format-href
1252 (org-odt-relocate-relative-path
1253 thefile org-current-export-file))))
1254 (href
1255 (org-odt-format-tags
1256 "<draw:image xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>" ""
1257 (if org-export-odt-embed-images
1258 (org-odt-copy-image-file thefile) thelink))))
1259 (org-export-odt-format-image thefile href)))
1261 (defun org-export-odt-format-formula (src href &optional embed-as)
1262 "Create image tag with source and attributes."
1263 (save-match-data
1264 (let* ((caption (org-find-text-property-in-string 'org-caption src))
1265 (caption (and caption (org-xml-format-desc caption)))
1266 (label (org-find-text-property-in-string 'org-label src))
1267 (latex-frag (org-find-text-property-in-string 'org-latex-src src))
1268 (embed-as (or embed-as
1269 (and latex-frag
1270 (org-find-text-property-in-string
1271 'org-latex-src-embed-type src))
1272 (if (or caption label) 'paragraph 'character)))
1273 width height)
1274 (when latex-frag
1275 (setq href (org-propertize href :title "LaTeX Fragment"
1276 :description latex-frag)))
1277 (cond
1278 ((eq embed-as 'character)
1279 (org-odt-format-entity "InlineFormula" href width height))
1281 (org-lparse-end-paragraph)
1282 (org-lparse-insert-list-table
1283 `((,(org-odt-format-entity
1284 (if caption "CaptionedDisplayFormula" "DisplayFormula")
1285 href width height caption nil)
1286 ,(if (not label) ""
1287 (org-odt-format-entity-caption label nil "__MathFormula__"))))
1288 nil nil nil "OrgEquation" nil '((1 "c" 8) (2 "c" 1)))
1289 (throw 'nextline nil))))))
1291 (defvar org-odt-embedded-formulas-count 0)
1292 (defun org-odt-copy-formula-file (path)
1293 "Returns the internal name of the file"
1294 (let* ((src-file (expand-file-name
1295 path (file-name-directory org-current-export-file)))
1296 (target-dir (format "Formula-%04d/"
1297 (incf org-odt-embedded-formulas-count)))
1298 (target-file (concat target-dir "content.xml")))
1299 (when (not org-lparse-to-buffer)
1300 (message "Embedding %s as %s ..."
1301 (substring-no-properties path) target-file)
1303 (make-directory target-dir)
1304 (org-odt-create-manifest-file-entry
1305 "application/vnd.oasis.opendocument.formula" target-dir "1.2")
1307 (case (org-odt-is-formula-link-p src-file)
1308 (mathml
1309 (copy-file src-file target-file 'overwrite))
1310 (odf
1311 (org-odt-zip-extract-one src-file "content.xml" target-dir))
1313 (error "%s is not a formula file" src-file)))
1315 (org-odt-create-manifest-file-entry "text/xml" target-file))
1316 target-file))
1318 (defun org-odt-format-inline-formula (thefile)
1319 (let* ((thelink (if (file-name-absolute-p thefile) thefile
1320 (org-xml-format-href
1321 (org-odt-relocate-relative-path
1322 thefile org-current-export-file))))
1323 (href
1324 (org-odt-format-tags
1325 "<draw:object xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>" ""
1326 (file-name-directory (org-odt-copy-formula-file thefile)))))
1327 (org-export-odt-format-formula thefile href)))
1329 (defun org-odt-is-formula-link-p (file)
1330 (let ((case-fold-search nil))
1331 (cond
1332 ((string-match "\\.\\(mathml\\|mml\\)\\'" file)
1333 'mathml)
1334 ((string-match "\\.odf\\'" file)
1335 'odf))))
1337 (defun org-odt-format-org-link (opt-plist type-1 path fragment desc attr
1338 descp)
1339 "Make a OpenDocument link.
1340 OPT-PLIST is an options list.
1341 TYPE-1 is the device-type of the link (THIS://foo.html).
1342 PATH is the path of the link (http://THIS#location).
1343 FRAGMENT is the fragment part of the link, if any (foo.html#THIS).
1344 DESC is the link description, if any.
1345 ATTR is a string of other attributes of the a element."
1346 (declare (special org-lparse-par-open))
1347 (save-match-data
1348 (let* ((may-inline-p
1349 (and (member type-1 '("http" "https" "file"))
1350 (org-lparse-should-inline-p path descp)
1351 (not fragment)))
1352 (type (if (equal type-1 "id") "file" type-1))
1353 (filename path)
1354 (thefile path))
1355 (cond
1356 ;; check for inlined images
1357 ((and (member type '("file"))
1358 (not fragment)
1359 (org-file-image-p
1360 filename org-export-odt-inline-image-extensions)
1361 (or (eq t org-export-odt-inline-images)
1362 (and org-export-odt-inline-images (not descp))))
1363 (org-odt-format-inline-image thefile))
1364 ;; check for embedded formulas
1365 ((and (member type '("file"))
1366 (not fragment)
1367 (org-odt-is-formula-link-p filename)
1368 (or (not descp)))
1369 (org-odt-format-inline-formula thefile))
1370 ((string= type "coderef")
1371 (let* ((ref fragment)
1372 (lineno-or-ref (cdr (assoc ref org-export-code-refs)))
1373 (desc (and descp desc))
1374 (org-odt-suppress-xref nil)
1375 (href (org-xml-format-href (concat "#coderef-" ref))))
1376 (cond
1377 ((and (numberp lineno-or-ref) (not desc))
1378 (org-odt-format-link lineno-or-ref href))
1379 ((and (numberp lineno-or-ref) desc
1380 (string-match (regexp-quote (concat "(" ref ")")) desc))
1381 (format (replace-match "%s" t t desc)
1382 (org-odt-format-link lineno-or-ref href)))
1384 (setq desc (format
1385 (if (and desc (string-match
1386 (regexp-quote (concat "(" ref ")"))
1387 desc))
1388 (replace-match "%s" t t desc)
1389 (or desc "%s"))
1390 lineno-or-ref))
1391 (org-odt-format-link (org-xml-format-desc desc) href)))))
1393 (when (string= type "file")
1394 (setq thefile
1395 (cond
1396 ((file-name-absolute-p path)
1397 (concat "file://" (expand-file-name path)))
1398 (t (org-odt-relocate-relative-path
1399 thefile org-current-export-file)))))
1401 (when (and (member type '("" "http" "https" "file")) fragment)
1402 (setq thefile (concat thefile "#" fragment)))
1404 (setq thefile (org-xml-format-href thefile))
1406 (when (not (member type '("" "file")))
1407 (setq thefile (concat type ":" thefile)))
1409 (let ((org-odt-suppress-xref nil))
1410 (org-odt-format-link
1411 (org-xml-format-desc desc) thefile attr)))))))
1413 (defun org-odt-format-heading (text level &optional id)
1414 (let* ((text (if id (org-odt-format-target text id) text)))
1415 (org-odt-format-tags
1416 '("<text:h text:style-name=\"Heading_20_%s\" text:outline-level=\"%s\">" .
1417 "</text:h>") text level level)))
1419 (defun org-odt-format-headline (title extra-targets tags
1420 &optional snumber level)
1421 (concat
1422 (org-lparse-format 'EXTRA-TARGETS extra-targets)
1424 ;; No need to generate section numbers. They are auto-generated by
1425 ;; the application
1427 ;; (concat (org-lparse-format 'SECTION-NUMBER snumber level) " ")
1428 title
1429 (and tags (concat (org-lparse-format 'SPACES 3)
1430 (org-lparse-format 'ORG-TAGS tags)))))
1432 (defun org-odt-format-anchor (text name &optional class)
1433 (org-odt-format-target text name))
1435 (defun org-odt-format-bookmark (text id)
1436 (if id
1437 (org-odt-format-tags "<text:bookmark text:name=\"%s\"/>" text id)
1438 text))
1440 (defun org-odt-format-target (text id)
1441 (let ((name (concat org-export-odt-bookmark-prefix id)))
1442 (concat
1443 (and id (org-odt-format-tags
1444 "<text:bookmark-start text:name=\"%s\"/>" "" name))
1445 (org-odt-format-bookmark text id)
1446 (and id (org-odt-format-tags
1447 "<text:bookmark-end text:name=\"%s\"/>" "" name)))))
1449 (defun org-odt-format-footnote (n def)
1450 (let ((id (concat "fn" n))
1451 (note-class "footnote")
1452 (par-style "Footnote"))
1453 (org-odt-format-tags
1454 '("<text:note text:id=\"%s\" text:note-class=\"%s\">" .
1455 "</text:note>")
1456 (concat
1457 (org-odt-format-tags
1458 '("<text:note-citation>" . "</text:note-citation>")
1460 (org-odt-format-tags
1461 '("<text:note-body>" . "</text:note-body>")
1462 def))
1463 id note-class)))
1465 (defun org-odt-format-footnote-reference (n def refcnt)
1466 (if (= refcnt 1)
1467 (org-odt-format-footnote n def)
1468 (org-odt-format-footnote-ref n)))
1470 (defun org-odt-format-footnote-ref (n)
1471 (let ((note-class "footnote")
1472 (ref-format "text")
1473 (ref-name (concat "fn" n)))
1474 (org-odt-format-tags
1475 '("<text:span text:style-name=\"%s\">" . "</text:span>")
1476 (org-odt-format-tags
1477 '("<text:note-ref text:note-class=\"%s\" text:reference-format=\"%s\" text:ref-name=\"%s\">" . "</text:note-ref>")
1478 n note-class ref-format ref-name)
1479 "OrgSuperscript")))
1481 (defun org-odt-get-image-name (file-name)
1482 (require 'sha1)
1483 (file-relative-name
1484 (expand-file-name
1485 (concat (sha1 file-name) "." (file-name-extension file-name)) "Pictures")))
1487 (defun org-export-odt-format-image (src href &optional embed-as)
1488 "Create image tag with source and attributes."
1489 (save-match-data
1490 (let* ((caption (org-find-text-property-in-string 'org-caption src))
1491 (caption (and caption (org-xml-format-desc caption)))
1492 (attr (org-find-text-property-in-string 'org-attributes src))
1493 (label (org-find-text-property-in-string 'org-label src))
1494 (latex-frag (org-find-text-property-in-string
1495 'org-latex-src src))
1496 (category (and latex-frag "__DvipngImage__"))
1497 (embed-as (or embed-as
1498 (if latex-frag
1499 (or (org-find-text-property-in-string
1500 'org-latex-src-embed-type src) 'character)
1501 'paragraph)))
1502 (attr-plist (org-lparse-get-block-params attr))
1503 (size (org-odt-image-size-from-file
1504 src (plist-get attr-plist :width)
1505 (plist-get attr-plist :height)
1506 (plist-get attr-plist :scale) nil embed-as))
1507 (width (car size)) (height (cdr size)))
1508 (when latex-frag
1509 (setq href (org-propertize href :title "LaTeX Fragment"
1510 :description latex-frag)))
1511 (cond
1512 ((not (or caption label))
1513 (case embed-as
1514 (paragraph (org-odt-format-entity "DisplayImage" href width height))
1515 (character (org-odt-format-entity "InlineImage" href width height))
1516 (t (error "Unknown value for embed-as %S" embed-as))))
1518 (org-odt-format-entity
1519 "CaptionedDisplayImage" href width height caption label category))))))
1521 (defun org-odt-format-object-description (title description)
1522 (concat (and title (org-odt-format-tags
1523 '("<svg:title>" . "</svg:title>")
1524 (org-odt-encode-plain-text title t)))
1525 (and description (org-odt-format-tags
1526 '("<svg:desc>" . "</svg:desc>")
1527 (org-odt-encode-plain-text description t)))))
1529 (defun org-odt-format-frame (text width height style &optional
1530 extra anchor-type)
1531 (let ((frame-attrs
1532 (concat
1533 (if width (format " svg:width=\"%0.2fcm\"" width) "")
1534 (if height (format " svg:height=\"%0.2fcm\"" height) "")
1535 extra
1536 (format " text:anchor-type=\"%s\"" (or anchor-type "paragraph")))))
1537 (org-odt-format-tags
1538 '("<draw:frame draw:style-name=\"%s\"%s>" . "</draw:frame>")
1539 (concat text (org-odt-format-object-description
1540 (get-text-property 0 :title text)
1541 (get-text-property 0 :description text)))
1542 style frame-attrs)))
1544 (defun org-odt-format-textbox (text width height style &optional
1545 extra anchor-type)
1546 (org-odt-format-frame
1547 (org-odt-format-tags
1548 '("<draw:text-box %s>" . "</draw:text-box>")
1549 text (concat (format " fo:min-height=\"%0.2fcm\"" (or height .2))
1550 (format " fo:min-width=\"%0.2fcm\"" (or width .2))))
1551 width nil style extra anchor-type))
1553 (defun org-odt-format-inlinetask (heading content
1554 &optional todo priority tags)
1555 (org-odt-format-stylized-paragraph
1556 nil (org-odt-format-textbox
1557 (concat (org-odt-format-stylized-paragraph
1558 "OrgInlineTaskHeading"
1559 (org-lparse-format
1560 'HEADLINE (concat (org-lparse-format-todo todo) " " heading)
1561 nil tags))
1562 content) nil nil "OrgInlineTaskFrame" " style:rel-width=\"100%\"")))
1564 (defvar org-odt-entity-frame-styles
1565 '(("InlineImage" "__Figure__" ("OrgInlineImage" nil "as-char"))
1566 ("DisplayImage" "__Figure__" ("OrgDisplayImage" nil "paragraph"))
1567 ("CaptionedDisplayImage" "__Figure__"
1568 ("OrgCaptionedImage"
1569 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
1570 ("OrgImageCaptionFrame"))
1571 ("InlineFormula" "__MathFormula__" ("OrgInlineFormula" nil "as-char"))
1572 ("DisplayFormula" "__MathFormula__" ("OrgDisplayFormula" nil "as-char"))
1573 ("CaptionedDisplayFormula" "__MathFormula__"
1574 ("OrgCaptionedFormula" nil "paragraph")
1575 ("OrgFormulaCaptionFrame" nil "as-char"))))
1577 (defun org-odt-format-entity (entity href width height
1578 &optional caption label category)
1579 (let* ((entity-style (assoc entity org-odt-entity-frame-styles))
1580 (entity-frame (apply 'org-odt-format-frame
1581 href width height (nth 2 entity-style))))
1582 (if (not (or caption label)) entity-frame
1583 (apply 'org-odt-format-textbox
1584 (org-odt-format-stylized-paragraph
1585 'illustration
1586 (concat entity-frame
1587 (org-odt-format-entity-caption
1588 label caption (or category (nth 1 entity-style)))))
1589 width height (nth 3 entity-style)))))
1591 (defvar org-odt-embedded-images-count 0)
1592 (defun org-odt-copy-image-file (path)
1593 "Returns the internal name of the file"
1594 (let* ((image-type (file-name-extension path))
1595 (media-type (format "image/%s" image-type))
1596 (src-file (expand-file-name
1597 path (file-name-directory org-current-export-file)))
1598 (target-dir "Images/")
1599 (target-file
1600 (format "%s%04d.%s" target-dir
1601 (incf org-odt-embedded-images-count) image-type)))
1602 (when (not org-lparse-to-buffer)
1603 (message "Embedding %s as %s ..."
1604 (substring-no-properties path) target-file)
1606 (when (= 1 org-odt-embedded-images-count)
1607 (make-directory target-dir)
1608 (org-odt-create-manifest-file-entry "" target-dir))
1610 (copy-file src-file target-file 'overwrite)
1611 (org-odt-create-manifest-file-entry media-type target-file))
1612 target-file))
1614 (defvar org-export-odt-image-size-probe-method
1615 '(emacs imagemagick force)
1616 "Ordered list of methods by for determining size of an embedded
1617 image.")
1619 (defvar org-export-odt-default-image-sizes-alist
1620 '(("character" . (5 . 0.4))
1621 ("paragraph" . (5 . 5)))
1622 "Hardcoded image dimensions one for each of the anchor
1623 methods.")
1625 ;; A4 page size is 21.0 by 29.7 cms
1626 ;; The default page settings has 2cm margin on each of the sides. So
1627 ;; the effective text area is 17.0 by 25.7 cm
1628 (defvar org-export-odt-max-image-size '(17.0 . 20.0)
1629 "Limiting dimensions for an embedded image.")
1631 (defun org-odt-do-image-size (probe-method file &optional dpi anchor-type)
1632 (setq dpi (or dpi org-export-odt-pixels-per-inch))
1633 (setq anchor-type (or anchor-type "paragraph"))
1634 (flet ((size-in-cms (size-in-pixels)
1635 (flet ((pixels-to-cms (pixels)
1636 (let* ((cms-per-inch 2.54)
1637 (inches (/ pixels dpi)))
1638 (* cms-per-inch inches))))
1639 (and size-in-pixels
1640 (cons (pixels-to-cms (car size-in-pixels))
1641 (pixels-to-cms (cdr size-in-pixels)))))))
1642 (case probe-method
1643 (emacs
1644 (size-in-cms (ignore-errors (image-size (create-image file) 'pixels))))
1645 (imagemagick
1646 (size-in-cms
1647 (let ((dim (shell-command-to-string
1648 (format "identify -format \"%%w:%%h\" \"%s\"" file))))
1649 (when (string-match "\\([0-9]+\\):\\([0-9]+\\)" dim)
1650 (cons (string-to-number (match-string 1 dim))
1651 (string-to-number (match-string 2 dim)))))))
1653 (cdr (assoc-string anchor-type
1654 org-export-odt-default-image-sizes-alist))))))
1656 (defun org-odt-image-size-from-file (file &optional user-width
1657 user-height scale dpi embed-as)
1658 (unless (file-name-absolute-p file)
1659 (setq file (expand-file-name
1660 file (file-name-directory org-current-export-file))))
1661 (let* (size width height)
1662 (unless (and user-height user-width)
1663 (loop for probe-method in org-export-odt-image-size-probe-method
1664 until size
1665 do (setq size (org-odt-do-image-size
1666 probe-method file dpi embed-as)))
1667 (or size (error "Cannot determine Image size. Aborting ..."))
1668 (setq width (car size) height (cdr size)))
1669 (cond
1670 (scale
1671 (setq width (* width scale) height (* height scale)))
1672 ((and user-height user-width)
1673 (setq width user-width height user-height))
1674 (user-height
1675 (setq width (* user-height (/ width height)) height user-height))
1676 (user-width
1677 (setq height (* user-width (/ height width)) width user-width))
1678 (t (ignore)))
1679 ;; ensure that an embedded image fits comfortably within a page
1680 (let ((max-width (car org-export-odt-max-image-size))
1681 (max-height (cdr org-export-odt-max-image-size)))
1682 (when (or (> width max-width) (> height max-height))
1683 (let* ((scale1 (/ max-width width))
1684 (scale2 (/ max-height height))
1685 (scale (min scale1 scale2)))
1686 (setq width (* scale width) height (* scale height)))))
1687 (cons width height)))
1689 (defvar org-odt-entity-labels-alist nil
1690 "Associate Labels with the Labelled entities.
1691 Each element of the alist is of the form (LABEL-NAME
1692 CATEGORY-NAME SEQNO LABEL-STYLE-NAME). LABEL-NAME is same as
1693 that specified by \"#+LABEL: ...\" line. CATEGORY-NAME is the
1694 type of the entity that LABEL-NAME is attached to. CATEGORY-NAME
1695 can be one of \"Table\", \"Figure\" or \"Equation\". SEQNO is
1696 the unique number assigned to the referenced entity on a
1697 per-CATEGORY basis. It is generated sequentially and is 1-based.
1698 LABEL-STYLE-NAME is a key `org-odt-label-styles'.
1700 See `org-odt-add-label-definition' and
1701 `org-odt-fixup-label-references'.")
1703 (defvar org-odt-entity-counts-plist nil
1704 "Plist of running counters of SEQNOs for each of the CATEGORY-NAMEs.
1705 See `org-odt-entity-labels-alist' for known CATEGORY-NAMEs.")
1707 (defvar org-odt-label-styles
1708 '(("text" "(%n)" "text" "(%n)")
1709 ("category-and-value" "%e %n%c" "category-and-value" "%e %n"))
1710 "Specify how labels are applied and referenced.
1711 This is an alist where each element is of the
1712 form (LABEL-STYLE-NAME LABEL-ATTACH-FMT LABEL-REF-MODE
1713 LABEL-REF-FMT).
1715 LABEL-ATTACH-FMT controls how labels and captions are attached to
1716 an entity. It may contain following specifiers - %e, %n and %c.
1717 %e is replaced with the CATEGORY-NAME. %n is replaced with
1718 \"<text:sequence ...> SEQNO </text:sequence>\". %c is replaced
1719 with CAPTION. See `org-odt-format-label-definition'.
1721 LABEL-REF-MODE and LABEL-REF-FMT controls how label references
1722 are generated. The following XML is generated for a label
1723 reference - \"<text:sequence-ref
1724 text:reference-format=\"LABEL-REF-MODE\" ...> LABEL-REF-FMT
1725 </text:sequence-ref>\". LABEL-REF-FMT may contain following
1726 specifiers - %e and %n. %e is replaced with the CATEGORY-NAME.
1727 %n is replaced with SEQNO. See
1728 `org-odt-format-label-reference'.")
1730 (defvar org-odt-category-map-alist
1731 '(("__Table__" "Table" "category-and-value")
1732 ("__Figure__" "Figure" "category-and-value")
1733 ("__MathFormula__" "Equation" "text")
1734 ("__DvipngImage__" "Equation" "category-and-value"))
1735 "Map a CATEGORY-HANDLE to CATEGORY-NAME and LABEL-STYLE.
1736 This is an alist where each element is of the form
1737 \\(CATEGORY-HANDLE CATEGORY-NAME LABEL-STYLE\\). CATEGORY_HANDLE
1738 could either be one of the internal handles (as seen above) or be
1739 derived from the \"#+LABEL:<label-name>\" specification. See
1740 `org-export-odt-get-category-from-label'. CATEGORY-NAME and
1741 LABEL-STYLE are used for generating ODT labels. See
1742 `org-odt-label-styles'.")
1744 (defvar org-export-odt-user-categories
1745 '("Illustration" "Table" "Text" "Drawing" "Equation" "Figure"))
1747 (defvar org-export-odt-get-category-from-label nil
1748 "Should category of label be inferred from label itself.
1749 When this option is non-nil, a label is parsed in to two
1750 component parts delimited by a \":\" (colon) as shown here -
1751 #+LABEL:[CATEGORY-HANDLE:]EXTRA. The CATEGORY-HANDLE is mapped
1752 to a CATEGORY-NAME and LABEL-STYLE using
1753 `org-odt-category-map-alist'. (If no such map is provided and
1754 CATEGORY-NAME is set to CATEGORY-HANDLE and LABEL-STYLE is set to
1755 \"category-and-value\"). If CATEGORY-NAME so obtained is listed
1756 under `org-export-odt-user-categories' then the user specified
1757 styles are used. Otherwise styles as determined by the internal
1758 CATEGORY-HANDLE is used. See
1759 `org-odt-get-label-category-and-style' for details.")
1761 (defun org-odt-get-label-category-and-style (label default-category)
1762 "See `org-export-odt-get-category-from-label'."
1763 (let ((default-category-map
1764 (assoc default-category org-odt-category-map-alist))
1765 user-category user-category-map category)
1766 (cond
1767 ((not org-export-odt-get-category-from-label)
1768 default-category-map)
1769 ((not (setq user-category
1770 (save-match-data
1771 (and (string-match "\\`\\(.*\\):.+" label)
1772 (match-string 1 label)))))
1773 default-category-map)
1775 (setq user-category-map
1776 (or (assoc user-category org-odt-category-map-alist)
1777 (list nil user-category "category-and-value"))
1778 category (nth 1 user-category-map))
1779 (if (member category org-export-odt-user-categories)
1780 user-category-map
1781 default-category-map)))))
1783 (defun org-odt-add-label-definition (label default-category)
1784 "Create an entry in `org-odt-entity-labels-alist' and return it."
1785 (setq label (substring-no-properties label))
1786 (let* ((label-props (org-odt-get-label-category-and-style
1787 label default-category))
1788 (category (nth 1 label-props))
1789 (counter category)
1790 (label-style (nth 2 label-props))
1791 (sequence-var (intern (mapconcat
1792 'downcase
1793 (org-split-string counter) "-")))
1794 (seqno (1+ (or (plist-get org-odt-entity-counts-plist sequence-var)
1795 0)))
1796 (label-props (list label category seqno label-style)))
1797 (setq org-odt-entity-counts-plist
1798 (plist-put org-odt-entity-counts-plist sequence-var seqno))
1799 (push label-props org-odt-entity-labels-alist)
1800 label-props))
1802 (defun org-odt-format-label-definition (caption label category seqno label-style)
1803 (assert label)
1804 (format-spec
1805 (cadr (assoc-string label-style org-odt-label-styles t))
1806 `((?e . ,category)
1807 (?n . ,(org-odt-format-tags
1808 '("<text:sequence text:ref-name=\"%s\" text:name=\"%s\" text:formula=\"ooow:%s+1\" style:num-format=\"1\">" . "</text:sequence>")
1809 (format "%d" seqno) label category category))
1810 (?c . ,(or (and caption (concat ": " caption)) "")))))
1812 (defun org-odt-format-label-reference (label category seqno label-style)
1813 (assert label)
1814 (save-match-data
1815 (let* ((fmt (cddr (assoc-string label-style org-odt-label-styles t)))
1816 (fmt1 (car fmt))
1817 (fmt2 (cadr fmt)))
1818 (org-odt-format-tags
1819 '("<text:sequence-ref text:reference-format=\"%s\" text:ref-name=\"%s\">"
1820 . "</text:sequence-ref>")
1821 (format-spec fmt2 `((?e . ,category)
1822 (?n . ,(format "%d" seqno)))) fmt1 label))))
1824 (defun org-odt-fixup-label-references ()
1825 (goto-char (point-min))
1826 (while (re-search-forward
1827 "<text:sequence-ref text:ref-name=\"\\([^\"]+\\)\">[ \t\n]*</text:sequence-ref>"
1828 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 (with-current-buffer
1962 (find-file-noselect manifest-file t)
1963 (insert
1964 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
1965 <manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"1.2\">\n")
1966 (mapc
1967 (lambda (file-entry)
1968 (let* ((version (nth 2 file-entry))
1969 (extra (if version
1970 (format " manifest:version=\"%s\"" version)
1971 "")))
1972 (insert
1973 (format org-odt-manifest-file-entry-tag
1974 (nth 0 file-entry) (nth 1 file-entry) extra))))
1975 org-odt-manifest-file-entries)
1976 (insert "\n</manifest:manifest>"))))
1978 (defun org-odt-update-meta-file (opt-plist)
1979 (let ((date (org-odt-iso-date-from-org-timestamp
1980 (plist-get opt-plist :date)))
1981 (author (or (plist-get opt-plist :author) ""))
1982 (email (plist-get opt-plist :email))
1983 (keywords (plist-get opt-plist :keywords))
1984 (description (plist-get opt-plist :description))
1985 (title (plist-get opt-plist :title)))
1986 (write-region
1987 (concat
1988 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
1989 <office:document-meta
1990 xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"
1991 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
1992 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
1993 xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"
1994 xmlns:ooo=\"http://openoffice.org/2004/office\"
1995 office:version=\"1.2\">
1996 <office:meta>" "\n"
1997 (org-odt-format-author)
1998 (org-odt-format-tags
1999 '("\n<meta:initial-creator>" . "</meta:initial-creator>") author)
2000 (org-odt-format-tags '("\n<dc:date>" . "</dc:date>") date)
2001 (org-odt-format-tags
2002 '("\n<meta:creation-date>" . "</meta:creation-date>") date)
2003 (org-odt-format-tags '("\n<meta:generator>" . "</meta:generator>")
2004 (when org-export-creator-info
2005 (format "Org-%s/Emacs-%s"
2006 org-version emacs-version)))
2007 (org-odt-format-tags '("\n<meta:keyword>" . "</meta:keyword>") keywords)
2008 (org-odt-format-tags '("\n<dc:subject>" . "</dc:subject>") description)
2009 (org-odt-format-tags '("\n<dc:title>" . "</dc:title>") title)
2010 "\n"
2011 " </office:meta>" "</office:document-meta>")
2012 nil (expand-file-name "meta.xml")))
2014 ;; create a manifest entry for meta.xml
2015 (org-odt-create-manifest-file-entry "text/xml" "meta.xml"))
2017 (defun org-odt-update-styles-file (opt-plist)
2018 ;; write styles file
2019 (let ((styles-file (plist-get opt-plist :odt-styles-file)))
2020 (org-odt-copy-styles-file (and styles-file
2021 (read (org-trim styles-file)))))
2023 ;; Update styles.xml - take care of outline numbering
2024 (with-current-buffer
2025 (find-file-noselect (expand-file-name "styles.xml") t)
2026 ;; Don't make automatic backup of styles.xml file. This setting
2027 ;; prevents the backedup styles.xml file from being zipped in to
2028 ;; odt file. This is more of a hackish fix. Better alternative
2029 ;; would be to fix the zip command so that the output odt file
2030 ;; includes only the needed files and excludes any auto-generated
2031 ;; extra files like backups and auto-saves etc etc. Note that
2032 ;; currently the zip command zips up the entire temp directory so
2033 ;; that any auto-generated files created under the hood ends up in
2034 ;; the resulting odt file.
2035 (set (make-local-variable 'backup-inhibited) t)
2037 ;; Import local setting of `org-export-with-section-numbers'
2038 (org-lparse-bind-local-variables opt-plist)
2039 (org-odt-configure-outline-numbering
2040 (if org-export-with-section-numbers org-export-headline-levels 0)))
2042 ;; Write custom stlyes for source blocks
2043 (org-odt-insert-custom-styles-for-srcblocks
2044 (mapconcat
2045 (lambda (style)
2046 (format " %s\n" (cddr style)))
2047 hfy-user-sheet-assoc "")))
2049 (defun org-odt-write-mimetype-file (format)
2050 ;; create mimetype file
2051 (let ((mimetype
2052 (case format
2053 (odt "application/vnd.oasis.opendocument.text")
2054 (odf "application/vnd.oasis.opendocument.formula")
2055 (t (error "Unknown OpenDocument backend %S" org-lparse-backend)))))
2056 (write-region mimetype nil (expand-file-name "mimetype"))
2057 mimetype))
2059 (defun org-odt-finalize-outfile ()
2060 (org-odt-delete-empty-paragraphs))
2062 (defun org-odt-delete-empty-paragraphs ()
2063 (goto-char (point-min))
2064 (let ((open "<text:p[^>]*>")
2065 (close "</text:p>"))
2066 (while (re-search-forward (format "%s[ \r\n\t]*%s" open close) nil t)
2067 (replace-match ""))))
2069 (defcustom org-export-odt-convert-processes
2070 '(("BasicODConverter"
2071 ("soffice" "-norestore" "-invisible" "-headless"
2072 "\"macro:///BasicODConverter.Main.Convert(%I,%f,%O)\""))
2073 ("unoconv"
2074 ("unoconv" "-f" "%f" "-o" "%d" "%i")))
2075 "Specify a list of document converters and their usage.
2076 The converters in this list are offered as choices while
2077 customizing `org-export-odt-convert-process'.
2079 This variable is an alist where each element is of the
2080 form (CONVERTER-NAME CONVERTER-PROCESS). CONVERTER-NAME is name
2081 of the converter. CONVERTER-PROCESS specifies the command-line
2082 syntax of the converter and is of the form (CONVERTER-PROGRAM
2083 ARG1 ARG2 ...). CONVERTER-PROGRAM is the name of the executable.
2084 ARG1, ARG2 etc are command line options that are passed to
2085 CONVERTER-PROGRAM. Format specifiers can be used in the ARGs and
2086 they are interpreted as below:
2088 %i input file name in full
2089 %I input file name as a URL
2090 %f format of the output file
2091 %o output file name in full
2092 %O output file name as a URL
2093 %d output dir in full
2094 %D output dir as a URL."
2095 :group 'org-export-odt
2096 :type
2097 '(choice
2098 (const :tag "None" nil)
2099 (alist :tag "Converters"
2100 :key-type (string :tag "Converter Name")
2101 :value-type (group (cons (string :tag "Executable")
2102 (repeat (string :tag "Command line args")))))))
2104 (defcustom org-export-odt-convert-process nil
2105 "Use this converter to convert from \"odt\" format to other formats.
2106 During customization, the list of converter names are populated
2107 from `org-export-odt-convert-processes'."
2108 :group 'org-export-odt
2109 :type '(choice :convert-widget
2110 (lambda (w)
2111 (apply 'widget-convert (widget-type w)
2112 (eval (car (widget-get w :args)))))
2113 `((const :tag "None" nil)
2114 ,@(mapcar (lambda (c)
2115 `(const :tag ,(car c) ,(car c)))
2116 org-export-odt-convert-processes))))
2118 (defcustom org-export-odt-convert-capabilities
2119 '(("Text"
2120 ("odt" "ott" "doc" "rtf")
2121 (("pdf" "pdf") ("odt" "odt") ("xhtml" "html") ("rtf" "rtf")
2122 ("ott" "ott") ("doc" "doc") ("ooxml" "xml") ("html" "html")))
2123 ("Web"
2124 ("html" "xhtml") (("pdf" "pdf") ("odt" "txt") ("html" "html")))
2125 ("Spreadsheet"
2126 ("ods" "ots" "xls" "csv")
2127 (("pdf" "pdf") ("ots" "ots") ("html" "html") ("csv" "csv")
2128 ("ods" "ods") ("xls" "xls") ("xhtml" "xhtml") ("ooxml" "xml")))
2129 ("Presentation"
2130 ("odp" "otp" "ppt")
2131 (("pdf" "pdf") ("swf" "swf") ("odp" "odp") ("xhtml" "xml")
2132 ("otp" "otp") ("ppt" "ppt") ("odg" "odg") ("html" "html"))))
2133 "Specify input and output formats of `org-export-odt-convert-process'.
2134 More correctly, specify the set of input and output formats that
2135 the user is actually interested in.
2137 This variable is an alist where each element is of the
2138 form (DOCUMENT-CLASS INPUT-FMT-LIST OUTPUT-FMT-ALIST).
2139 INPUT-FMT-LIST is a list of INPUT-FMTs. OUTPUT-FMT-ALIST is an
2140 alist where each element is of the form (OUTPUT-FMT
2141 OUTPUT-FILE-EXTENSION).
2143 The variable is interpreted as follows:
2144 `org-export-odt-convert-process' can take any document that is in
2145 INPUT-FMT-LIST and produce any document that is in the
2146 OUTPUT-FMT-LIST. A document converted to OUTPUT-FMT will have
2147 OUTPUT-FILE-EXTENSION as the file name extension. OUTPUT-FMT
2148 serves dual purposes:
2149 - It is used for populating completion candidates during
2150 `org-export-odt-convert' commands.
2151 - It is used as the value of \"%f\" specifier in
2152 `org-export-odt-convert-process'.
2154 DOCUMENT-CLASS is used to group a set of file formats in
2155 INPUT-FMT-LIST in to a single class.
2157 Note that this variable inherently captures how LibreOffice based
2158 converters work. LibreOffice maps documents of various formats
2159 to classes like Text, Web, Spreadsheet, Presentation etc and
2160 allow document of a given class (irrespective of it's source
2161 format) to be converted to any of the export formats associated
2162 with that class.
2164 See default setting of this variable for an typical
2165 configuration."
2166 :group 'org-export-odt
2167 :type
2168 '(choice
2169 (const :tag "None" nil)
2170 (alist :key-type (string :tag "Document Class")
2171 :value-type
2172 (group (repeat :tag "Input formats" (string :tag "Input format"))
2173 (alist :tag "Output formats"
2174 :key-type (string :tag "Output format")
2175 :value-type
2176 (group (string :tag "Output file extension")))))))
2178 ;;;###autoload
2179 (defun org-export-odt-convert (&optional in-file out-fmt prefix-arg)
2180 "Convert IN-FILE to format OUT-FMT using a command line converter.
2181 IN-FILE is the file to be converted. If unspecified, it defaults
2182 to variable `buffer-file-name'. OUT-FMT is the desired output
2183 format. Use `org-export-odt-convert-process' as the converter.
2184 If PREFIX-ARG is non-nil then the newly converted file is opened
2185 using `org-open-file'."
2186 (interactive
2187 (append (org-lparse-convert-read-params) current-prefix-arg))
2188 (org-lparse-do-convert in-file out-fmt prefix-arg))
2190 (defun org-odt-get (what &optional opt-plist)
2191 (case what
2192 (BACKEND 'odt)
2193 (EXPORT-DIR (org-export-directory :html opt-plist))
2194 (FILE-NAME-EXTENSION "odt")
2195 (EXPORT-BUFFER-NAME "*Org ODT Export*")
2196 (ENTITY-CONTROL org-odt-entity-control-callbacks-alist)
2197 (ENTITY-FORMAT org-odt-entity-format-callbacks-alist)
2198 (INIT-METHOD 'org-odt-init-outfile)
2199 (FINAL-METHOD 'org-odt-finalize-outfile)
2200 (SAVE-METHOD 'org-odt-save-as-outfile)
2201 (CONVERT-METHOD
2202 (and org-export-odt-convert-process
2203 (cadr (assoc-string org-export-odt-convert-process
2204 org-export-odt-convert-processes t))))
2205 (CONVERT-CAPABILITIES
2206 (and org-export-odt-convert-process
2207 (cadr (assoc-string org-export-odt-convert-process
2208 org-export-odt-convert-processes t))
2209 org-export-odt-convert-capabilities))
2210 (TOPLEVEL-HLEVEL 1)
2211 (SPECIAL-STRING-REGEXPS org-export-odt-special-string-regexps)
2212 (INLINE-IMAGES 'maybe)
2213 (INLINE-IMAGE-EXTENSIONS '("png" "jpeg" "jpg" "gif" "svg"))
2214 (PLAIN-TEXT-MAP '(("&" . "&amp;") ("<" . "&lt;") (">" . "&gt;")))
2215 (TABLE-FIRST-COLUMN-AS-LABELS nil)
2216 (FOOTNOTE-SEPARATOR (org-lparse-format 'FONTIFY "," 'superscript))
2217 (CODING-SYSTEM-FOR-WRITE 'utf-8)
2218 (CODING-SYSTEM-FOR-SAVE 'utf-8)
2219 (t (error "Unknown property: %s" what))))
2221 (defvar org-lparse-latex-fragment-fallback) ; set by org-do-lparse
2222 (defun org-export-odt-do-preprocess-latex-fragments ()
2223 "Convert LaTeX fragments to images."
2224 (let* ((latex-frag-opt (plist-get org-lparse-opt-plist :LaTeX-fragments))
2225 (latex-frag-opt ; massage the options
2226 (or (and (member latex-frag-opt '(mathjax t))
2227 (not (and (fboundp 'org-format-latex-mathml-available-p)
2228 (org-format-latex-mathml-available-p)))
2229 (prog1 org-lparse-latex-fragment-fallback
2230 (org-lparse-warn
2231 (concat
2232 "LaTeX to MathML converter not available. "
2233 (format "Using %S instead."
2234 org-lparse-latex-fragment-fallback)))))
2235 latex-frag-opt))
2236 cache-dir display-msg)
2237 (cond
2238 ((eq latex-frag-opt 'dvipng)
2239 (setq cache-dir "ltxpng/")
2240 (setq display-msg "Creating LaTeX image %s"))
2241 ((member latex-frag-opt '(mathjax t))
2242 (setq latex-frag-opt 'mathml)
2243 (setq cache-dir "ltxmathml/")
2244 (setq display-msg "Creating MathML formula %s")))
2245 (when (and org-current-export-file)
2246 (org-format-latex
2247 (concat cache-dir (file-name-sans-extension
2248 (file-name-nondirectory org-current-export-file)))
2249 org-current-export-dir nil display-msg
2250 nil nil latex-frag-opt))))
2252 (defadvice org-format-latex-as-mathml
2253 (after org-odt-protect-latex-fragment activate)
2254 "Encode LaTeX fragment as XML.
2255 Do this when translation to MathML fails."
2256 (when (or (not (> (length ad-return-value) 0))
2257 (get-text-property 0 'org-protected ad-return-value))
2258 (setq ad-return-value
2259 (org-propertize (org-odt-encode-plain-text (ad-get-arg 0))
2260 'org-protected t))))
2262 (defun org-export-odt-preprocess-latex-fragments ()
2263 (when (equal org-export-current-backend 'odt)
2264 (org-export-odt-do-preprocess-latex-fragments)))
2266 (defun org-export-odt-preprocess-label-references ()
2267 (goto-char (point-min))
2268 (let (label label-components category value pretty-label)
2269 (while (re-search-forward "\\\\ref{\\([^{}\n]+\\)}" nil t)
2270 (org-if-unprotected-at (match-beginning 1)
2271 (replace-match
2272 (let ((org-lparse-encode-pending t)
2273 (label (match-string 1)))
2274 ;; markup generated below is mostly an eye-candy. At
2275 ;; pre-processing stage, there is no information on which
2276 ;; entity a label reference points to. The actual markup
2277 ;; is generated as part of `org-odt-fixup-label-references'
2278 ;; which gets called at the fag end of export. By this
2279 ;; time we would have seen and collected all the label
2280 ;; definitions in `org-odt-entity-labels-alist'.
2281 (org-odt-format-tags
2282 '("<text:sequence-ref text:ref-name=\"%s\">" .
2283 "</text:sequence-ref>")
2284 "" (org-add-props label '(org-protected t)))) t t)))))
2286 ;; process latex fragments as part of
2287 ;; `org-export-preprocess-after-blockquote-hook'. Note that this hook
2288 ;; is the one that is closest and well before the call to
2289 ;; `org-export-attach-captions-and-attributes' in
2290 ;; `org-export-preprocess-stirng'. The above arrangement permits
2291 ;; captions, labels and attributes to be attached to png images
2292 ;; generated out of latex equations.
2293 (add-hook 'org-export-preprocess-after-blockquote-hook
2294 'org-export-odt-preprocess-latex-fragments)
2296 (defun org-export-odt-preprocess (parameters)
2297 (org-export-odt-preprocess-label-references))
2299 (declare-function archive-zip-extract "arc-mode.el" (archive name))
2300 (defun org-odt-zip-extract-one (archive member &optional target)
2301 (require 'arc-mode)
2302 (let* ((target (or target default-directory))
2303 (archive (expand-file-name archive))
2304 (archive-zip-extract
2305 (list "unzip" "-qq" "-o" "-d" target))
2306 exit-code command-output)
2307 (setq command-output
2308 (with-temp-buffer
2309 (setq exit-code (archive-zip-extract archive member))
2310 (buffer-string)))
2311 (unless (zerop exit-code)
2312 (message command-output)
2313 (error "Extraction failed"))))
2315 (defun org-odt-zip-extract (archive members &optional target)
2316 (when (atom members) (setq members (list members)))
2317 (mapc (lambda (member)
2318 (org-odt-zip-extract-one archive member target))
2319 members))
2321 (defun org-odt-copy-styles-file (&optional styles-file)
2322 ;; Non-availability of styles.xml is not a critical error. For now
2323 ;; throw an error purely for aesthetic reasons.
2324 (setq styles-file (or styles-file
2325 org-export-odt-styles-file
2326 (expand-file-name "styles/OrgOdtStyles.xml"
2327 org-odt-data-dir)
2328 (error "org-odt: Missing styles file?")))
2329 (cond
2330 ((listp styles-file)
2331 (let ((archive (nth 0 styles-file))
2332 (members (nth 1 styles-file)))
2333 (org-odt-zip-extract archive members)
2334 (mapc
2335 (lambda (member)
2336 (when (org-file-image-p member)
2337 (let* ((image-type (file-name-extension member))
2338 (media-type (format "image/%s" image-type)))
2339 (org-odt-create-manifest-file-entry media-type member))))
2340 members)))
2341 ((and (stringp styles-file) (file-exists-p styles-file))
2342 (let ((styles-file-type (file-name-extension styles-file)))
2343 (cond
2344 ((string= styles-file-type "xml")
2345 (copy-file styles-file "styles.xml" t))
2346 ((member styles-file-type '("odt" "ott"))
2347 (org-odt-zip-extract styles-file "styles.xml")))))
2349 (error (format "Invalid specification of styles.xml file: %S"
2350 org-export-odt-styles-file))))
2352 ;; create a manifest entry for styles.xml
2353 (org-odt-create-manifest-file-entry "text/xml" "styles.xml"))
2355 (defvar org-export-odt-factory-settings
2356 "d4328fb9d1b6cb211d4320ff546829f26700dc5e"
2357 "SHA1 hash of OrgOdtStyles.xml.")
2359 (defun org-odt-configure-outline-numbering (level)
2360 "Outline numbering is retained only upto LEVEL.
2361 To disable outline numbering pass a LEVEL of 0."
2362 (goto-char (point-min))
2363 (let ((regex
2364 "<text:outline-level-style\\([^>]*\\)text:level=\"\\([^\"]*\\)\"\\([^>]*\\)>")
2365 (replacement
2366 "<text:outline-level-style\\1text:level=\"\\2\" style:num-format=\"\">"))
2367 (while (re-search-forward regex nil t)
2368 (when (> (string-to-number (match-string 2)) level)
2369 (replace-match replacement t nil))))
2370 (save-buffer 0))
2372 ;;;###autoload
2373 (defun org-export-as-odf (latex-frag &optional odf-file)
2374 "Export LATEX-FRAG as OpenDocument formula file ODF-FILE.
2375 Use `org-create-math-formula' to convert LATEX-FRAG first to
2376 MathML. When invoked as an interactive command, use
2377 `org-latex-regexps' to infer LATEX-FRAG from currently active
2378 region. If no LaTeX fragments are found, prompt for it. Push
2379 MathML source to kill ring, if `org-export-copy-to-kill-ring' is
2380 non-nil."
2381 (interactive
2382 `(,(let (frag)
2383 (setq frag (and (setq frag (and (region-active-p)
2384 (buffer-substring (region-beginning)
2385 (region-end))))
2386 (loop for e in org-latex-regexps
2387 thereis (when (string-match (nth 1 e) frag)
2388 (match-string (nth 2 e) frag)))))
2389 (read-string "LaTeX Fragment: " frag nil frag))
2390 ,(let ((odf-filename (expand-file-name
2391 (concat
2392 (file-name-sans-extension
2393 (or (file-name-nondirectory buffer-file-name)))
2394 "." "odf")
2395 (file-name-directory buffer-file-name))))
2396 (message "default val is %s" odf-filename)
2397 (read-file-name "ODF filename: " nil odf-filename nil
2398 (file-name-nondirectory odf-filename)))))
2399 (let* ((org-lparse-backend 'odf)
2400 org-lparse-opt-plist
2401 (filename (or odf-file
2402 (expand-file-name
2403 (concat
2404 (file-name-sans-extension
2405 (or (file-name-nondirectory buffer-file-name)))
2406 "." "odf")
2407 (file-name-directory buffer-file-name))))
2408 (buffer (find-file-noselect (org-odt-init-outfile filename)))
2409 (coding-system-for-write 'utf-8)
2410 (save-buffer-coding-system 'utf-8))
2411 (set-buffer buffer)
2412 (set-buffer-file-coding-system coding-system-for-write)
2413 (let ((mathml (org-create-math-formula latex-frag)))
2414 (unless mathml (error "No Math formula created"))
2415 (insert mathml)
2416 (or (org-export-push-to-kill-ring
2417 (upcase (symbol-name org-lparse-backend)))
2418 (message "Exporting... done")))
2419 (org-odt-save-as-outfile filename nil)))
2421 ;;;###autoload
2422 (defun org-export-as-odf-and-open ()
2423 "Export LaTeX fragment as OpenDocument formula and immediately open it.
2424 Use `org-export-as-odf' to read LaTeX fragment and OpenDocument
2425 formula file."
2426 (interactive)
2427 (org-lparse-and-open
2428 nil nil nil (call-interactively 'org-export-as-odf)))
2430 (provide 'org-odt)
2432 ;;; org-odt.el ends here