org-odt.el: Improve how labels are applied and generated.
[org-mode/org-jambu.git] / contrib / lisp / org-odt.el
blob7c03745aa32d31150d14430c5b525c62670636b4
1 ;;; org-odt.el --- OpenDocumentText export for Org-mode
3 ;; Copyright (C) 2010-2011 Jambunathan <kjambunathan at gmail dot com>
5 ;; Author: Jambunathan K <kjambunathan at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 0.8
10 ;; This file is not (yet) part of GNU Emacs.
11 ;; However, it is distributed under the same license.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;;; Code:
30 (eval-when-compile (require 'cl))
31 (require 'org-lparse)
33 (defun org-odt-end-export ()
34 (org-odt-fixup-label-references)
36 ;; remove empty paragraphs
37 (goto-char (point-min))
38 (while (re-search-forward
39 "<text:p\\( text:style-name=\"Text_20_body\"\\)?>[ \r\n\t]*</text:p>"
40 nil t)
41 (replace-match ""))
42 (goto-char (point-min))
44 ;; Convert whitespace place holders
45 (goto-char (point-min))
46 (let (beg end n)
47 (while (setq beg (next-single-property-change (point) 'org-whitespace))
48 (setq n (get-text-property beg 'org-whitespace)
49 end (next-single-property-change beg 'org-whitespace))
50 (goto-char beg)
51 (delete-region beg end)
52 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
53 (make-string n ?x)))))
55 ;; Remove empty lines at the beginning of the file.
56 (goto-char (point-min))
57 (when (looking-at "\\s-+\n") (replace-match ""))
59 ;; Remove display properties
60 (remove-text-properties (point-min) (point-max) '(display t)))
62 (defvar org-odt-suppress-xref nil)
63 (defconst org-export-odt-special-string-regexps
64 '(("\\\\-" . "&#x00ad;\\1") ; shy
65 ("---\\([^-]\\)" . "&#x2014;\\1") ; mdash
66 ("--\\([^-]\\)" . "&#x2013;\\1") ; ndash
67 ("\\.\\.\\." . "&#x2026;")) ; hellip
68 "Regular expressions for special string conversion.")
70 (defconst org-odt-lib-dir (file-name-directory load-file-name))
71 (defconst org-odt-data-dir
72 (let ((dir1 (expand-file-name "../odt" org-odt-lib-dir)) ; git
73 (dir2 (expand-file-name "./contrib/odt" org-odt-lib-dir))) ; elpa
74 (cond
75 ((file-directory-p dir1) dir1)
76 ((file-directory-p dir2) dir2)
77 (t (error "Cannot find factory styles file. Check package dir layout"))))
78 "Directory that holds auxiliary files used by the ODT exporter.
80 The 'styles' subdir contains the following xml files -
81 'OrgOdtStyles.xml' and 'OrgOdtContentTemplate.xml' - which are
82 used as factory settings of `org-export-odt-styles-file' and
83 `org-export-odt-content-template-file'.
85 The 'etc/schema' subdir contains rnc files for validating of
86 OpenDocument xml files.")
88 (defvar org-odt-file-extensions
89 '(("odt" . "OpenDocument Text")
90 ("ott" . "OpenDocument Text Template")
91 ("odm" . "OpenDocument Master Document")
92 ("ods" . "OpenDocument Spreadsheet")
93 ("ots" . "OpenDocument Spreadsheet Template")
94 ("odg" . "OpenDocument Drawing (Graphics)")
95 ("otg" . "OpenDocument Drawing Template")
96 ("odp" . "OpenDocument Presentation")
97 ("otp" . "OpenDocument Presentation Template")
98 ("odi" . "OpenDocument Image")
99 ("odf" . "OpenDocument Formula")
100 ("odc" . "OpenDocument Chart")
101 ("doc" . "Microsoft Text")
102 ("docx" . "Microsoft Text")
103 ("xls" . "Microsoft Spreadsheet")
104 ("xlsx" . "Microsoft Spreadsheet")
105 ("ppt" . "Microsoft Presentation")
106 ("pptx" . "Microsoft Presentation")))
108 (defvar org-odt-ms-file-extensions
109 '(("doc" . "Microsoft Text")
110 ("docx" . "Microsoft Text")
111 ("xls" . "Microsoft Spreadsheet")
112 ("xlsx" . "Microsoft Spreadsheet")
113 ("ppt" . "Microsoft Presentation")
114 ("pptx" . "Microsoft Presentation")))
116 ;; RelaxNG validation of OpenDocument xml files
117 (eval-after-load 'rng-nxml
118 '(setq rng-nxml-auto-validate-flag t))
120 (eval-after-load 'rng-loc
121 '(add-to-list 'rng-schema-locating-files
122 (expand-file-name "etc/schema/schemas.xml" org-odt-data-dir)))
124 (mapc
125 (lambda (desc)
126 ;; Let Org open all OpenDocument files using system-registered app
127 (add-to-list 'org-file-apps
128 (cons (concat "\\." (car desc) "\\'") 'system))
129 ;; Let Emacs open all OpenDocument files in archive mode
130 (add-to-list 'auto-mode-alist
131 (cons (concat "\\." (car desc) "\\'") 'archive-mode)))
132 org-odt-file-extensions)
134 (mapc
135 (lambda (desc)
136 ;; Let Org open all Microsoft files using system-registered app
137 (add-to-list 'org-file-apps
138 (cons (concat "\\." (car desc) "\\'") 'system)))
139 org-odt-ms-file-extensions)
141 ;; register the odt exporter with the pre-processor
142 (add-to-list 'org-export-backends 'odt)
144 ;; register the odt exporter with org-lparse library
145 (org-lparse-register-backend 'odt)
147 (defun org-odt-unload-function ()
148 (org-lparse-unregister-backend 'odt)
149 (remove-hook 'org-export-preprocess-after-blockquote-hook
150 'org-export-odt-preprocess-latex-fragments)
151 nil)
153 (defcustom org-export-odt-content-template-file nil
154 "Template file for \"content.xml\".
155 The exporter embeds the exported content just before
156 \"</office:text>\" element.
158 If unspecified, the file named \"OrgOdtContentTemplate.xml\"
159 under `org-odt-data-dir' is used."
160 :type 'file
161 :group 'org-export-odt)
163 (defcustom org-export-odt-styles-file nil
164 "Default styles file for use with ODT export.
165 Valid values are one of:
166 1. nil
167 2. path to a styles.xml file
168 3. path to a *.odt or a *.ott file
169 4. list of the form (ODT-OR-OTT-FILE (FILE-MEMBER-1 FILE-MEMBER-2
170 ...))
172 In case of option 1, an in-built styles.xml is used. See
173 `org-odt-data-dir' for more information.
175 In case of option 3, the specified file is unzipped and the
176 styles.xml embedded therein is used.
178 In case of option 4, the specified ODT-OR-OTT-FILE is unzipped
179 and FILE-MEMBER-1, FILE-MEMBER-2 etc are copied in to the
180 generated odt file. Use relative path for specifying the
181 FILE-MEMBERS. styles.xml must be specified as one of the
182 FILE-MEMBERS.
184 Use options 1, 2 or 3 only if styles.xml alone suffices for
185 achieving the desired formatting. Use option 4, if the styles.xml
186 references additional files like header and footer images for
187 achieving the desired formattting."
188 :group 'org-export-odt
189 :type
190 '(choice
191 (const :tag "Factory settings" nil)
192 (file :must-match t :tag "styles.xml")
193 (file :must-match t :tag "ODT or OTT file")
194 (list :tag "ODT or OTT file + Members"
195 (file :must-match t :tag "ODF Text or Text Template file")
196 (cons :tag "Members"
197 (file :tag " Member" "styles.xml")
198 (repeat (file :tag "Member"))))))
200 (defconst org-export-odt-tmpdir-prefix "odt-")
201 (defconst org-export-odt-bookmark-prefix "OrgXref.")
202 (defcustom org-export-odt-use-bookmarks-for-internal-links t
203 "Export Internal links as bookmarks?."
204 :type 'boolean
205 :group 'org-export-odt)
207 (defcustom org-export-odt-embed-images t
208 "Should the images be copied in to the odt file or just linked?"
209 :type 'boolean
210 :group 'org-export-odt)
212 (defcustom org-odt-export-inline-images 'maybe
213 "Non-nil means inline images into exported HTML pages.
214 This is done using an <img> tag. When nil, an anchor with href is used to
215 link to the image. If this option is `maybe', then images in links with
216 an empty description will be inlined, while images with a description will
217 be linked only."
218 :group 'org-odt-export
219 :type '(choice (const :tag "Never" nil)
220 (const :tag "Always" t)
221 (const :tag "When there is no description" maybe)))
223 (defcustom org-odt-export-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-odt-export)
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 an external converter to convert the resulting document
280 to this format.
282 The converter used is that specified with CONVERT-METHOD option
283 in `org-odt-get'. If the above option is unspecified then
284 `org-lparse-convert-process' is used.
286 The format specified here should be listed in OTHER-BACKENDS
287 option of `org-odt-get' or `org-lparse-convert-capabilities' as
288 appropriate."
289 :group 'org-odt
290 :type '(choice :convert-widget
291 (lambda (w)
292 (apply 'widget-convert (widget-type w)
293 (eval (car (widget-get w :args)))))
294 `((const :tag "None" nil)
295 ,@(mapcar (lambda (c)
296 `(const :tag ,(car c) ,(car c)))
297 (org-lparse-get-other-backends "odt")))))
299 ;;;###autoload
300 (defun org-export-as-odt-and-open (arg)
301 "Export the outline as ODT and immediately open it with a browser.
302 If there is an active region, export only the region.
303 The prefix ARG specifies how many levels of the outline should become
304 headlines. The default is 3. Lower levels will become bulleted lists."
305 (interactive "P")
306 (org-lparse-and-open
307 (or org-export-odt-preferred-output-format "odt") "odt" arg))
309 ;;;###autoload
310 (defun org-export-as-odt-batch ()
311 "Call the function `org-lparse-batch'.
312 This function can be used in batch processing as:
313 emacs --batch
314 --load=$HOME/lib/emacs/org.el
315 --eval \"(setq org-export-headline-levels 2)\"
316 --visit=MyFile --funcall org-export-as-odt-batch"
317 (org-lparse-batch "odt"))
319 ;;;###autoload
320 (defun org-export-as-odt-to-buffer (arg)
321 "Call `org-lparse-odt` with output to a temporary buffer.
322 No file is created. The prefix ARG is passed through to `org-lparse-to-buffer'."
323 (interactive "P")
324 (org-lparse-to-buffer "odt" arg))
326 ;;;###autoload
327 (defun org-replace-region-by-odt (beg end)
328 "Assume the current region has org-mode syntax, and convert it to ODT.
329 This can be used in any buffer. For example, you could write an
330 itemized list in org-mode syntax in an ODT buffer and then use this
331 command to convert it."
332 (interactive "r")
333 (org-replace-region-by "odt" beg end))
335 ;;;###autoload
336 (defun org-export-region-as-odt (beg end &optional body-only buffer)
337 "Convert region from BEG to END in org-mode buffer to ODT.
338 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
339 contents, and only produce the region of converted text, useful for
340 cut-and-paste operations.
341 If BUFFER is a buffer or a string, use/create that buffer as a target
342 of the converted ODT. If BUFFER is the symbol `string', return the
343 produced ODT as a string and leave not buffer behind. For example,
344 a Lisp program could call this function in the following way:
346 (setq odt (org-export-region-as-odt beg end t 'string))
348 When called interactively, the output buffer is selected, and shown
349 in a window. A non-interactive call will only return the buffer."
350 (interactive "r\nP")
351 (org-lparse-region "odt" beg end body-only buffer))
353 ;;; org-export-as-odt
354 ;;;###autoload
355 (defun org-export-as-odt (arg &optional hidden ext-plist
356 to-buffer body-only pub-dir)
357 "Export the outline as a OpenDocumentText file.
358 If there is an active region, export only the region. The prefix
359 ARG specifies how many levels of the outline should become
360 headlines. The default is 3. Lower levels will become bulleted
361 lists. HIDDEN is obsolete and does nothing.
362 EXT-PLIST is a property list with external parameters overriding
363 org-mode's default settings, but still inferior to file-local
364 settings. When TO-BUFFER is non-nil, create a buffer with that
365 name and export to that buffer. If TO-BUFFER is the symbol
366 `string', don't leave any buffer behind but just return the
367 resulting XML as a string. When BODY-ONLY is set, don't produce
368 the file header and footer, simply return the content of
369 <body>...</body>, without even the body tags themselves. When
370 PUB-DIR is set, use this as the publishing directory."
371 (interactive "P")
372 (org-lparse (or org-export-odt-preferred-output-format "odt")
373 "odt" arg hidden ext-plist to-buffer body-only pub-dir))
375 (defvar org-odt-entity-control-callbacks-alist
376 `((EXPORT
377 . (org-odt-begin-export org-odt-end-export))
378 (DOCUMENT-CONTENT
379 . (org-odt-begin-document-content org-odt-end-document-content))
380 (DOCUMENT-BODY
381 . (org-odt-begin-document-body org-odt-end-document-body))
382 (TOC
383 . (org-odt-begin-toc org-odt-end-toc))
384 (ENVIRONMENT
385 . (org-odt-begin-environment org-odt-end-environment))
386 (FOOTNOTE-DEFINITION
387 . (org-odt-begin-footnote-definition org-odt-end-footnote-definition))
388 (TABLE
389 . (org-odt-begin-table org-odt-end-table))
390 (TABLE-ROWGROUP
391 . (org-odt-begin-table-rowgroup org-odt-end-table-rowgroup))
392 (LIST
393 . (org-odt-begin-list org-odt-end-list))
394 (LIST-ITEM
395 . (org-odt-begin-list-item org-odt-end-list-item))
396 (OUTLINE
397 . (org-odt-begin-outline org-odt-end-outline))
398 (OUTLINE-TEXT
399 . (org-odt-begin-outline-text org-odt-end-outline-text))
400 (PARAGRAPH
401 . (org-odt-begin-paragraph org-odt-end-paragraph)))
404 (defvar org-odt-entity-format-callbacks-alist
405 `((EXTRA-TARGETS . org-lparse-format-extra-targets)
406 (ORG-TAGS . org-lparse-format-org-tags)
407 (SECTION-NUMBER . org-lparse-format-section-number)
408 (HEADLINE . org-odt-format-headline)
409 (TOC-ENTRY . org-odt-format-toc-entry)
410 (TOC-ITEM . org-odt-format-toc-item)
411 (TAGS . org-odt-format-tags)
412 (SPACES . org-odt-format-spaces)
413 (TABS . org-odt-format-tabs)
414 (LINE-BREAK . org-odt-format-line-break)
415 (FONTIFY . org-odt-format-fontify)
416 (TODO . org-lparse-format-todo)
417 (LINK . org-odt-format-link)
418 (INLINE-IMAGE . org-odt-format-inline-image)
419 (ORG-LINK . org-odt-format-org-link)
420 (HEADING . org-odt-format-heading)
421 (ANCHOR . org-odt-format-anchor)
422 (TABLE . org-lparse-format-table)
423 (TABLE-ROW . org-odt-format-table-row)
424 (TABLE-CELL . org-odt-format-table-cell)
425 (FOOTNOTES-SECTION . ignore)
426 (FOOTNOTE-REFERENCE . org-odt-format-footnote-reference)
427 (HORIZONTAL-LINE . org-odt-format-horizontal-line)
428 (COMMENT . org-odt-format-comment)
429 (LINE . org-odt-format-line)
430 (ORG-ENTITY . org-odt-format-org-entity))
433 ;;;_. callbacks
434 ;;;_. control callbacks
435 ;;;_ , document body
436 (defun org-odt-begin-office-body ()
437 ;; automatic styles
438 (insert-file-contents
439 (or org-export-odt-content-template-file
440 (expand-file-name "styles/OrgOdtContentTemplate.xml"
441 org-odt-data-dir)))
442 (goto-char (point-min))
443 (re-search-forward "</office:text>" nil nil)
444 (delete-region (match-beginning 0) (point-max)))
446 ;; Following variable is let bound when `org-do-lparse' is in
447 ;; progress. See org-html.el.
448 (defvar org-lparse-toc)
449 (defun org-odt-begin-document-body (opt-plist)
450 (org-odt-begin-office-body)
451 (let ((title (plist-get opt-plist :title)))
452 (when title
453 (insert
454 (org-odt-format-stylized-paragraph 'title title))))
456 ;; insert toc
457 (when org-lparse-toc
458 (insert "\n" org-lparse-toc "\n")))
460 (defvar org-lparse-body-only) ; let bound during org-do-lparse
461 (defvar org-lparse-to-buffer) ; let bound during org-do-lparse
462 (defun org-odt-end-document-body (opt-plist)
463 (unless org-lparse-body-only
464 (org-lparse-insert-tag "</office:text>")
465 (org-lparse-insert-tag "</office:body>")))
467 (defun org-odt-begin-document-content (opt-plist)
468 (ignore))
470 (defun org-odt-end-document-content ()
471 (org-lparse-insert-tag "</office:document-content>"))
473 (defun org-odt-begin-outline (level1 snumber title tags
474 target extra-targets class)
475 (org-lparse-insert
476 'HEADING (org-lparse-format
477 'HEADLINE title extra-targets tags snumber level1)
478 level1 target))
480 (defun org-odt-end-outline ()
481 (ignore))
483 (defun org-odt-begin-outline-text (level1 snumber class)
484 (ignore))
486 (defun org-odt-end-outline-text ()
487 (ignore))
489 (defun org-odt-begin-paragraph (&optional style)
490 (org-lparse-insert-tag
491 "<text:p%s>" (org-odt-get-extra-attrs-for-paragraph-style style)))
493 (defun org-odt-end-paragraph ()
494 (org-lparse-insert-tag "</text:p>"))
496 (defun org-odt-get-extra-attrs-for-paragraph-style (style)
497 (let (style-name)
498 (setq style-name
499 (cond
500 ((stringp style) style)
501 ((symbolp style) (org-odt-get-style-name-for-entity
502 'paragraph style))))
503 (unless style-name
504 (error "Don't know how to handle paragraph style %s" style))
505 (format " text:style-name=\"%s\"" style-name)))
507 (defun org-odt-format-stylized-paragraph (style text)
508 (org-odt-format-tags
509 '("<text:p%s>" . "</text:p>") text
510 (org-odt-get-extra-attrs-for-paragraph-style style)))
512 (defun org-odt-begin-environment (style)
513 (case style
514 ((blockquote verse center quote)
515 (org-lparse-begin-paragraph style)
516 (list))
517 ((fixedwidth native)
518 (org-lparse-end-paragraph)
519 (list))
520 (t (error "Unknown environment %s" style))))
522 (defun org-odt-end-environment (style)
523 (case style
524 ((blockquote verse center quote)
525 (org-lparse-end-paragraph)
526 (list))
527 ((fixedwidth native)
528 (org-lparse-begin-paragraph)
529 (list))
530 (t (error "Unknown environment %s" style))))
532 (defvar org-lparse-list-level) ; dynamically bound in org-do-lparse
533 (defun org-odt-begin-list (ltype)
534 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
535 ltype))
536 (let* ((style-name (org-odt-get-style-name-for-entity 'list ltype))
537 (extra (concat (when (= org-lparse-list-level 1)
538 " text:continue-numbering=\"false\"")
539 (when style-name
540 (format " text:style-name=\"%s\"" style-name)))))
541 (case ltype
542 ((ordered unordered description)
543 (org-lparse-end-paragraph)
544 (org-lparse-insert-tag "<text:list%s>" extra))
545 (t (error "Unknown list type: %s" ltype)))))
547 (defun org-odt-end-list (ltype)
548 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
549 ltype))
550 (if ltype
551 (org-lparse-insert-tag "</text:list>")
552 (error "Unknown list type: %s" ltype)))
554 (defun org-odt-begin-list-item (ltype &optional arg headline)
555 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
556 ltype))
557 (case ltype
558 (ordered
559 (assert (not headline) t)
560 (let* ((counter arg) (extra ""))
561 (org-lparse-insert-tag "<text:list-item>")
562 (org-lparse-begin-paragraph)))
563 (unordered
564 (let* ((id arg) (extra ""))
565 (org-lparse-insert-tag "<text:list-item>")
566 (org-lparse-begin-paragraph)
567 (insert (if headline (org-odt-format-target headline id)
568 (org-odt-format-bookmark "" id)))))
569 (description
570 (assert (not headline) t)
571 (let ((term (or arg "(no term)")))
572 (insert
573 (org-odt-format-tags
574 '("<text:list-item>" . "</text:list-item>")
575 (org-odt-format-stylized-paragraph 'definition-term term)))
576 (org-lparse-begin-list-item 'unordered)
577 (org-lparse-begin-list 'description)
578 (org-lparse-begin-list-item 'unordered)))
579 (t (error "Unknown list type"))))
581 (defun org-odt-end-list-item (ltype)
582 (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
583 ltype))
584 (case ltype
585 ((ordered unordered)
586 (org-lparse-insert-tag "</text:list-item>"))
587 (description
588 (org-lparse-end-list-item-1)
589 (org-lparse-end-list 'description)
590 (org-lparse-end-list-item-1))
591 (t (error "Unknown list type"))))
593 ;; Following variables are let bound when table emission is in
594 ;; progress. See org-lparse.el.
595 (defvar org-lparse-table-begin-marker)
596 (defvar org-lparse-table-ncols)
597 (defvar org-lparse-table-rowgrp-open)
598 (defvar org-lparse-table-rownum)
599 (defvar org-lparse-table-cur-rowgrp-is-hdr)
600 (defvar org-lparse-table-is-styled)
601 (defvar org-lparse-table-rowgrp-info)
602 (defvar org-lparse-table-colalign-vector)
604 (defvar org-odt-table-style nil
605 "Table style specified by \"#+ATTR_ODT: <style-name>\" line.
606 This is set during `org-odt-begin-table'.")
608 (defvar org-odt-table-style-spec nil
609 "Entry for `org-odt-table-style' in `org-export-odt-table-styles'.")
611 (defcustom org-export-odt-table-styles nil
612 "Specify how Table Styles should be derived from a Table Template.
613 This is a list where each element is of the
614 form (TABLE-STYLE-NAME TABLE-TEMPLATE-NAME TABLE-CELL-OPTIONS).
616 TABLE-STYLE-NAME is the style associated with the table through
617 `org-odt-table-style'.
619 TABLE-TEMPLATE-NAME is a set of - upto 9 - automatic
620 TABLE-CELL-STYLE-NAMEs and PARAGRAPH-STYLE-NAMEs (as defined
621 below) that is included in
622 `org-export-odt-content-template-file'.
624 TABLE-CELL-STYLE-NAME := TABLE-TEMPLATE-NAME + TABLE-CELL-TYPE +
625 \"TableCell\"
626 PARAGRAPH-STYLE-NAME := TABLE-TEMPLATE-NAME + TABLE-CELL-TYPE +
627 \"TableParagraph\"
628 TABLE-CELL-TYPE := \"FirstRow\" | \"LastColumn\" |
629 \"FirstRow\" | \"LastRow\" |
630 \"EvenRow\" | \"OddRow\" |
631 \"EvenColumn\" | \"OddColumn\" | \"\"
632 where \"+\" above denotes string concatenation.
634 TABLE-CELL-OPTIONS is an alist where each element is of the
635 form (TABLE-CELL-STYLE-SELECTOR . ON-OR-OFF).
636 TABLE-CELL-STYLE-SELECTOR := `use-first-row-styles' |
637 `use-last-row-styles' |
638 `use-first-column-styles' |
639 `use-last-column-styles' |
640 `use-banding-rows-styles' |
641 `use-banding-columns-styles' |
642 `use-first-row-styles'
643 ON-OR-OFF := `t' | `nil'
645 For example, with the following configuration
647 \(setq org-export-odt-table-styles
648 '\(\(\"TableWithHeaderRowsAndColumns\" \"Custom\"
649 \(\(use-first-row-styles . t\)
650 \(use-first-column-styles . t\)\)\)
651 \(\"TableWithHeaderColumns\" \"Custom\"
652 \(\(use-first-column-styles . t\)\)\)\)\)
654 1. A table associated with \"TableWithHeaderRowsAndColumns\"
655 style will use the following table-cell styles -
656 \"CustomFirstRowTableCell\", \"CustomFirstColumnTableCell\",
657 \"CustomTableCell\" and the following paragraph styles
658 \"CustomFirstRowTableParagraph\",
659 \"CustomFirstColumnTableParagraph\", \"CustomTableParagraph\"
660 as appropriate.
662 2. A table associated with \"TableWithHeaderColumns\" style will
663 use the following table-cell styles -
664 \"CustomFirstColumnTableCell\", \"CustomTableCell\" and the
665 following paragraph styles
666 \"CustomFirstColumnTableParagraph\", \"CustomTableParagraph\"
667 as appropriate..
669 Note that TABLE-TEMPLATE-NAME corresponds to the
670 \"<table:table-template>\" elements contained within
671 \"<office:styles>\". The entries (TABLE-STYLE-NAME
672 TABLE-TEMPLATE-NAME TABLE-CELL-OPTIONS) correspond to
673 \"table:template-name\" and \"table:use-first-row-styles\" etc
674 attributes of \"<table:table>\" element. Refer ODF-1.2
675 specification for more information. Also consult the
676 implementation filed under `org-odt-get-table-cell-styles'."
677 :group 'org-export-odt
678 :type '(choice
679 (const :tag "None" nil)
680 (repeat :tag "Table Styles"
681 (list :tag "Table Style Specification"
682 (string :tag "Table Style Name")
683 (string :tag "Table Template Name")
684 (alist :options (use-first-row-styles
685 use-last-row-styles
686 use-first-column-styles
687 use-last-column-styles
688 use-banding-rows-styles
689 use-banding-columns-styles)
690 :key-type symbol
691 :value-type (const :tag "True" t))))))
693 (defun org-odt-begin-table (caption label attributes)
694 (setq org-odt-table-style attributes)
695 (setq org-odt-table-style-spec
696 (assoc org-odt-table-style org-export-odt-table-styles))
697 (when label
698 (insert
699 (org-odt-format-stylized-paragraph
700 'table (org-odt-format-entity-caption label caption "Table"))))
701 (org-lparse-insert-tag
702 "<table:table table:name=\"%s\" table:style-name=\"%s\">"
703 (or label "") (or (nth 1 org-odt-table-style-spec) "OrgTable"))
704 (setq org-lparse-table-begin-marker (point)))
706 (defun org-odt-end-table ()
707 (goto-char org-lparse-table-begin-marker)
708 (loop for level from 0 below org-lparse-table-ncols
709 do (insert
710 (org-odt-format-tags
711 "<table:table-column table:style-name=\"%sColumn\"/>"
712 "" (or (nth 1 org-odt-table-style-spec) "OrgTable"))))
714 ;; fill style attributes for table cells
715 (when org-lparse-table-is-styled
716 (while (re-search-forward "@@\\(table-cell:p\\|table-cell:style-name\\)@@\\([0-9]+\\)@@\\([0-9]+\\)@@" nil t)
717 (let* ((spec (match-string 1))
718 (r (string-to-number (match-string 2)))
719 (c (string-to-number (match-string 3)))
720 (cell-styles (org-odt-get-table-cell-styles
721 r c org-odt-table-style-spec))
722 (table-cell-style (car cell-styles))
723 (table-cell-paragraph-style (cdr cell-styles)))
724 (cond
725 ((equal spec "table-cell:p")
726 (replace-match table-cell-paragraph-style t t))
727 ((equal spec "table-cell:style-name")
728 (replace-match table-cell-style t t))))))
729 (goto-char (point-max))
730 (org-lparse-insert-tag "</table:table>"))
732 (defun org-odt-begin-table-rowgroup (&optional is-header-row)
733 (when org-lparse-table-rowgrp-open
734 (org-lparse-end 'TABLE-ROWGROUP))
735 (org-lparse-insert-tag (if is-header-row
736 "<table:table-header-rows>"
737 "<table:table-rows>"))
738 (setq org-lparse-table-rowgrp-open t)
739 (setq org-lparse-table-cur-rowgrp-is-hdr is-header-row))
741 (defun org-odt-end-table-rowgroup ()
742 (when org-lparse-table-rowgrp-open
743 (setq org-lparse-table-rowgrp-open nil)
744 (org-lparse-insert-tag
745 (if org-lparse-table-cur-rowgrp-is-hdr
746 "</table:table-header-rows>" "</table:table-rows>"))))
748 (defun org-odt-format-table-row (row)
749 (org-odt-format-tags
750 '("<table:table-row>" . "</table:table-row>") row))
752 (defun org-odt-get-table-cell-styles (r c &optional style-spec)
753 "Retrieve styles applicable to a table cell.
754 R and C are (zero-based) row and column numbers of the table
755 cell. STYLE-SPEC is an entry in `org-export-odt-table-styles'
756 applicable to the current table. It is `nil' if the table is not
757 associated with any style attributes.
759 Return a cons of (TABLE-CELL-STYLE-NAME . PARAGRAPH-STYLE-NAME).
761 When STYLE-SPEC is nil, style the table cell the conventional way
762 - choose cell borders based on row and column groupings and
763 choose paragraph alignment based on `org-col-cookies' text
764 property. See also
765 `org-odt-get-paragraph-style-cookie-for-table-cell'.
767 When STYLE-SPEC is non-nil, ignore the above cookie and return
768 styles congruent with the ODF-1.2 specification."
769 (cond
770 (style-spec
772 ;; LibreOffice - particularly the Writer - honors neither table
773 ;; templates nor custom table-cell styles. Inorder to retain
774 ;; inter-operability with LibreOffice, only automatic styles are
775 ;; used for styling of table-cells. The current implementation is
776 ;; congruent with ODF-1.2 specification and hence is
777 ;; future-compatible.
779 ;; Additional Note: LibreOffice's AutoFormat facility for tables -
780 ;; which recognizes as many as 16 different cell types - is much
781 ;; richer. Unfortunately it is NOT amenable to easy configuration
782 ;; by hand.
784 (let* ((template-name (nth 1 style-spec))
785 (cell-style-selectors (nth 2 style-spec))
786 (cell-type
787 (cond
788 ((and (cdr (assoc 'use-first-column-styles cell-style-selectors))
789 (= c 0)) "FirstColumn")
790 ((and (cdr (assoc 'use-last-column-styles cell-style-selectors))
791 (= c (1- org-lparse-table-ncols))) "LastColumn")
792 ((and (cdr (assoc 'use-first-row-styles cell-style-selectors))
793 (= r 0)) "FirstRow")
794 ((and (cdr (assoc 'use-last-row-styles cell-style-selectors))
795 (= r org-lparse-table-rownum))
796 "LastRow")
797 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
798 (= (% r 2) 1)) "EvenRow")
799 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
800 (= (% r 2) 0)) "OddRow")
801 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
802 (= (% c 2) 1)) "EvenColumn")
803 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
804 (= (% c 2) 0)) "OddColumn")
805 (t ""))))
806 (cons
807 (concat template-name cell-type "TableCell")
808 (concat template-name cell-type "TableParagraph"))))
810 (cons
811 (concat
812 "OrgTblCell"
813 (cond
814 ((= r 0) "T")
815 ((eq (cdr (assoc r org-lparse-table-rowgrp-info)) :start) "T")
816 (t ""))
817 (when (= r org-lparse-table-rownum) "B")
818 (cond
819 ((= c 0) "")
820 ((or (memq (nth c org-table-colgroup-info) '(:start :startend))
821 (memq (nth (1- c) org-table-colgroup-info) '(:end :startend))) "L")
822 (t "")))
823 (capitalize (aref org-lparse-table-colalign-vector c))))))
825 (defun org-odt-get-paragraph-style-cookie-for-table-cell (r c)
826 (concat
827 (and (not org-odt-table-style-spec)
828 (cond
829 (org-lparse-table-cur-rowgrp-is-hdr "OrgTableHeading")
830 ((and (= c 0) (org-lparse-get 'TABLE-FIRST-COLUMN-AS-LABELS))
831 "OrgTableHeading")
832 (t "OrgTableContents")))
833 (and org-lparse-table-is-styled
834 (format "@@table-cell:p@@%03d@@%03d@@" r c))))
836 (defun org-odt-get-style-name-cookie-for-table-cell (r c)
837 (when org-lparse-table-is-styled
838 (format "@@table-cell:style-name@@%03d@@%03d@@" r c)))
840 (defun org-odt-format-table-cell (data r c)
841 (let* ((paragraph-style-cookie
842 (org-odt-get-paragraph-style-cookie-for-table-cell r c))
843 (style-name-cookie
844 (org-odt-get-style-name-cookie-for-table-cell r c))
845 (extra (if style-name-cookie
846 (format " table:style-name=\"%s\"" style-name-cookie) "")))
847 (org-odt-format-tags
848 '("<table:table-cell%s>" . "</table:table-cell>")
849 (if org-lparse-list-table-p data
850 (org-odt-format-stylized-paragraph paragraph-style-cookie data)) extra)))
852 (defun org-odt-begin-footnote-definition (n)
853 (org-lparse-begin-paragraph 'footnote))
855 (defun org-odt-end-footnote-definition (n)
856 (org-lparse-end-paragraph))
858 (defun org-odt-begin-toc (lang-specific-heading)
859 (insert
860 (format "
861 <text:table-of-content text:style-name=\"Sect2\" text:protected=\"true\" text:name=\"Table of Contents1\">
862 <text:table-of-content-source text:outline-level=\"10\">
863 <text:index-title-template text:style-name=\"Contents_20_Heading\">%s</text:index-title-template>
864 " lang-specific-heading))
866 (loop for level from 1 upto 10
867 do (insert (format
869 <text:table-of-content-entry-template text:outline-level=\"%d\" text:style-name=\"Contents_20_%d\">
870 <text:index-entry-link-start text:style-name=\"Internet_20_link\"/>
871 <text:index-entry-chapter/>
872 <text:index-entry-text/>
873 <text:index-entry-link-end/>
874 </text:table-of-content-entry-template>
875 " level level)))
877 (insert
878 (format "
879 </text:table-of-content-source>
881 <text:index-body>
882 <text:index-title text:style-name=\"Sect1\" text:name=\"Table of Contents1_Head\">
883 <text:p text:style-name=\"Contents_20_Heading\">%s</text:p>
884 </text:index-title>
885 " lang-specific-heading)))
887 (defun org-odt-end-toc ()
888 (insert "
889 </text:index-body>
890 </text:table-of-content>
893 (defun org-odt-format-toc-entry (snumber todo headline tags href)
894 (setq headline (concat
895 (and org-export-with-section-numbers
896 (concat snumber ". "))
897 headline
898 (and tags
899 (concat
900 (org-lparse-format 'SPACES 3)
901 (org-lparse-format 'FONTIFY tags "tag")))))
902 (when todo
903 (setq headline (org-lparse-format 'FONTIFY headline "todo")))
905 (let ((org-odt-suppress-xref t))
906 (org-odt-format-link headline (concat "#" href))))
908 (defun org-odt-format-toc-item (toc-entry level org-last-level)
909 (let ((style (format "Contents_20_%d"
910 (+ level (or (org-lparse-get 'TOPLEVEL-HLEVEL) 1) -1))))
911 (insert "\n" (org-odt-format-stylized-paragraph style toc-entry) "\n")))
913 ;; Following variable is let bound during 'ORG-LINK callback. See
914 ;; org-html.el
915 (defvar org-lparse-link-description-is-image nil)
916 (defun org-odt-format-link (desc href &optional attr)
917 (cond
918 ((and (= (string-to-char href) ?#) (not org-odt-suppress-xref))
919 (setq href (concat org-export-odt-bookmark-prefix (substring href 1)))
920 (org-odt-format-tags
921 '("<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"%s\">" .
922 "</text:bookmark-ref>")
923 desc href))
924 (org-lparse-link-description-is-image
925 (org-odt-format-tags
926 '("<draw:a xlink:type=\"simple\" xlink:href=\"%s\" %s>" . "</draw:a>")
927 desc href (or attr "")))
929 (org-odt-format-tags
930 '("<text:a xlink:type=\"simple\" xlink:href=\"%s\" %s>" . "</text:a>")
931 desc href (or attr "")))))
933 (defun org-odt-format-spaces (n)
934 (cond
935 ((= n 1) " ")
936 ((> n 1) (concat
937 " " (org-odt-format-tags "<text:s text:c=\"%d\"/>" "" (1- n))))
938 (t "")))
940 (defun org-odt-format-tabs (&optional n)
941 (let ((tab "<text:tab/>")
942 (n (or n 1)))
943 (insert tab)))
945 (defun org-odt-format-line-break ()
946 (org-odt-format-tags "<text:line-break/>" ""))
948 (defun org-odt-format-horizontal-line ()
949 (org-odt-format-stylized-paragraph 'horizontal-line ""))
951 (defun org-odt-format-line (line)
952 (case org-lparse-dyn-current-environment
953 (fixedwidth (concat
954 (org-odt-format-stylized-paragraph
955 'fixedwidth (org-odt-fill-tabs-and-spaces
956 (org-xml-encode-plain-text line))) "\n"))
957 (t (concat line "\n"))))
959 (defun org-odt-format-comment (fmt &rest args)
960 (let ((comment (apply 'format fmt args)))
961 (format "\n<!-- %s -->\n" comment)))
963 (defun org-odt-format-org-entity (wd)
964 (org-entity-get-representation wd 'utf8))
966 (defun org-odt-fill-tabs-and-spaces (line)
967 (replace-regexp-in-string
968 "\\([\t]\\|\\([ ]+\\)\\)" (lambda (s)
969 (cond
970 ((string= s "\t") (org-odt-format-tabs))
971 (t (org-odt-format-spaces (length s))))) line))
973 (defcustom org-export-odt-use-htmlfontify t
974 "Specify whether or not source blocks need to be fontified.
975 Turn this option on if you want to colorize the source code
976 blocks in the exported file. For colorization to work, you need
977 to make available an enhanced version of `htmlfontify' library."
978 :type 'boolean
979 :group 'org-export-odt)
981 (defun org-odt-format-source-code-or-example-plain
982 (lines lang caption textareap cols rows num cont rpllbl fmt)
983 "Format source or example blocks much like fixedwidth blocks.
984 Use this when `org-export-odt-use-htmlfontify' option is turned
985 off."
986 (setq lines (org-export-number-lines (org-xml-encode-plain-text-lines lines)
987 0 0 num cont rpllbl fmt))
988 (mapconcat
989 (lambda (line)
990 (org-odt-format-stylized-paragraph
991 'fixedwidth (org-odt-fill-tabs-and-spaces line)))
992 (org-split-string lines "[\r\n]") "\n"))
994 (defvar org-src-block-paragraph-format
995 "<style:style style:name=\"OrgSrcBlock\" style:family=\"paragraph\" style:parent-style-name=\"Preformatted_20_Text\">
996 <style:paragraph-properties fo:background-color=\"%s\" fo:padding=\"0.049cm\" fo:border=\"0.51pt solid #000000\" style:shadow=\"none\">
997 <style:background-image/>
998 </style:paragraph-properties>
999 <style:text-properties fo:color=\"%s\"/>
1000 </style:style>"
1001 "Custom paragraph style for colorized source and example blocks.
1002 This style is much the same as that of \"OrgFixedWidthBlock\"
1003 except that the foreground and background colors are set
1004 according to the default face identified by the `htmlfontify'.")
1006 (defun org-odt-hfy-face-to-css (fn)
1007 "Create custom style for face FN.
1008 When FN is the default face, use it's foreground and background
1009 properties to create \"OrgSrcBlock\" paragraph style. Otherwise
1010 use it's color attribute to create a character style whose name
1011 is obtained from FN. Currently all attributes of FN other than
1012 color are ignored.
1014 The style name for a face FN is derived using the following
1015 operations on the face name in that order - de-dash, CamelCase
1016 and prefix with \"OrgSrc\". For example,
1017 `font-lock-function-name-face' is associated with
1018 \"OrgSrcFontLockFunctionNameFace\"."
1019 (let* ((css-list (hfy-face-to-style fn))
1020 (style-name ((lambda (fn)
1021 (concat "OrgSrc"
1022 (mapconcat
1023 'capitalize (split-string
1024 (hfy-face-or-def-to-name fn) "-")
1025 ""))) fn))
1026 (color-val (cdr (assoc "color" css-list)))
1027 (background-color-val (cdr (assoc "background" css-list)))
1028 (style (and org-export-odt-create-custom-styles-for-srcblocks
1029 (cond
1030 ((eq fn 'default)
1031 (format org-src-block-paragraph-format
1032 background-color-val color-val))
1034 (format
1036 <style:style style:name=\"%s\" style:family=\"text\">
1037 <style:text-properties fo:color=\"%s\"/>
1038 </style:style>" style-name color-val))))))
1039 (cons style-name style)))
1041 (defcustom org-export-odt-create-custom-styles-for-srcblocks t
1042 "Whether custom styles for colorized source blocks be automatically created.
1043 When this option is turned on, the exporter creates custom styles
1044 for source blocks based on the advice of `htmlfontify'. Creation
1045 of custom styles happen as part of `org-odt-hfy-face-to-css'.
1047 When this option is turned off exporter does not create such
1048 styles.
1050 Use the latter option if you do not want the custom styles to be
1051 based on your current display settings. It is necessary that the
1052 styles.xml already contains needed styles for colorizing to work.
1054 This variable is effective only if
1055 `org-export-odt-use-htmlfontify' is turned on."
1056 :group 'org-export-odt
1057 :type 'boolean)
1059 (defun org-odt-insert-custom-styles-for-srcblocks (styles)
1060 "Save STYLES used for colorizing of source blocks.
1061 Update styles.xml with styles that were collected as part of
1062 `org-odt-hfy-face-to-css' callbacks."
1063 (when styles
1064 (with-current-buffer
1065 (find-file-noselect (expand-file-name "styles.xml") t)
1066 (goto-char (point-min))
1067 (when (re-search-forward "</office:styles>" nil t)
1068 (goto-char (match-beginning 0))
1069 (insert "\n<!-- Org Htmlfontify Styles -->\n" styles "\n")))))
1071 (defun org-odt-format-source-code-or-example-colored
1072 (lines lang caption textareap cols rows num cont rpllbl fmt)
1073 "Format source or example blocks using `htmlfontify-string'.
1074 Use this routine when `org-export-odt-use-htmlfontify' option is
1075 turned on."
1076 (let* ((lang-m (and lang (or (cdr (assoc lang org-src-lang-modes)) lang)))
1077 (mode (and lang-m (intern (concat (if (symbolp lang-m)
1078 (symbol-name lang-m)
1079 lang-m) "-mode"))))
1080 (org-inhibit-startup t)
1081 (org-startup-folded nil)
1082 (lines (with-temp-buffer
1083 (insert lines)
1084 (if (functionp mode) (funcall mode) (fundamental-mode))
1085 (font-lock-fontify-buffer)
1086 (buffer-string)))
1087 (hfy-html-quote-regex "\\([<\"&> ]\\)")
1088 (hfy-html-quote-map '(("\"" "&quot;")
1089 ("<" "&lt;")
1090 ("&" "&amp;")
1091 (">" "&gt;")
1092 (" " "<text:s/>")
1093 (" " "<text:tab/>")))
1094 (hfy-face-to-css 'org-odt-hfy-face-to-css)
1095 (hfy-optimisations-1 (copy-seq hfy-optimisations))
1096 (hfy-optimisations (add-to-list 'hfy-optimisations-1
1097 'body-text-only))
1098 (hfy-begin-span-handler
1099 (lambda (style text-block text-id text-begins-block-p)
1100 (insert (format "<text:span text:style-name=\"%s\">" style))))
1101 (hfy-end-span-handler (lambda nil (insert "</text:span>"))))
1102 (when (fboundp 'htmlfontify-string)
1103 (mapconcat
1104 (lambda (line)
1105 (org-odt-format-stylized-paragraph 'src (htmlfontify-string line)))
1106 (org-split-string lines "[\r\n]") "\n"))))
1108 (defun org-odt-format-source-code-or-example (lines lang caption textareap
1109 cols rows num cont
1110 rpllbl fmt)
1111 "Format source or example blocks for export.
1112 Use `org-odt-format-source-code-or-example-plain' or
1113 `org-odt-format-source-code-or-example-colored' depending on the
1114 value of `org-export-odt-use-htmlfontify."
1115 (funcall
1116 (if (and org-export-odt-use-htmlfontify
1117 (or (featurep 'htmlfontify) (require 'htmlfontify))
1118 (fboundp 'htmlfontify-string))
1119 'org-odt-format-source-code-or-example-colored
1120 'org-odt-format-source-code-or-example-plain)
1121 lines lang caption textareap cols rows num cont rpllbl fmt))
1123 (defun org-xml-encode-plain-text-lines (rtn)
1124 (mapconcat 'org-xml-encode-plain-text (org-split-string rtn "[\r\n]") "\n"))
1126 (defun org-odt-remap-stylenames (style-name)
1128 (cdr (assoc style-name '(("timestamp-wrapper" . "OrgTimestampWrapper")
1129 ("timestamp" . "OrgTimestamp")
1130 ("timestamp-kwd" . "OrgTimestampKeyword")
1131 ("tag" . "OrgTag")
1132 ("todo" . "OrgTodo")
1133 ("done" . "OrgDone")
1134 ("target" . "OrgTarget"))))
1135 style-name))
1137 (defun org-odt-format-fontify (text style &optional id)
1138 (let* ((style-name
1139 (cond
1140 ((stringp style)
1141 (org-odt-remap-stylenames style))
1142 ((symbolp style)
1143 (org-odt-get-style-name-for-entity 'character style))
1144 ((listp style)
1145 (assert (< 1 (length style)))
1146 (let ((parent-style (pop style)))
1147 (mapconcat (lambda (s)
1148 ;; (assert (stringp s) t)
1149 (org-odt-remap-stylenames s)) style "")
1150 (org-odt-remap-stylenames parent-style)))
1151 (t (error "Don't how to handle style %s" style)))))
1152 (org-odt-format-tags
1153 '("<text:span text:style-name=\"%s\">" . "</text:span>")
1154 text style-name)))
1156 (defun org-odt-relocate-relative-path (path dir)
1157 (if (file-name-absolute-p path) path
1158 (file-relative-name (expand-file-name path dir)
1159 (expand-file-name "eyecandy" dir))))
1161 (defun org-odt-format-inline-image (thefile)
1162 (let* ((thelink (if (file-name-absolute-p thefile) thefile
1163 (org-xml-format-href
1164 (org-odt-relocate-relative-path
1165 thefile org-current-export-file))))
1166 (href
1167 (org-odt-format-tags
1168 "<draw:image xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>" ""
1169 (if org-export-odt-embed-images
1170 (org-odt-copy-image-file thefile) thelink))))
1171 (org-export-odt-format-image thefile href)))
1173 (defun org-export-odt-do-format-numbered-formula (embed-as caption attr label
1174 width height href)
1175 (with-temp-buffer
1176 (let ((org-lparse-table-colalign-info '((0 "c" "8") (0 "c" "1"))))
1177 (org-lparse-insert-list-table
1178 `((,(org-export-odt-do-format-formula ; caption and label
1179 ; should be nil
1180 embed-as nil attr nil width height href)
1181 ,(org-odt-format-entity-caption label caption "Equation")))
1182 nil nil nil nil nil org-lparse-table-colalign-info))
1183 (buffer-substring-no-properties (point-min) (point-max))))
1185 (defun org-export-odt-do-format-formula (embed-as caption attr label
1186 width height href)
1187 "Create image tag with source and attributes."
1188 (save-match-data
1189 (cond
1190 ((and (not caption) (not label))
1191 (let (style-name anchor-type)
1192 (case embed-as
1193 (paragraph
1194 (setq style-name "OrgSimpleGraphics" anchor-type "paragraph"))
1195 (character
1196 (setq style-name "OrgInlineGraphics" anchor-type "as-char"))
1198 (error "Unknown value for embed-as %S" embed-as)))
1199 (org-odt-format-frame href style-name width height nil anchor-type)))
1201 (concat
1202 (org-odt-format-textbox
1203 (org-odt-format-stylized-paragraph
1204 'illustration
1205 (concat
1206 (let ((extra ""))
1207 (org-odt-format-frame
1208 href "" width height extra "paragraph"))
1209 (org-odt-format-entity-caption label caption "Equation")))
1210 "OrgCaptionFrame" width height))))))
1212 (defun org-export-odt-format-formula (src href &optional embed-as)
1213 "Create image tag with source and attributes."
1214 (save-match-data
1215 (let* ((caption (org-find-text-property-in-string 'org-caption src))
1216 (caption (and caption (org-xml-format-desc caption)))
1217 (attr (org-find-text-property-in-string 'org-attributes src))
1218 (label (org-find-text-property-in-string 'org-label src))
1219 (embed-as (or embed-as
1220 (and (org-find-text-property-in-string
1221 'org-latex-src src)
1222 (org-find-text-property-in-string
1223 'org-latex-src-embed-type src))
1224 'paragraph))
1225 (attr-plist (when attr (read attr)))
1226 (width (plist-get attr-plist :width))
1227 (height (plist-get attr-plist :height)))
1228 (org-export-odt-do-format-formula
1229 embed-as caption attr label width height href))))
1231 (defvar org-odt-embedded-formulas-count 0)
1232 (defun org-odt-copy-formula-file (path)
1233 "Returns the internal name of the file"
1234 (let* ((src-file (expand-file-name
1235 path (file-name-directory org-current-export-file)))
1236 (target-dir (format "Formula-%04d/"
1237 (incf org-odt-embedded-formulas-count)))
1238 (target-file (concat target-dir "content.xml")))
1239 (when (not org-lparse-to-buffer)
1240 (message "Embedding %s as %s ..."
1241 (substring-no-properties path) target-file)
1243 (make-directory target-dir)
1244 (org-odt-create-manifest-file-entry
1245 "application/vnd.oasis.opendocument.formula" target-dir "1.2")
1247 (copy-file src-file target-file 'overwrite)
1248 (org-odt-create-manifest-file-entry "text/xml" target-file))
1249 target-file))
1251 (defun org-odt-format-inline-formula (thefile)
1252 (let* ((thelink (if (file-name-absolute-p thefile) thefile
1253 (org-xml-format-href
1254 (org-odt-relocate-relative-path
1255 thefile org-current-export-file))))
1256 (href
1257 (org-odt-format-tags
1258 "<draw:object xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>" ""
1259 (file-name-directory (org-odt-copy-formula-file thefile)))))
1260 (org-export-odt-format-formula thefile href)))
1262 (defun org-odt-is-formula-link-p (file)
1263 (member (downcase (file-name-extension file)) '("mathml")))
1265 (defun org-odt-format-org-link (opt-plist type-1 path fragment desc attr
1266 descp)
1267 "Make an HTML link.
1268 OPT-PLIST is an options list.
1269 TYPE is the device-type of the link (THIS://foo.html)
1270 PATH is the path of the link (http://THIS#locationx)
1271 FRAGMENT is the fragment part of the link, if any (foo.html#THIS)
1272 DESC is the link description, if any.
1273 ATTR is a string of other attributes of the a element.
1274 MAY-INLINE-P allows inlining it as an image."
1275 (declare (special org-lparse-par-open))
1276 (save-match-data
1277 (let* ((may-inline-p
1278 (and (member type-1 '("http" "https" "file"))
1279 (org-lparse-should-inline-p path descp)
1280 (not fragment)))
1281 (type (if (equal type-1 "id") "file" type-1))
1282 (filename path)
1283 (thefile path))
1284 (cond
1285 ;; check for inlined images
1286 ((and (member type '("file"))
1287 (not fragment)
1288 (org-file-image-p
1289 filename org-odt-export-inline-image-extensions)
1290 (or (eq t org-odt-export-inline-images)
1291 (and org-odt-export-inline-images (not descp))))
1292 (org-odt-format-inline-image thefile))
1293 ;; check for embedded formulas
1294 ((and (member type '("file"))
1295 (not fragment)
1296 (org-odt-is-formula-link-p filename)
1297 (or (not descp)))
1298 (org-odt-format-inline-formula thefile))
1300 (when (string= type "file")
1301 (setq thefile
1302 (cond
1303 ((file-name-absolute-p path)
1304 (concat "file://" (expand-file-name path)))
1305 (t (org-odt-relocate-relative-path
1306 thefile org-current-export-file)))))
1308 (when (and (member type '("" "http" "https" "file" "coderef"))
1309 fragment)
1310 (setq thefile (concat thefile "#" fragment)))
1312 (setq thefile (org-xml-format-href thefile))
1314 (when (not (member type '("" "file" "coderef")))
1315 (setq thefile (concat type ":" thefile)))
1317 (let ((org-odt-suppress-xref (string= type "coderef")))
1318 (org-odt-format-link
1319 (org-xml-format-desc desc) thefile attr)))))))
1321 (defun org-odt-format-heading (text level &optional id)
1322 (let* ((text (if id (org-odt-format-target text id) text)))
1323 (org-odt-format-tags
1324 '("<text:h text:style-name=\"Heading_20_%s\" text:outline-level=\"%s\">" .
1325 "</text:h>") text level level)))
1327 (defun org-odt-format-headline (title extra-targets tags
1328 &optional snumber level)
1329 (concat
1330 (org-lparse-format 'EXTRA-TARGETS extra-targets)
1332 ;; No need to generate section numbers. They are auto-generated by
1333 ;; the application
1335 ;; (concat (org-lparse-format 'SECTION-NUMBER snumber level) " ")
1336 title
1337 (and tags (concat (org-lparse-format 'SPACES 3)
1338 (org-lparse-format 'ORG-TAGS tags)))))
1340 (defun org-odt-format-anchor (text name &optional class)
1341 (org-odt-format-target text name))
1343 (defun org-odt-format-bookmark (text id)
1344 (if id
1345 (org-odt-format-tags "<text:bookmark text:name=\"%s\"/>" text id)
1346 text))
1348 (defun org-odt-format-target (text id)
1349 (let ((name (concat org-export-odt-bookmark-prefix id)))
1350 (concat
1351 (and id (org-odt-format-tags
1352 "<text:bookmark-start text:name=\"%s\"/>" "" name))
1353 (org-odt-format-bookmark text id)
1354 (and id (org-odt-format-tags
1355 "<text:bookmark-end text:name=\"%s\"/>" "" name)))))
1357 (defun org-odt-format-footnote (n def)
1358 (let ((id (concat "fn" n))
1359 (note-class "footnote")
1360 (par-style "Footnote"))
1361 (org-odt-format-tags
1362 '("<text:note text:id=\"%s\" text:note-class=\"%s\">" .
1363 "</text:note>")
1364 (concat
1365 (org-odt-format-tags
1366 '("<text:note-citation>" . "</text:note-citation>")
1368 (org-odt-format-tags
1369 '("<text:note-body>" . "</text:note-body>")
1370 def))
1371 id note-class)))
1373 (defun org-odt-format-footnote-reference (n def refcnt)
1374 (if (= refcnt 1)
1375 (org-odt-format-footnote n def)
1376 (org-odt-format-footnote-ref n)))
1378 (defun org-odt-format-footnote-ref (n)
1379 (let ((note-class "footnote")
1380 (ref-format "text")
1381 (ref-name (concat "fn" n)))
1382 (org-odt-format-tags
1383 '("<text:span text:style-name=\"%s\">" . "</text:span>")
1384 (org-odt-format-tags
1385 '("<text:note-ref text:note-class=\"%s\" text:reference-format=\"%s\" text:ref-name=\"%s\">" . "</text:note-ref>")
1386 n note-class ref-format ref-name)
1387 "OrgSuperscript")))
1389 (defun org-odt-get-image-name (file-name)
1390 (require 'sha1)
1391 (file-relative-name
1392 (expand-file-name
1393 (concat (sha1 file-name) "." (file-name-extension file-name)) "Pictures")))
1395 (defun org-export-odt-format-image (src href &optional embed-as)
1396 "Create image tag with source and attributes."
1397 (save-match-data
1398 (let* ((caption (org-find-text-property-in-string 'org-caption src))
1399 (caption (and caption (org-xml-format-desc caption)))
1400 (attr (org-find-text-property-in-string 'org-attributes src))
1401 (label (org-find-text-property-in-string 'org-label src))
1402 (embed-as (or embed-as
1403 (if (org-find-text-property-in-string
1404 'org-latex-src src)
1405 (or (org-find-text-property-in-string
1406 'org-latex-src-embed-type src) 'character)
1407 'paragraph)))
1408 (attr-plist (when attr (read attr)))
1409 (size (org-odt-image-size-from-file
1410 src (plist-get attr-plist :width)
1411 (plist-get attr-plist :height)
1412 (plist-get attr-plist :scale) nil embed-as)))
1413 (org-export-odt-do-format-image
1414 embed-as caption attr label (car size) (cdr size) href))))
1416 (defun org-odt-format-frame (text style &optional
1417 width height extra anchor-type)
1418 (let ((frame-attrs
1419 (concat
1420 (if width (format " svg:width=\"%0.2fcm\"" width) "")
1421 (if height (format " svg:height=\"%0.2fcm\"" height) "")
1422 extra
1423 (format " text:anchor-type=\"%s\"" (or anchor-type "paragraph")))))
1424 (org-odt-format-tags
1425 '("<draw:frame draw:style-name=\"%s\"%s>" . "</draw:frame>")
1426 text style frame-attrs)))
1428 (defun org-odt-format-textbox (text style &optional width height extra)
1429 (org-odt-format-frame
1430 (org-odt-format-tags
1431 '("<draw:text-box %s>" . "</draw:text-box>")
1432 text (concat (format " fo:min-height=\"%0.2fcm\"" (or height .2))
1433 (format " fo:min-width=\"%0.2fcm\"" (or width .2))))
1434 style width nil extra))
1436 (defun org-odt-format-inlinetask (heading content
1437 &optional todo priority tags)
1438 (org-odt-format-stylized-paragraph
1439 nil (org-odt-format-textbox
1440 (concat (org-odt-format-stylized-paragraph
1441 "OrgInlineTaskHeading"
1442 (org-lparse-format
1443 'HEADLINE (concat (org-lparse-format-todo todo) " " heading)
1444 nil tags))
1445 content) "OrgInlineTaskFrame" nil nil " style:rel-width=\"100%\"")))
1446 (defun org-export-odt-do-format-image (embed-as caption attr label
1447 width height href)
1448 "Create image tag with source and attributes."
1449 (save-match-data
1450 (cond
1451 ((and (not caption) (not label))
1452 (let (style-name anchor-type)
1453 (case embed-as
1454 (paragraph
1455 (setq style-name "OrgSimpleGraphics" anchor-type "paragraph"))
1456 (character
1457 (setq style-name "OrgInlineGraphics" anchor-type "as-char"))
1459 (error "Unknown value for embed-as %S" embed-as)))
1460 (org-odt-format-frame href style-name width height nil anchor-type)))
1462 (concat
1463 (org-odt-format-textbox
1464 (org-odt-format-stylized-paragraph
1465 'illustration
1466 (concat
1467 (let ((extra " style:rel-width=\"100%\" style:rel-height=\"scale\""))
1468 (org-odt-format-frame
1469 href "OrgCaptionedGraphics" width height extra "paragraph"))
1470 (org-odt-format-entity-caption label caption "Figure")))
1471 "OrgCaptionFrame" width height))))))
1473 (defvar org-odt-embedded-images-count 0)
1474 (defun org-odt-copy-image-file (path)
1475 "Returns the internal name of the file"
1476 (let* ((image-type (file-name-extension path))
1477 (media-type (format "image/%s" image-type))
1478 (src-file (expand-file-name
1479 path (file-name-directory org-current-export-file)))
1480 (target-dir "Images/")
1481 (target-file
1482 (format "%s%04d.%s" target-dir
1483 (incf org-odt-embedded-images-count) image-type)))
1484 (when (not org-lparse-to-buffer)
1485 (message "Embedding %s as %s ..."
1486 (substring-no-properties path) target-file)
1488 (when (= 1 org-odt-embedded-images-count)
1489 (make-directory target-dir)
1490 (org-odt-create-manifest-file-entry "" target-dir))
1492 (copy-file src-file target-file 'overwrite)
1493 (org-odt-create-manifest-file-entry media-type target-file))
1494 target-file))
1496 (defvar org-export-odt-image-size-probe-method
1497 '(emacs imagemagick force)
1498 "Ordered list of methods by for determining size of an embedded
1499 image.")
1501 (defvar org-export-odt-default-image-sizes-alist
1502 '(("character" . (5 . 0.4))
1503 ("paragraph" . (5 . 5)))
1504 "Hardcoded image dimensions one for each of the anchor
1505 methods.")
1507 (defun org-odt-do-image-size (probe-method file &optional dpi anchor-type)
1508 (setq dpi (or dpi org-export-odt-pixels-per-inch))
1509 (setq anchor-type (or anchor-type "paragraph"))
1510 (flet ((size-in-cms (size-in-pixels)
1511 (flet ((pixels-to-cms (pixels)
1512 (let* ((cms-per-inch 2.54)
1513 (inches (/ pixels dpi)))
1514 (* cms-per-inch inches))))
1515 (and size-in-pixels
1516 (cons (pixels-to-cms (car size-in-pixels))
1517 (pixels-to-cms (cdr size-in-pixels)))))))
1518 (case probe-method
1519 (emacs
1520 (size-in-cms (ignore-errors (image-size (create-image file) 'pixels))))
1521 (imagemagick
1522 (size-in-cms
1523 (let ((dim (shell-command-to-string
1524 (format "identify -format \"%%w:%%h\" \"%s\"" file))))
1525 (when (string-match "\\([0-9]+\\):\\([0-9]+\\)" dim)
1526 (cons (string-to-number (match-string 1 dim))
1527 (string-to-number (match-string 2 dim)))))))
1529 (cdr (assoc-string anchor-type
1530 org-export-odt-default-image-sizes-alist))))))
1532 (defun org-odt-image-size-from-file (file &optional user-width
1533 user-height scale dpi embed-as)
1534 (unless (file-name-absolute-p file)
1535 (setq file (expand-file-name
1536 file (file-name-directory org-current-export-file))))
1537 (let* (size width height)
1538 (unless (and user-height user-width)
1539 (loop for probe-method in org-export-odt-image-size-probe-method
1540 until size
1541 do (setq size (org-odt-do-image-size
1542 probe-method file dpi embed-as)))
1543 (or size (error "Cannot determine Image size. Aborting ..."))
1544 (setq width (car size) height (cdr size)))
1545 (cond
1546 (scale
1547 (setq width (* width scale) height (* height scale)))
1548 ((and user-height user-width)
1549 (setq width user-width height user-height))
1550 (user-height
1551 (setq width (* user-height (/ width height)) height user-height))
1552 (user-width
1553 (setq height (* user-width (/ height width)) width user-width))
1554 (t (ignore)))
1555 (cons width height)))
1557 (defvar org-odt-entity-labels-alist nil
1558 "Associate Labels with the Labelled entities.
1559 Each element of the alist is of the form (LABEL-NAME
1560 CATEGORY-NAME SEQNO). LABEL-NAME is same as that specified by
1561 \"#+LABEL: ...\" line. CATEGORY-NAME is the type of the entity
1562 that LABEL-NAME is attached to. CATEGORY-NAME can be one of
1563 \"Table\", \"Figure\" or \"Equation\". SEQNO is the unique
1564 number assigned to the referenced entity on a per-CATEGORY basis.
1565 It is generated sequentially and is 1-based.
1567 Update this alist with `org-odt-add-label-definition' and
1568 retrieve an entry with `org-odt-get-label-definition'.")
1570 (defvar org-odt-entity-counts-plist nil
1571 "Plist of running counters of SEQNOs for each of the CATEGORY-NAMEs.
1572 See `org-odt-entity-labels-alist' for known CATEGORY-NAMEs.")
1574 (defvar org-odt-label-def-ref-spec
1575 '(;; ("Equation" "(%n)" "text" "(%n)")
1576 ("" "%e %n%c" "category-and-value" "%e %n"))
1577 "Specify how labels are applied and referenced.
1578 This is an alist where each element is of the form (CATEGORY-NAME
1579 LABEL-APPLY-FMT LABEL-REF-MODE LABEL-REF-FMT). CATEGORY-NAME is
1580 as defined in `org-odt-entity-labels-alist'. It can additionally
1581 be an empty string in which case it is used as a catch-all
1582 specifier.
1584 LABEL-APPLY-FMT is used for applying labels and captions. It may
1585 contain following specifiers - %e, %n and %c. %e is replaced
1586 with the CATEGORY-NAME. %n is replaced with \"<text:sequence
1587 ...> SEQNO </text:sequence>\". %c is replaced with CAPTION. See
1588 `org-odt-format-label-definition'.
1590 LABEL-REF-MODE and LABEL-REF-FMT are used for generating the
1591 following label reference - \"<text:sequence-ref
1592 text:reference-format=\"LABEL-REF-MODE\" ...> LABEL-REF-FMT
1593 </text:sequence-ref>\". LABEL-REF-FMT may contain following
1594 specifiers - %e and %n. %e is replaced with the CATEGORY-NAME. %n is
1595 replaced with SEQNO. See `org-odt-format-label-reference'.")
1597 (defun org-odt-add-label-definition (label category)
1598 "Return (SEQNO . LABEL-APPLY-FMT).
1599 See `org-odt-label-def-ref-spec'."
1600 (setq label (substring-no-properties label))
1601 (let (seqno label-props fmt (category-sym (intern category)))
1602 (setq seqno (1+ (plist-get org-odt-entity-counts-plist category-sym))
1603 org-odt-entity-counts-plist (plist-put org-odt-entity-counts-plist
1604 category-sym seqno)
1605 fmt (cadr (or (assoc-string category org-odt-label-def-ref-spec t)
1606 (assoc-string "" org-odt-label-def-ref-spec t)))
1607 label-props (list label category seqno))
1608 (push label-props org-odt-entity-labels-alist)
1609 (cons seqno fmt)))
1611 (defun org-odt-get-label-definition (label)
1612 "Return (LABEL-NAME CATEGORY-NAME SEQNO LABEL-REF-MODE LABEL-REF-FMT).
1613 See `org-odt-entity-labels-alist' and
1614 `org-odt-label-def-ref-spec'."
1615 (let* ((label-props (assoc label org-odt-entity-labels-alist))
1616 (category (nth 1 label-props)))
1617 (append label-props
1618 (cddr (or (assoc-string category org-odt-label-def-ref-spec t)
1619 (assoc-string "" org-odt-label-def-ref-spec t))))))
1621 (defun org-odt-format-label-definition (label category caption)
1622 (assert label)
1623 (let* ((label-props (org-odt-add-label-definition label category))
1624 (seqno (car label-props))
1625 (fmt (cdr label-props)))
1626 (or (format-spec
1628 `((?e . ,category)
1629 (?n . ,(org-odt-format-tags
1630 '("<text:sequence text:ref-name=\"%s\" text:name=\"%s\" text:formula=\"ooow:%s+1\" style:num-format=\"1\">" . "</text:sequence>")
1631 (format "%d" seqno) label category category))
1632 (?c . ,(or (and caption (concat ": " caption)) ""))))
1633 caption "")))
1635 (defun org-odt-format-label-reference (label category seqno fmt1 fmt2)
1636 (assert label)
1637 (save-match-data
1638 (org-odt-format-tags
1639 '("<text:sequence-ref text:reference-format=\"%s\" text:ref-name=\"%s\">"
1640 . "</text:sequence-ref>")
1641 (format-spec fmt2 `((?e . ,category)
1642 (?n . ,(format "%d" seqno)))) fmt1 label)))
1644 (defun org-odt-fixup-label-references ()
1645 (goto-char (point-min))
1646 (while (re-search-forward
1647 "<text:sequence-ref text:ref-name=\"\\([^\"]+\\)\"/>" nil t)
1648 (let* ((label (match-string 1)))
1649 (replace-match
1650 (apply 'org-odt-format-label-reference
1651 (org-odt-get-label-definition label)) t t))))
1653 (defun org-odt-format-entity-caption (label caption category)
1654 (or (and label (org-odt-format-label-definition label category caption))
1655 caption ""))
1657 (defun org-odt-format-tags (tag text &rest args)
1658 (let ((prefix (when org-lparse-encode-pending "@"))
1659 (suffix (when org-lparse-encode-pending "@")))
1660 (apply 'org-lparse-format-tags tag text prefix suffix args)))
1662 (defun org-odt-init-outfile (filename)
1663 (unless (executable-find "zip")
1664 ;; Not at all OSes ship with zip by default
1665 (error "Executable \"zip\" needed for creating OpenDocument files"))
1667 (let* ((outdir (make-temp-file org-export-odt-tmpdir-prefix t))
1668 (content-file (expand-file-name "content.xml" outdir)))
1670 ;; init conten.xml
1671 (with-current-buffer (find-file-noselect content-file t))
1673 ;; reset variables
1674 (setq org-odt-manifest-file-entries nil
1675 org-odt-embedded-images-count 0
1676 org-odt-embedded-formulas-count 0
1677 org-odt-entity-labels-alist nil
1678 org-odt-entity-counts-plist (list 'Table 0 'Equation 0 'Figure 0))
1679 content-file))
1681 (defcustom org-export-odt-prettify-xml nil
1682 "Specify whether or not the xml output should be prettified.
1683 When this option is turned on, `indent-region' is run on all
1684 component xml buffers before they are saved. Turn this off for
1685 regular use. Turn this on if you need to examine the xml
1686 visually."
1687 :group 'org-export-odt
1688 :type 'boolean)
1690 (defvar hfy-user-sheet-assoc) ; bound during org-do-lparse
1691 (defun org-odt-save-as-outfile (target opt-plist)
1692 ;; create mimetype file
1693 (write-region "application/vnd.oasis.opendocument.text" nil
1694 (expand-file-name "mimetype"))
1696 ;; write meta file
1697 (org-odt-update-meta-file opt-plist)
1699 ;; write styles file
1700 (org-odt-copy-styles-file)
1702 ;; Update styles.xml - take care of outline numbering
1703 (with-current-buffer
1704 (find-file-noselect (expand-file-name "styles.xml") t)
1705 ;; Don't make automatic backup of styles.xml file. This setting
1706 ;; prevents the backedup styles.xml file from being zipped in to
1707 ;; odt file. This is more of a hackish fix. Better alternative
1708 ;; would be to fix the zip command so that the output odt file
1709 ;; includes only the needed files and excludes any auto-generated
1710 ;; extra files like backups and auto-saves etc etc. Note that
1711 ;; currently the zip command zips up the entire temp directory so
1712 ;; that any auto-generated files created under the hood ends up in
1713 ;; the resulting odt file.
1714 (set (make-local-variable 'backup-inhibited) t)
1716 ;; Import local setting of `org-export-with-section-numbers'
1717 (org-lparse-bind-local-variables opt-plist)
1718 (org-odt-configure-outline-numbering
1719 (if org-export-with-section-numbers org-export-headline-levels 0)))
1721 ;; Write custom stlyes for source blocks
1722 (org-odt-insert-custom-styles-for-srcblocks
1723 (mapconcat
1724 (lambda (style)
1725 (format " %s\n" (cddr style)))
1726 hfy-user-sheet-assoc ""))
1728 ;; create a manifest entry for content.xml
1729 (org-odt-create-manifest-file-entry
1730 "application/vnd.oasis.opendocument.text" "/" "1.2")
1732 (org-odt-create-manifest-file-entry "text/xml" "content.xml")
1734 ;; write out the manifest entries before zipping
1735 (org-odt-write-manifest-file)
1737 (let ((xml-files '("mimetype" "META-INF/manifest.xml" "content.xml"
1738 "meta.xml" "styles.xml"))
1739 (zipdir default-directory))
1740 (message "Switching to directory %s" (expand-file-name zipdir))
1742 ;; save all xml files
1743 (mapc (lambda (file)
1744 (with-current-buffer
1745 (find-file-noselect (expand-file-name file) t)
1746 ;; prettify output if needed
1747 (when org-export-odt-prettify-xml
1748 (indent-region (point-min) (point-max)))
1749 (save-buffer 0)))
1750 xml-files)
1752 (let* ((target-name (file-name-nondirectory target))
1753 (target-dir (file-name-directory target))
1754 (cmds `(("zip" "-mX0" ,target-name "mimetype")
1755 ("zip" "-rmTq" ,target-name "."))))
1756 (when (file-exists-p target)
1757 ;; FIXME: If the file is locked this throws a cryptic error
1758 (delete-file target))
1760 (let ((coding-system-for-write 'no-conversion) exitcode)
1761 (message "Creating odt file...")
1762 (mapc
1763 (lambda (cmd)
1764 (message "Running %s" (mapconcat 'identity cmd " "))
1765 (setq exitcode
1766 (apply 'call-process (car cmd) nil nil nil (cdr cmd)))
1767 (or (zerop exitcode)
1768 (error "Unable to create odt file (%S)" exitcode)))
1769 cmds))
1771 ;; move the file from outdir to target-dir
1772 (rename-file target-name target-dir)
1774 ;; kill all xml buffers
1775 (mapc (lambda (file)
1776 (kill-buffer
1777 (find-file-noselect (expand-file-name file zipdir) t)))
1778 xml-files)
1780 (delete-directory zipdir)))
1782 (message "Created %s" target)
1783 (set-buffer (find-file-noselect target t)))
1785 (defun org-odt-format-date (date)
1786 (let ((warning-msg
1787 "OpenDocument files require that dates be in ISO-8601 format. Please review your DATE options for compatibility."))
1788 ;; If the user is not careful with the date specification, an
1789 ;; invalid meta.xml will be emitted.
1791 ;; For now honor user's diktat and let him off with a warning
1792 ;; message. This is OK as LibreOffice (and possibly other
1793 ;; apps) doesn't deem this deviation as critical and continue
1794 ;; to load the file.
1796 ;; FIXME: Surely there a better way to handle this. Revisit this
1797 ;; later.
1798 (cond
1799 ((and date (string-match "%" date))
1800 ;; Honor user's diktat. See comments above
1801 (org-lparse-warn warning-msg)
1802 (format-time-string date))
1803 (date
1804 ;; Honor user's diktat. See comments above
1805 (org-lparse-warn warning-msg)
1806 date)
1808 ;; ISO 8601 format
1809 (let ((stamp (format-time-string "%Y-%m-%dT%H:%M:%S%z")))
1810 (format "%s:%s" (substring stamp 0 -2) (substring stamp -2)))))))
1812 (defconst org-odt-manifest-file-entry-tag
1814 <manifest:file-entry manifest:media-type=\"%s\" manifest:full-path=\"%s\"%s/>")
1816 (defvar org-odt-manifest-file-entries nil)
1818 (defun org-odt-create-manifest-file-entry (&rest args)
1819 (push args org-odt-manifest-file-entries))
1821 (defun org-odt-write-manifest-file ()
1822 (make-directory "META-INF")
1823 (let ((manifest-file (expand-file-name "META-INF/manifest.xml")))
1824 (write-region
1825 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
1826 <manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"1.2\">\n"
1827 nil manifest-file)
1828 (mapc
1829 (lambda (file-entry)
1830 (let* ((version (nth 2 file-entry))
1831 (extra (if version
1832 (format " manifest:version=\"%s\"" version)
1833 "")))
1834 (write-region
1835 (format org-odt-manifest-file-entry-tag
1836 (nth 0 file-entry) (nth 1 file-entry) extra)
1837 nil manifest-file t))) org-odt-manifest-file-entries)
1838 (write-region "\n</manifest:manifest>" nil manifest-file t)))
1840 (defun org-odt-update-meta-file (opt-plist)
1841 (let ((date (org-odt-format-date (plist-get opt-plist :date)))
1842 (author (or (plist-get opt-plist :author) ""))
1843 (email (plist-get opt-plist :email))
1844 (keywords (plist-get opt-plist :keywords))
1845 (description (plist-get opt-plist :description))
1846 (title (plist-get opt-plist :title)))
1848 (write-region
1849 (concat
1850 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
1851 <office:document-meta
1852 xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"
1853 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
1854 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
1855 xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"
1856 xmlns:ooo=\"http://openoffice.org/2004/office\"
1857 office:version=\"1.2\">
1858 <office:meta>" "\n"
1859 (org-odt-format-tags '("<dc:creator>" . "</dc:creator>") author)
1860 (org-odt-format-tags
1861 '("\n<meta:initial-creator>" . "</meta:initial-creator>") author)
1862 (org-odt-format-tags '("\n<dc:date>" . "</dc:date>") date)
1863 (org-odt-format-tags
1864 '("\n<meta:creation-date>" . "</meta:creation-date>") date)
1865 (org-odt-format-tags '("\n<meta:generator>" . "</meta:generator>")
1866 (when org-export-creator-info
1867 (format "Org-%s/Emacs-%s"
1868 org-version emacs-version)))
1869 (org-odt-format-tags '("\n<meta:keyword>" . "</meta:keyword>") keywords)
1870 (org-odt-format-tags '("\n<dc:subject>" . "</dc:subject>") description)
1871 (org-odt-format-tags '("\n<dc:title>" . "</dc:title>") title)
1872 "\n"
1873 " </office:meta>" "</office:document-meta>")
1874 nil (expand-file-name "meta.xml")))
1876 ;; create a manifest entry for meta.xml
1877 (org-odt-create-manifest-file-entry "text/xml" "meta.xml"))
1879 (defun org-odt-finalize-outfile ()
1880 (org-odt-delete-empty-paragraphs))
1882 (defun org-odt-delete-empty-paragraphs ()
1883 (goto-char (point-min))
1884 (let ((open "<text:p[^>]*>")
1885 (close "</text:p>"))
1886 (while (re-search-forward (format "%s[ \r\n\t]*%s" open close) nil t)
1887 (replace-match ""))))
1889 (defun org-odt-get (what &optional opt-plist)
1890 (case what
1891 (BACKEND 'odt)
1892 (EXPORT-DIR (org-export-directory :html opt-plist))
1893 (FILE-NAME-EXTENSION "odt")
1894 (EXPORT-BUFFER-NAME "*Org ODT Export*")
1895 (ENTITY-CONTROL org-odt-entity-control-callbacks-alist)
1896 (ENTITY-FORMAT org-odt-entity-format-callbacks-alist)
1897 (INIT-METHOD 'org-odt-init-outfile)
1898 (FINAL-METHOD 'org-odt-finalize-outfile)
1899 (SAVE-METHOD 'org-odt-save-as-outfile)
1900 ;; (OTHER-BACKENDS) ; see note in `org-xhtml-get'
1901 ;; (CONVERT-METHOD) ; see note in `org-xhtml-get'
1902 (TOPLEVEL-HLEVEL 1)
1903 (SPECIAL-STRING-REGEXPS org-export-odt-special-string-regexps)
1904 (INLINE-IMAGES 'maybe)
1905 (INLINE-IMAGE-EXTENSIONS '("png" "jpeg" "jpg" "gif" "svg"))
1906 (PLAIN-TEXT-MAP '(("&" . "&amp;") ("<" . "&lt;") (">" . "&gt;")))
1907 (TABLE-FIRST-COLUMN-AS-LABELS nil)
1908 (FOOTNOTE-SEPARATOR (org-lparse-format 'FONTIFY "," 'superscript))
1909 (CODING-SYSTEM-FOR-WRITE 'utf-8)
1910 (CODING-SYSTEM-FOR-SAVE 'utf-8)
1911 (t (error "Unknown property: %s" what))))
1913 (defvar org-lparse-latex-fragment-fallback) ; set by org-do-lparse
1914 (defvar org-lparse-opt-plist) ; bound during org-do-lparse
1915 (defun org-export-odt-do-preprocess-latex-fragments ()
1916 "Convert LaTeX fragments to images."
1917 (let* ((latex-frag-opt (plist-get org-lparse-opt-plist :LaTeX-fragments))
1918 (latex-frag-opt ; massage the options
1919 (or (and (member latex-frag-opt '(mathjax t))
1920 (not (and (fboundp 'org-format-latex-mathml-available-p)
1921 (org-format-latex-mathml-available-p)))
1922 (prog1 org-lparse-latex-fragment-fallback
1923 (org-lparse-warn
1924 (concat
1925 "LaTeX to MathML converter not available. "
1926 (format "Using %S instead."
1927 org-lparse-latex-fragment-fallback)))))
1928 latex-frag-opt))
1929 cache-dir display-msg)
1930 (cond
1931 ((eq latex-frag-opt 'dvipng)
1932 (setq cache-dir "ltxpng/")
1933 (setq display-msg "Creating LaTeX image %s"))
1934 ((member latex-frag-opt '(mathjax t))
1935 (setq latex-frag-opt 'mathml)
1936 (setq cache-dir "ltxmathml/")
1937 (setq display-msg "Creating MathML formula %s")))
1938 (when (and org-current-export-file)
1939 (org-format-latex
1940 (concat cache-dir (file-name-sans-extension
1941 (file-name-nondirectory org-current-export-file)))
1942 org-current-export-dir nil display-msg
1943 nil nil latex-frag-opt))))
1945 (defun org-export-odt-preprocess-latex-fragments ()
1946 (when (equal org-export-current-backend 'odt)
1947 (org-export-odt-do-preprocess-latex-fragments)))
1949 (defun org-export-odt-preprocess-label-references ()
1950 (goto-char (point-min))
1951 (let (label label-components category value pretty-label)
1952 (while (re-search-forward "\\\\ref{\\([^{}\n]+\\)}" nil t)
1953 (org-if-unprotected-at (match-beginning 1)
1954 (replace-match
1955 (let ((org-lparse-encode-pending t)
1956 (label (match-string 1)))
1957 ;; markup generated below is mostly an eye-candy. At
1958 ;; pre-processing stage, there is no information on which
1959 ;; entity a label reference points to. The actual markup
1960 ;; is generated as part of `org-odt-fixup-label-references'
1961 ;; which gets called at the fag end of export. By this
1962 ;; time we would have seen and collected all the label
1963 ;; definitions in `org-odt-entity-labels-alist'.
1964 (org-odt-format-tags
1965 "<text:sequence-ref text:ref-name=\"%s\"/>" "" label)) t t)))))
1967 ;; process latex fragments as part of
1968 ;; `org-export-preprocess-after-blockquote-hook'. Note that this hook
1969 ;; is the one that is closest and well before the call to
1970 ;; `org-export-attach-captions-and-attributes' in
1971 ;; `org-export-preprocess-stirng'. The above arrangement permits
1972 ;; captions, labels and attributes to be attached to png images
1973 ;; generated out of latex equations.
1974 (add-hook 'org-export-preprocess-after-blockquote-hook
1975 'org-export-odt-preprocess-latex-fragments)
1977 (defun org-export-odt-preprocess (parameters)
1978 (org-export-odt-preprocess-label-references))
1980 (declare-function archive-zip-extract "arc-mode.el" (archive name))
1981 (defun org-odt-zip-extract-one (archive member &optional target)
1982 (require 'arc-mode)
1983 (let* ((target (or target default-directory))
1984 (archive (expand-file-name archive))
1985 (archive-zip-extract
1986 (list "unzip" "-qq" "-o" "-d" target))
1987 exit-code command-output)
1988 (setq command-output
1989 (with-temp-buffer
1990 (setq exit-code (archive-zip-extract archive member))
1991 (buffer-string)))
1992 (unless (zerop exit-code)
1993 (message command-output)
1994 (error "Extraction failed"))))
1996 (defun org-odt-zip-extract (archive members &optional target)
1997 (when (atom members) (setq members (list members)))
1998 (mapc (lambda (member)
1999 (org-odt-zip-extract-one archive member target))
2000 members))
2002 (defun org-odt-copy-styles-file (&optional styles-file)
2003 ;; Non-availability of styles.xml is not a critical error. For now
2004 ;; throw an error purely for aesthetic reasons.
2005 (setq styles-file (or styles-file
2006 org-export-odt-styles-file
2007 (expand-file-name "styles/OrgOdtStyles.xml"
2008 org-odt-data-dir)
2009 (error "org-odt: Missing styles file?")))
2010 (cond
2011 ((listp styles-file)
2012 (let ((archive (nth 0 styles-file))
2013 (members (nth 1 styles-file)))
2014 (org-odt-zip-extract archive members)
2015 (mapc
2016 (lambda (member)
2017 (when (org-file-image-p member)
2018 (let* ((image-type (file-name-extension member))
2019 (media-type (format "image/%s" image-type)))
2020 (org-odt-create-manifest-file-entry media-type member))))
2021 members)))
2022 ((and (stringp styles-file) (file-exists-p styles-file))
2023 (let ((styles-file-type (file-name-extension styles-file)))
2024 (cond
2025 ((string= styles-file-type "xml")
2026 (copy-file styles-file "styles.xml" t))
2027 ((member styles-file-type '("odt" "ott"))
2028 (org-odt-zip-extract styles-file "styles.xml")))))
2030 (error (format "Invalid specification of styles.xml file: %S"
2031 org-export-odt-styles-file))))
2033 ;; create a manifest entry for styles.xml
2034 (org-odt-create-manifest-file-entry "text/xml" "styles.xml"))
2036 (defvar org-export-odt-factory-settings
2037 "d4328fb9d1b6cb211d4320ff546829f26700dc5e"
2038 "SHA1 hash of OrgOdtStyles.xml.")
2040 (defun org-odt-configure-outline-numbering (level)
2041 "Outline numbering is retained only upto LEVEL.
2042 To disable outline numbering pass a LEVEL of 0."
2043 (goto-char (point-min))
2044 (let ((regex
2045 "<text:outline-level-style\\(.*\\)text:level=\"\\([^\"]*\\)\"\\(.*\\)>")
2046 (replacement
2047 "<text:outline-level-style\\1text:level=\"\\2\" style:num-format=\"\">"))
2048 (while (re-search-forward regex nil t)
2049 (when (> (string-to-number (match-string 2)) level)
2050 (replace-match replacement t nil))))
2051 (save-buffer 0))
2053 (provide 'org-odt)
2055 ;;; org-odt.el ends here