org-odt.el: Add bottom margin to source or example blocks
[org-mode.git] / contrib / lisp / org-odt.el
blob4c516e12637b12cda0d5d4a13a2f0a39cb0e137f
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 (let ((xref-format "text"))
921 (when (numberp desc)
922 (setq desc (format "%d" desc) xref-format "number"))
923 (org-odt-format-tags
924 '("<text:bookmark-ref text:reference-format=\"%s\" text:ref-name=\"%s\">" .
925 "</text:bookmark-ref>")
926 desc xref-format href)))
927 (org-lparse-link-description-is-image
928 (org-odt-format-tags
929 '("<draw:a xlink:type=\"simple\" xlink:href=\"%s\" %s>" . "</draw:a>")
930 desc href (or attr "")))
932 (org-odt-format-tags
933 '("<text:a xlink:type=\"simple\" xlink:href=\"%s\" %s>" . "</text:a>")
934 desc href (or attr "")))))
936 (defun org-odt-format-spaces (n)
937 (cond
938 ((= n 1) " ")
939 ((> n 1) (concat
940 " " (org-odt-format-tags "<text:s text:c=\"%d\"/>" "" (1- n))))
941 (t "")))
943 (defun org-odt-format-tabs (&optional n)
944 (let ((tab "<text:tab/>")
945 (n (or n 1)))
946 (insert tab)))
948 (defun org-odt-format-line-break ()
949 (org-odt-format-tags "<text:line-break/>" ""))
951 (defun org-odt-format-horizontal-line ()
952 (org-odt-format-stylized-paragraph 'horizontal-line ""))
954 (defun org-odt-format-line (line)
955 (case org-lparse-dyn-current-environment
956 (fixedwidth (concat
957 (org-odt-format-stylized-paragraph
958 'fixedwidth (org-odt-fill-tabs-and-spaces
959 (org-xml-encode-plain-text line))) "\n"))
960 (t (concat line "\n"))))
962 (defun org-odt-format-comment (fmt &rest args)
963 (let ((comment (apply 'format fmt args)))
964 (format "\n<!-- %s -->\n" comment)))
966 (defun org-odt-format-org-entity (wd)
967 (org-entity-get-representation wd 'utf8))
969 (defun org-odt-fill-tabs-and-spaces (line)
970 (replace-regexp-in-string
971 "\\([\t]\\|\\([ ]+\\)\\)" (lambda (s)
972 (cond
973 ((string= s "\t") (org-odt-format-tabs))
974 (t (org-odt-format-spaces (length s))))) line))
976 (defcustom org-export-odt-use-htmlfontify t
977 "Specify whether or not source blocks need to be fontified.
978 Turn this option on if you want to colorize the source code
979 blocks in the exported file. For colorization to work, you need
980 to make available an enhanced version of `htmlfontify' library."
981 :type 'boolean
982 :group 'org-export-odt)
984 (defun org-odt-format-source-line-with-line-number-and-label
985 (line rpllbl num fontifier par-style)
987 (let ((keep-label (not (numberp rpllbl)))
988 (ref (org-find-text-property-in-string 'org-coderef line)))
989 (setq line (concat line (and keep-label ref (format "(%s)" ref))))
990 (setq line (funcall fontifier line))
991 (when ref
992 (setq line (org-odt-format-target line (concat "coderef-" ref))))
993 (setq line (org-odt-format-stylized-paragraph par-style line))
994 (when num
995 (org-odt-format-tags '("<text:list-item>" . "</text:list-item>") line))))
997 (defun org-odt-format-source-code-or-example-plain
998 (lines lang caption textareap cols rows num cont rpllbl fmt)
999 "Format source or example blocks much like fixedwidth blocks.
1000 Use this when `org-export-odt-use-htmlfontify' option is turned
1001 off."
1002 (let* ((lines (org-split-string lines "[\r\n]"))
1003 (line-count (length lines))
1004 (i 0))
1005 (mapconcat
1006 (lambda (line)
1007 (incf i)
1008 (org-odt-format-source-line-with-line-number-and-label
1009 line rpllbl num (lambda (line)
1010 (org-odt-fill-tabs-and-spaces
1011 (org-xml-encode-plain-text line)))
1012 (if (= i line-count) "OrgFixedWidthBlockLastLine" "OrgFixedWidthBlock")))
1013 lines "\n")))
1015 (defvar org-src-block-paragraph-format
1016 "<style:style style:name=\"OrgSrcBlock\" style:family=\"paragraph\" style:parent-style-name=\"Preformatted_20_Text\">
1017 <style:paragraph-properties fo:background-color=\"%s\" fo:padding=\"0.049cm\" fo:border=\"0.51pt solid #000000\" style:shadow=\"none\">
1018 <style:background-image/>
1019 </style:paragraph-properties>
1020 <style:text-properties fo:color=\"%s\"/>
1021 </style:style>"
1022 "Custom paragraph style for colorized source and example blocks.
1023 This style is much the same as that of \"OrgFixedWidthBlock\"
1024 except that the foreground and background colors are set
1025 according to the default face identified by the `htmlfontify'.")
1027 (defun org-odt-hfy-face-to-css (fn)
1028 "Create custom style for face FN.
1029 When FN is the default face, use it's foreground and background
1030 properties to create \"OrgSrcBlock\" paragraph style. Otherwise
1031 use it's color attribute to create a character style whose name
1032 is obtained from FN. Currently all attributes of FN other than
1033 color are ignored.
1035 The style name for a face FN is derived using the following
1036 operations on the face name in that order - de-dash, CamelCase
1037 and prefix with \"OrgSrc\". For example,
1038 `font-lock-function-name-face' is associated with
1039 \"OrgSrcFontLockFunctionNameFace\"."
1040 (let* ((css-list (hfy-face-to-style fn))
1041 (style-name ((lambda (fn)
1042 (concat "OrgSrc"
1043 (mapconcat
1044 'capitalize (split-string
1045 (hfy-face-or-def-to-name fn) "-")
1046 ""))) fn))
1047 (color-val (cdr (assoc "color" css-list)))
1048 (background-color-val (cdr (assoc "background" css-list)))
1049 (style (and org-export-odt-create-custom-styles-for-srcblocks
1050 (cond
1051 ((eq fn 'default)
1052 (format org-src-block-paragraph-format
1053 background-color-val color-val))
1055 (format
1057 <style:style style:name=\"%s\" style:family=\"text\">
1058 <style:text-properties fo:color=\"%s\"/>
1059 </style:style>" style-name color-val))))))
1060 (cons style-name style)))
1062 (defcustom org-export-odt-create-custom-styles-for-srcblocks t
1063 "Whether custom styles for colorized source blocks be automatically created.
1064 When this option is turned on, the exporter creates custom styles
1065 for source blocks based on the advice of `htmlfontify'. Creation
1066 of custom styles happen as part of `org-odt-hfy-face-to-css'.
1068 When this option is turned off exporter does not create such
1069 styles.
1071 Use the latter option if you do not want the custom styles to be
1072 based on your current display settings. It is necessary that the
1073 styles.xml already contains needed styles for colorizing to work.
1075 This variable is effective only if
1076 `org-export-odt-use-htmlfontify' is turned on."
1077 :group 'org-export-odt
1078 :type 'boolean)
1080 (defun org-odt-insert-custom-styles-for-srcblocks (styles)
1081 "Save STYLES used for colorizing of source blocks.
1082 Update styles.xml with styles that were collected as part of
1083 `org-odt-hfy-face-to-css' callbacks."
1084 (when styles
1085 (with-current-buffer
1086 (find-file-noselect (expand-file-name "styles.xml") t)
1087 (goto-char (point-min))
1088 (when (re-search-forward "</office:styles>" nil t)
1089 (goto-char (match-beginning 0))
1090 (insert "\n<!-- Org Htmlfontify Styles -->\n" styles "\n")))))
1092 (defun org-odt-format-source-code-or-example-colored
1093 (lines lang caption textareap cols rows num cont rpllbl fmt)
1094 "Format source or example blocks using `htmlfontify-string'.
1095 Use this routine when `org-export-odt-use-htmlfontify' option is
1096 turned on."
1097 (let* ((lang-m (and lang (or (cdr (assoc lang org-src-lang-modes)) lang)))
1098 (mode (and lang-m (intern (concat (if (symbolp lang-m)
1099 (symbol-name lang-m)
1100 lang-m) "-mode"))))
1101 (org-inhibit-startup t)
1102 (org-startup-folded nil)
1103 (lines (with-temp-buffer
1104 (insert lines)
1105 (if (functionp mode) (funcall mode) (fundamental-mode))
1106 (font-lock-fontify-buffer)
1107 (buffer-string)))
1108 (hfy-html-quote-regex "\\([<\"&> ]\\)")
1109 (hfy-html-quote-map '(("\"" "&quot;")
1110 ("<" "&lt;")
1111 ("&" "&amp;")
1112 (">" "&gt;")
1113 (" " "<text:s/>")
1114 (" " "<text:tab/>")))
1115 (hfy-face-to-css 'org-odt-hfy-face-to-css)
1116 (hfy-optimisations-1 (copy-seq hfy-optimisations))
1117 (hfy-optimisations (add-to-list 'hfy-optimisations-1
1118 'body-text-only))
1119 (hfy-begin-span-handler
1120 (lambda (style text-block text-id text-begins-block-p)
1121 (insert (format "<text:span text:style-name=\"%s\">" style))))
1122 (hfy-end-span-handler (lambda nil (insert "</text:span>"))))
1123 (when (fboundp 'htmlfontify-string)
1124 (let* ((lines (org-split-string lines "[\r\n]"))
1125 (line-count (length lines))
1126 (i 0))
1127 (mapconcat
1128 (lambda (line)
1129 (incf i)
1130 (org-odt-format-source-line-with-line-number-and-label
1131 line rpllbl num 'htmlfontify-string
1132 (if (= i line-count) "OrgSrcBlockLastLine" "OrgSrcBlock")))
1133 lines "\n")))))
1135 (defun org-odt-format-source-code-or-example (lines lang caption textareap
1136 cols rows num cont
1137 rpllbl fmt)
1138 "Format source or example blocks for export.
1139 Use `org-odt-format-source-code-or-example-plain' or
1140 `org-odt-format-source-code-or-example-colored' depending on the
1141 value of `org-export-odt-use-htmlfontify."
1142 (setq lines (org-export-number-lines
1143 lines 0 0 num cont rpllbl fmt ;; 'preprocess
1145 lines (funcall
1146 (or (and org-export-odt-use-htmlfontify
1147 (or (featurep 'htmlfontify)
1148 (require 'htmlfontify))
1149 (fboundp 'htmlfontify-string)
1150 'org-odt-format-source-code-or-example-colored)
1151 'org-odt-format-source-code-or-example-plain)
1152 lines lang caption textareap cols rows num cont rpllbl fmt))
1153 (if (not num) lines
1154 (let ((extra (format " text:continue-numbering=\"%s\""
1155 (if cont "true" "false"))))
1156 (org-odt-format-tags
1157 '("<text:list text:style-name=\"OrgSrcBlockNumberedLine\"%s>"
1158 . "</text:list>") lines extra))))
1160 (defun org-odt-remap-stylenames (style-name)
1162 (cdr (assoc style-name '(("timestamp-wrapper" . "OrgTimestampWrapper")
1163 ("timestamp" . "OrgTimestamp")
1164 ("timestamp-kwd" . "OrgTimestampKeyword")
1165 ("tag" . "OrgTag")
1166 ("todo" . "OrgTodo")
1167 ("done" . "OrgDone")
1168 ("target" . "OrgTarget"))))
1169 style-name))
1171 (defun org-odt-format-fontify (text style &optional id)
1172 (let* ((style-name
1173 (cond
1174 ((stringp style)
1175 (org-odt-remap-stylenames style))
1176 ((symbolp style)
1177 (org-odt-get-style-name-for-entity 'character style))
1178 ((listp style)
1179 (assert (< 1 (length style)))
1180 (let ((parent-style (pop style)))
1181 (mapconcat (lambda (s)
1182 ;; (assert (stringp s) t)
1183 (org-odt-remap-stylenames s)) style "")
1184 (org-odt-remap-stylenames parent-style)))
1185 (t (error "Don't how to handle style %s" style)))))
1186 (org-odt-format-tags
1187 '("<text:span text:style-name=\"%s\">" . "</text:span>")
1188 text style-name)))
1190 (defun org-odt-relocate-relative-path (path dir)
1191 (if (file-name-absolute-p path) path
1192 (file-relative-name (expand-file-name path dir)
1193 (expand-file-name "eyecandy" dir))))
1195 (defun org-odt-format-inline-image (thefile)
1196 (let* ((thelink (if (file-name-absolute-p thefile) thefile
1197 (org-xml-format-href
1198 (org-odt-relocate-relative-path
1199 thefile org-current-export-file))))
1200 (href
1201 (org-odt-format-tags
1202 "<draw:image xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>" ""
1203 (if org-export-odt-embed-images
1204 (org-odt-copy-image-file thefile) thelink))))
1205 (org-export-odt-format-image thefile href)))
1207 (defun org-export-odt-format-formula (src href &optional embed-as)
1208 "Create image tag with source and attributes."
1209 (save-match-data
1210 (let* ((caption (org-find-text-property-in-string 'org-caption src))
1211 (caption (and caption (org-xml-format-desc caption)))
1212 (label (org-find-text-property-in-string 'org-label src))
1213 (embed-as (or embed-as
1214 (and (org-find-text-property-in-string
1215 'org-latex-src src)
1216 (org-find-text-property-in-string
1217 'org-latex-src-embed-type src))
1218 'paragraph))
1219 width height)
1220 (cond
1221 ((eq embed-as 'character)
1222 (org-odt-format-entity "InlineFormula" href width height))
1224 (org-lparse-end-paragraph)
1225 (org-lparse-insert-list-table
1226 `((,(org-odt-format-entity
1227 (if caption "CaptionedDisplayFormula" "DisplayFormula")
1228 href width height caption nil)
1229 ,(if (not label) ""
1230 (org-odt-format-entity-caption label nil "Equation"))))
1231 nil nil nil "OrgEquation" nil '((1 "c" 8) (2 "c" 1)))
1232 (throw 'nextline nil))))))
1234 (defvar org-odt-embedded-formulas-count 0)
1235 (defun org-odt-copy-formula-file (path)
1236 "Returns the internal name of the file"
1237 (let* ((src-file (expand-file-name
1238 path (file-name-directory org-current-export-file)))
1239 (target-dir (format "Formula-%04d/"
1240 (incf org-odt-embedded-formulas-count)))
1241 (target-file (concat target-dir "content.xml")))
1242 (when (not org-lparse-to-buffer)
1243 (message "Embedding %s as %s ..."
1244 (substring-no-properties path) target-file)
1246 (make-directory target-dir)
1247 (org-odt-create-manifest-file-entry
1248 "application/vnd.oasis.opendocument.formula" target-dir "1.2")
1250 (copy-file src-file target-file 'overwrite)
1251 (org-odt-create-manifest-file-entry "text/xml" target-file))
1252 target-file))
1254 (defun org-odt-format-inline-formula (thefile)
1255 (let* ((thelink (if (file-name-absolute-p thefile) thefile
1256 (org-xml-format-href
1257 (org-odt-relocate-relative-path
1258 thefile org-current-export-file))))
1259 (href
1260 (org-odt-format-tags
1261 "<draw:object xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>" ""
1262 (file-name-directory (org-odt-copy-formula-file thefile)))))
1263 (org-export-odt-format-formula thefile href)))
1265 (defun org-odt-is-formula-link-p (file)
1266 (member (downcase (file-name-extension file)) '("mathml")))
1268 (defun org-odt-format-org-link (opt-plist type-1 path fragment desc attr
1269 descp)
1270 "Make an HTML link.
1271 OPT-PLIST is an options list.
1272 TYPE is the device-type of the link (THIS://foo.html)
1273 PATH is the path of the link (http://THIS#locationx)
1274 FRAGMENT is the fragment part of the link, if any (foo.html#THIS)
1275 DESC is the link description, if any.
1276 ATTR is a string of other attributes of the a element.
1277 MAY-INLINE-P allows inlining it as an image."
1278 (declare (special org-lparse-par-open))
1279 (save-match-data
1280 (let* ((may-inline-p
1281 (and (member type-1 '("http" "https" "file"))
1282 (org-lparse-should-inline-p path descp)
1283 (not fragment)))
1284 (type (if (equal type-1 "id") "file" type-1))
1285 (filename path)
1286 (thefile path))
1287 (cond
1288 ;; check for inlined images
1289 ((and (member type '("file"))
1290 (not fragment)
1291 (org-file-image-p
1292 filename org-odt-export-inline-image-extensions)
1293 (or (eq t org-odt-export-inline-images)
1294 (and org-odt-export-inline-images (not descp))))
1295 (org-odt-format-inline-image thefile))
1296 ;; check for embedded formulas
1297 ((and (member type '("file"))
1298 (not fragment)
1299 (org-odt-is-formula-link-p filename)
1300 (or (not descp)))
1301 (org-odt-format-inline-formula thefile))
1302 ((string= type "coderef")
1303 (let* ((ref fragment)
1304 (lineno-or-ref (cdr (assoc ref org-export-code-refs)))
1305 (desc (and descp desc))
1306 (org-odt-suppress-xref nil)
1307 (href (org-xml-format-href (concat "#coderef-" ref))))
1308 (cond
1309 ((and (numberp lineno-or-ref) (not desc))
1310 (org-odt-format-link lineno-or-ref href))
1311 ((and (numberp lineno-or-ref) desc
1312 (string-match (regexp-quote (concat "(" ref ")")) desc))
1313 (format (replace-match "%s" t t desc)
1314 (org-odt-format-link lineno-or-ref href)))
1316 (setq desc (format
1317 (if (and desc (string-match
1318 (regexp-quote (concat "(" ref ")"))
1319 desc))
1320 (replace-match "%s" t t desc)
1321 (or desc "%s"))
1322 lineno-or-ref))
1323 (org-odt-format-link (org-xml-format-desc desc) href)))))
1325 (when (string= type "file")
1326 (setq thefile
1327 (cond
1328 ((file-name-absolute-p path)
1329 (concat "file://" (expand-file-name path)))
1330 (t (org-odt-relocate-relative-path
1331 thefile org-current-export-file)))))
1333 (when (and (member type '("" "http" "https" "file")) fragment)
1334 (setq thefile (concat thefile "#" fragment)))
1336 (setq thefile (org-xml-format-href thefile))
1338 (when (not (member type '("" "file")))
1339 (setq thefile (concat type ":" thefile)))
1341 (let ((org-odt-suppress-xref nil))
1342 (org-odt-format-link
1343 (org-xml-format-desc desc) thefile attr)))))))
1345 (defun org-odt-format-heading (text level &optional id)
1346 (let* ((text (if id (org-odt-format-target text id) text)))
1347 (org-odt-format-tags
1348 '("<text:h text:style-name=\"Heading_20_%s\" text:outline-level=\"%s\">" .
1349 "</text:h>") text level level)))
1351 (defun org-odt-format-headline (title extra-targets tags
1352 &optional snumber level)
1353 (concat
1354 (org-lparse-format 'EXTRA-TARGETS extra-targets)
1356 ;; No need to generate section numbers. They are auto-generated by
1357 ;; the application
1359 ;; (concat (org-lparse-format 'SECTION-NUMBER snumber level) " ")
1360 title
1361 (and tags (concat (org-lparse-format 'SPACES 3)
1362 (org-lparse-format 'ORG-TAGS tags)))))
1364 (defun org-odt-format-anchor (text name &optional class)
1365 (org-odt-format-target text name))
1367 (defun org-odt-format-bookmark (text id)
1368 (if id
1369 (org-odt-format-tags "<text:bookmark text:name=\"%s\"/>" text id)
1370 text))
1372 (defun org-odt-format-target (text id)
1373 (let ((name (concat org-export-odt-bookmark-prefix id)))
1374 (concat
1375 (and id (org-odt-format-tags
1376 "<text:bookmark-start text:name=\"%s\"/>" "" name))
1377 (org-odt-format-bookmark text id)
1378 (and id (org-odt-format-tags
1379 "<text:bookmark-end text:name=\"%s\"/>" "" name)))))
1381 (defun org-odt-format-footnote (n def)
1382 (let ((id (concat "fn" n))
1383 (note-class "footnote")
1384 (par-style "Footnote"))
1385 (org-odt-format-tags
1386 '("<text:note text:id=\"%s\" text:note-class=\"%s\">" .
1387 "</text:note>")
1388 (concat
1389 (org-odt-format-tags
1390 '("<text:note-citation>" . "</text:note-citation>")
1392 (org-odt-format-tags
1393 '("<text:note-body>" . "</text:note-body>")
1394 def))
1395 id note-class)))
1397 (defun org-odt-format-footnote-reference (n def refcnt)
1398 (if (= refcnt 1)
1399 (org-odt-format-footnote n def)
1400 (org-odt-format-footnote-ref n)))
1402 (defun org-odt-format-footnote-ref (n)
1403 (let ((note-class "footnote")
1404 (ref-format "text")
1405 (ref-name (concat "fn" n)))
1406 (org-odt-format-tags
1407 '("<text:span text:style-name=\"%s\">" . "</text:span>")
1408 (org-odt-format-tags
1409 '("<text:note-ref text:note-class=\"%s\" text:reference-format=\"%s\" text:ref-name=\"%s\">" . "</text:note-ref>")
1410 n note-class ref-format ref-name)
1411 "OrgSuperscript")))
1413 (defun org-odt-get-image-name (file-name)
1414 (require 'sha1)
1415 (file-relative-name
1416 (expand-file-name
1417 (concat (sha1 file-name) "." (file-name-extension file-name)) "Pictures")))
1419 (defun org-export-odt-format-image (src href &optional embed-as)
1420 "Create image tag with source and attributes."
1421 (save-match-data
1422 (let* ((caption (org-find-text-property-in-string 'org-caption src))
1423 (caption (and caption (org-xml-format-desc caption)))
1424 (attr (org-find-text-property-in-string 'org-attributes src))
1425 (label (org-find-text-property-in-string 'org-label src))
1426 (embed-as (or embed-as
1427 (if (org-find-text-property-in-string
1428 'org-latex-src src)
1429 (or (org-find-text-property-in-string
1430 'org-latex-src-embed-type src) 'character)
1431 'paragraph)))
1432 (attr-plist (when attr (read attr)))
1433 (size (org-odt-image-size-from-file
1434 src (plist-get attr-plist :width)
1435 (plist-get attr-plist :height)
1436 (plist-get attr-plist :scale) nil embed-as))
1437 (width (car size)) (height (cdr size)))
1438 (cond
1439 ((not (or caption label))
1440 (case embed-as
1441 (paragraph (org-odt-format-entity "DisplayImage" href width height))
1442 (character (org-odt-format-entity "InlineImage" href width height))
1443 (t (error "Unknown value for embed-as %S" embed-as))))
1445 (org-odt-format-entity
1446 "CaptionedDisplayImage" href width height caption label))))))
1448 (defun org-odt-format-frame (text width height style &optional
1449 extra anchor-type)
1450 (let ((frame-attrs
1451 (concat
1452 (if width (format " svg:width=\"%0.2fcm\"" width) "")
1453 (if height (format " svg:height=\"%0.2fcm\"" height) "")
1454 extra
1455 (format " text:anchor-type=\"%s\"" (or anchor-type "paragraph")))))
1456 (org-odt-format-tags
1457 '("<draw:frame draw:style-name=\"%s\"%s>" . "</draw:frame>")
1458 text style frame-attrs)))
1460 (defun org-odt-format-textbox (text width height style &optional
1461 extra anchor-type)
1462 (org-odt-format-frame
1463 (org-odt-format-tags
1464 '("<draw:text-box %s>" . "</draw:text-box>")
1465 text (concat (format " fo:min-height=\"%0.2fcm\"" (or height .2))
1466 (format " fo:min-width=\"%0.2fcm\"" (or width .2))))
1467 width nil style extra anchor-type))
1469 (defun org-odt-format-inlinetask (heading content
1470 &optional todo priority tags)
1471 (org-odt-format-stylized-paragraph
1472 nil (org-odt-format-textbox
1473 (concat (org-odt-format-stylized-paragraph
1474 "OrgInlineTaskHeading"
1475 (org-lparse-format
1476 'HEADLINE (concat (org-lparse-format-todo todo) " " heading)
1477 nil tags))
1478 content) nil nil "OrgInlineTaskFrame" " style:rel-width=\"100%\"")))
1480 (defvar org-odt-entity-frame-styles
1481 '(("InlineImage" "Figure" ("OrgInlineImage" nil "as-char"))
1482 ("DisplayImage" "Figure" ("OrgDisplayImage" nil "paragraph"))
1483 ("CaptionedDisplayImage" "Figure"
1484 ("OrgCaptionedImage"
1485 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
1486 ("OrgImageCaptionFrame"))
1487 ("InlineFormula" "Equation" ("OrgInlineFormula" nil "as-char"))
1488 ("DisplayFormula" "Equation" ("OrgDisplayFormula" nil "as-char"))
1489 ("CaptionedDisplayFormula" "Equation"
1490 ("OrgCaptionedFormula" nil "paragraph")
1491 ("OrgFormulaCaptionFrame" nil "as-char"))))
1493 (defun org-odt-format-entity (entity href width height &optional caption label)
1494 (let* ((entity-style (assoc entity org-odt-entity-frame-styles))
1495 (entity-frame (apply 'org-odt-format-frame
1496 href width height (nth 2 entity-style))))
1497 (if (not (or caption label)) entity-frame
1498 (apply 'org-odt-format-textbox
1499 (org-odt-format-stylized-paragraph
1500 'illustration
1501 (concat entity-frame (org-odt-format-entity-caption
1502 label caption (nth 1 entity-style))))
1503 width height (nth 3 entity-style)))))
1507 (defvar org-odt-embedded-images-count 0)
1508 (defun org-odt-copy-image-file (path)
1509 "Returns the internal name of the file"
1510 (let* ((image-type (file-name-extension path))
1511 (media-type (format "image/%s" image-type))
1512 (src-file (expand-file-name
1513 path (file-name-directory org-current-export-file)))
1514 (target-dir "Images/")
1515 (target-file
1516 (format "%s%04d.%s" target-dir
1517 (incf org-odt-embedded-images-count) image-type)))
1518 (when (not org-lparse-to-buffer)
1519 (message "Embedding %s as %s ..."
1520 (substring-no-properties path) target-file)
1522 (when (= 1 org-odt-embedded-images-count)
1523 (make-directory target-dir)
1524 (org-odt-create-manifest-file-entry "" target-dir))
1526 (copy-file src-file target-file 'overwrite)
1527 (org-odt-create-manifest-file-entry media-type target-file))
1528 target-file))
1530 (defvar org-export-odt-image-size-probe-method
1531 '(emacs imagemagick force)
1532 "Ordered list of methods by for determining size of an embedded
1533 image.")
1535 (defvar org-export-odt-default-image-sizes-alist
1536 '(("character" . (5 . 0.4))
1537 ("paragraph" . (5 . 5)))
1538 "Hardcoded image dimensions one for each of the anchor
1539 methods.")
1541 (defun org-odt-do-image-size (probe-method file &optional dpi anchor-type)
1542 (setq dpi (or dpi org-export-odt-pixels-per-inch))
1543 (setq anchor-type (or anchor-type "paragraph"))
1544 (flet ((size-in-cms (size-in-pixels)
1545 (flet ((pixels-to-cms (pixels)
1546 (let* ((cms-per-inch 2.54)
1547 (inches (/ pixels dpi)))
1548 (* cms-per-inch inches))))
1549 (and size-in-pixels
1550 (cons (pixels-to-cms (car size-in-pixels))
1551 (pixels-to-cms (cdr size-in-pixels)))))))
1552 (case probe-method
1553 (emacs
1554 (size-in-cms (ignore-errors (image-size (create-image file) 'pixels))))
1555 (imagemagick
1556 (size-in-cms
1557 (let ((dim (shell-command-to-string
1558 (format "identify -format \"%%w:%%h\" \"%s\"" file))))
1559 (when (string-match "\\([0-9]+\\):\\([0-9]+\\)" dim)
1560 (cons (string-to-number (match-string 1 dim))
1561 (string-to-number (match-string 2 dim)))))))
1563 (cdr (assoc-string anchor-type
1564 org-export-odt-default-image-sizes-alist))))))
1566 (defun org-odt-image-size-from-file (file &optional user-width
1567 user-height scale dpi embed-as)
1568 (unless (file-name-absolute-p file)
1569 (setq file (expand-file-name
1570 file (file-name-directory org-current-export-file))))
1571 (let* (size width height)
1572 (unless (and user-height user-width)
1573 (loop for probe-method in org-export-odt-image-size-probe-method
1574 until size
1575 do (setq size (org-odt-do-image-size
1576 probe-method file dpi embed-as)))
1577 (or size (error "Cannot determine Image size. Aborting ..."))
1578 (setq width (car size) height (cdr size)))
1579 (cond
1580 (scale
1581 (setq width (* width scale) height (* height scale)))
1582 ((and user-height user-width)
1583 (setq width user-width height user-height))
1584 (user-height
1585 (setq width (* user-height (/ width height)) height user-height))
1586 (user-width
1587 (setq height (* user-width (/ height width)) width user-width))
1588 (t (ignore)))
1589 (cons width height)))
1591 (defvar org-odt-entity-labels-alist nil
1592 "Associate Labels with the Labelled entities.
1593 Each element of the alist is of the form (LABEL-NAME
1594 CATEGORY-NAME SEQNO). LABEL-NAME is same as that specified by
1595 \"#+LABEL: ...\" line. CATEGORY-NAME is the type of the entity
1596 that LABEL-NAME is attached to. CATEGORY-NAME can be one of
1597 \"Table\", \"Figure\" or \"Equation\". SEQNO is the unique
1598 number assigned to the referenced entity on a per-CATEGORY basis.
1599 It is generated sequentially and is 1-based.
1601 Update this alist with `org-odt-add-label-definition' and
1602 retrieve an entry with `org-odt-get-label-definition'.")
1604 (defvar org-odt-entity-counts-plist nil
1605 "Plist of running counters of SEQNOs for each of the CATEGORY-NAMEs.
1606 See `org-odt-entity-labels-alist' for known CATEGORY-NAMEs.")
1608 (defvar org-odt-label-def-ref-spec
1609 '(("Equation" "(%n)" "text" "(%n)")
1610 ("" "%e %n%c" "category-and-value" "%e %n"))
1611 "Specify how labels are applied and referenced.
1612 This is an alist where each element is of the form (CATEGORY-NAME
1613 LABEL-APPLY-FMT LABEL-REF-MODE LABEL-REF-FMT). CATEGORY-NAME is
1614 as defined in `org-odt-entity-labels-alist'. It can additionally
1615 be an empty string in which case it is used as a catch-all
1616 specifier.
1618 LABEL-APPLY-FMT is used for applying labels and captions. It may
1619 contain following specifiers - %e, %n and %c. %e is replaced
1620 with the CATEGORY-NAME. %n is replaced with \"<text:sequence
1621 ...> SEQNO </text:sequence>\". %c is replaced with CAPTION. See
1622 `org-odt-format-label-definition'.
1624 LABEL-REF-MODE and LABEL-REF-FMT are used for generating the
1625 following label reference - \"<text:sequence-ref
1626 text:reference-format=\"LABEL-REF-MODE\" ...> LABEL-REF-FMT
1627 </text:sequence-ref>\". LABEL-REF-FMT may contain following
1628 specifiers - %e and %n. %e is replaced with the CATEGORY-NAME. %n is
1629 replaced with SEQNO. See `org-odt-format-label-reference'.")
1631 (defun org-odt-add-label-definition (label category)
1632 "Return (SEQNO . LABEL-APPLY-FMT).
1633 See `org-odt-label-def-ref-spec'."
1634 (setq label (substring-no-properties label))
1635 (let (seqno label-props fmt (category-sym (intern category)))
1636 (setq seqno (1+ (plist-get org-odt-entity-counts-plist category-sym))
1637 org-odt-entity-counts-plist (plist-put org-odt-entity-counts-plist
1638 category-sym seqno)
1639 fmt (cadr (or (assoc-string category org-odt-label-def-ref-spec t)
1640 (assoc-string "" org-odt-label-def-ref-spec t)))
1641 label-props (list label category seqno))
1642 (push label-props org-odt-entity-labels-alist)
1643 (cons seqno fmt)))
1645 (defun org-odt-get-label-definition (label)
1646 "Return (LABEL-NAME CATEGORY-NAME SEQNO LABEL-REF-MODE LABEL-REF-FMT).
1647 See `org-odt-entity-labels-alist' and
1648 `org-odt-label-def-ref-spec'."
1649 (let* ((label-props (assoc label org-odt-entity-labels-alist))
1650 (category (nth 1 label-props)))
1651 (append label-props
1652 (cddr (or (assoc-string category org-odt-label-def-ref-spec t)
1653 (assoc-string "" org-odt-label-def-ref-spec t))))))
1655 (defun org-odt-format-label-definition (label category caption)
1656 (assert label)
1657 (let* ((label-props (org-odt-add-label-definition label category))
1658 (seqno (car label-props))
1659 (fmt (cdr label-props)))
1660 (or (format-spec
1662 `((?e . ,category)
1663 (?n . ,(org-odt-format-tags
1664 '("<text:sequence text:ref-name=\"%s\" text:name=\"%s\" text:formula=\"ooow:%s+1\" style:num-format=\"1\">" . "</text:sequence>")
1665 (format "%d" seqno) label category category))
1666 (?c . ,(or (and caption (concat ": " caption)) ""))))
1667 caption "")))
1669 (defun org-odt-format-label-reference (label category seqno fmt1 fmt2)
1670 (assert label)
1671 (save-match-data
1672 (org-odt-format-tags
1673 '("<text:sequence-ref text:reference-format=\"%s\" text:ref-name=\"%s\">"
1674 . "</text:sequence-ref>")
1675 (format-spec fmt2 `((?e . ,category)
1676 (?n . ,(format "%d" seqno)))) fmt1 label)))
1678 (defun org-odt-fixup-label-references ()
1679 (goto-char (point-min))
1680 (while (re-search-forward
1681 "<text:sequence-ref text:ref-name=\"\\([^\"]+\\)\"/>" nil t)
1682 (let* ((label (match-string 1)))
1683 (replace-match
1684 (apply 'org-odt-format-label-reference
1685 (org-odt-get-label-definition label)) t t))))
1687 (defun org-odt-format-entity-caption (label caption category)
1688 (or (and label (org-odt-format-label-definition label category caption))
1689 caption ""))
1691 (defun org-odt-format-tags (tag text &rest args)
1692 (let ((prefix (when org-lparse-encode-pending "@"))
1693 (suffix (when org-lparse-encode-pending "@")))
1694 (apply 'org-lparse-format-tags tag text prefix suffix args)))
1696 (defun org-odt-init-outfile (filename)
1697 (unless (executable-find "zip")
1698 ;; Not at all OSes ship with zip by default
1699 (error "Executable \"zip\" needed for creating OpenDocument files"))
1701 (let* ((outdir (make-temp-file org-export-odt-tmpdir-prefix t))
1702 (content-file (expand-file-name "content.xml" outdir)))
1704 ;; init conten.xml
1705 (with-current-buffer (find-file-noselect content-file t))
1707 ;; reset variables
1708 (setq org-odt-manifest-file-entries nil
1709 org-odt-embedded-images-count 0
1710 org-odt-embedded-formulas-count 0
1711 org-odt-entity-labels-alist nil
1712 org-odt-entity-counts-plist (list 'Table 0 'Equation 0 'Figure 0))
1713 content-file))
1715 (defcustom org-export-odt-prettify-xml nil
1716 "Specify whether or not the xml output should be prettified.
1717 When this option is turned on, `indent-region' is run on all
1718 component xml buffers before they are saved. Turn this off for
1719 regular use. Turn this on if you need to examine the xml
1720 visually."
1721 :group 'org-export-odt
1722 :type 'boolean)
1724 (defvar hfy-user-sheet-assoc) ; bound during org-do-lparse
1725 (defun org-odt-save-as-outfile (target opt-plist)
1726 ;; create mimetype file
1727 (write-region "application/vnd.oasis.opendocument.text" nil
1728 (expand-file-name "mimetype"))
1730 ;; write meta file
1731 (org-odt-update-meta-file opt-plist)
1733 ;; write styles file
1734 (org-odt-copy-styles-file)
1736 ;; Update styles.xml - take care of outline numbering
1737 (with-current-buffer
1738 (find-file-noselect (expand-file-name "styles.xml") t)
1739 ;; Don't make automatic backup of styles.xml file. This setting
1740 ;; prevents the backedup styles.xml file from being zipped in to
1741 ;; odt file. This is more of a hackish fix. Better alternative
1742 ;; would be to fix the zip command so that the output odt file
1743 ;; includes only the needed files and excludes any auto-generated
1744 ;; extra files like backups and auto-saves etc etc. Note that
1745 ;; currently the zip command zips up the entire temp directory so
1746 ;; that any auto-generated files created under the hood ends up in
1747 ;; the resulting odt file.
1748 (set (make-local-variable 'backup-inhibited) t)
1750 ;; Import local setting of `org-export-with-section-numbers'
1751 (org-lparse-bind-local-variables opt-plist)
1752 (org-odt-configure-outline-numbering
1753 (if org-export-with-section-numbers org-export-headline-levels 0)))
1755 ;; Write custom stlyes for source blocks
1756 (org-odt-insert-custom-styles-for-srcblocks
1757 (mapconcat
1758 (lambda (style)
1759 (format " %s\n" (cddr style)))
1760 hfy-user-sheet-assoc ""))
1762 ;; create a manifest entry for content.xml
1763 (org-odt-create-manifest-file-entry
1764 "application/vnd.oasis.opendocument.text" "/" "1.2")
1766 (org-odt-create-manifest-file-entry "text/xml" "content.xml")
1768 ;; write out the manifest entries before zipping
1769 (org-odt-write-manifest-file)
1771 (let ((xml-files '("mimetype" "META-INF/manifest.xml" "content.xml"
1772 "meta.xml" "styles.xml"))
1773 (zipdir default-directory))
1774 (message "Switching to directory %s" (expand-file-name zipdir))
1776 ;; save all xml files
1777 (mapc (lambda (file)
1778 (with-current-buffer
1779 (find-file-noselect (expand-file-name file) t)
1780 ;; prettify output if needed
1781 (when org-export-odt-prettify-xml
1782 (indent-region (point-min) (point-max)))
1783 (save-buffer 0)))
1784 xml-files)
1786 (let* ((target-name (file-name-nondirectory target))
1787 (target-dir (file-name-directory target))
1788 (cmds `(("zip" "-mX0" ,target-name "mimetype")
1789 ("zip" "-rmTq" ,target-name "."))))
1790 (when (file-exists-p target)
1791 ;; FIXME: If the file is locked this throws a cryptic error
1792 (delete-file target))
1794 (let ((coding-system-for-write 'no-conversion) exitcode err-string)
1795 (message "Creating odt file...")
1796 (mapc
1797 (lambda (cmd)
1798 (message "Running %s" (mapconcat 'identity cmd " "))
1799 (setq err-string
1800 (with-output-to-string
1801 (setq exitcode
1802 (apply 'call-process (car cmd)
1803 nil standard-output nil (cdr cmd)))))
1804 (or (zerop exitcode)
1805 (ignore (message "%s" err-string))
1806 (error "Unable to create odt file (%S)" exitcode)))
1807 cmds))
1809 ;; move the file from outdir to target-dir
1810 (rename-file target-name target-dir)
1812 ;; kill all xml buffers
1813 (mapc (lambda (file)
1814 (kill-buffer
1815 (find-file-noselect (expand-file-name file zipdir) t)))
1816 xml-files)
1818 (delete-directory zipdir)))
1820 (message "Created %s" target)
1821 (set-buffer (find-file-noselect target t)))
1823 (defun org-odt-format-date (date)
1824 (let ((warning-msg
1825 "OpenDocument files require that dates be in ISO-8601 format. Please review your DATE options for compatibility."))
1826 ;; If the user is not careful with the date specification, an
1827 ;; invalid meta.xml will be emitted.
1829 ;; For now honor user's diktat and let him off with a warning
1830 ;; message. This is OK as LibreOffice (and possibly other
1831 ;; apps) doesn't deem this deviation as critical and continue
1832 ;; to load the file.
1834 ;; FIXME: Surely there a better way to handle this. Revisit this
1835 ;; later.
1836 (cond
1837 ((and date (string-match "%" date))
1838 ;; Honor user's diktat. See comments above
1839 (org-lparse-warn warning-msg)
1840 (format-time-string date))
1841 (date
1842 ;; Honor user's diktat. See comments above
1843 (org-lparse-warn warning-msg)
1844 date)
1846 ;; ISO 8601 format
1847 (let ((stamp (format-time-string "%Y-%m-%dT%H:%M:%S%z")))
1848 (format "%s:%s" (substring stamp 0 -2) (substring stamp -2)))))))
1850 (defconst org-odt-manifest-file-entry-tag
1852 <manifest:file-entry manifest:media-type=\"%s\" manifest:full-path=\"%s\"%s/>")
1854 (defvar org-odt-manifest-file-entries nil)
1856 (defun org-odt-create-manifest-file-entry (&rest args)
1857 (push args org-odt-manifest-file-entries))
1859 (defun org-odt-write-manifest-file ()
1860 (make-directory "META-INF")
1861 (let ((manifest-file (expand-file-name "META-INF/manifest.xml")))
1862 (write-region
1863 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
1864 <manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"1.2\">\n"
1865 nil manifest-file)
1866 (mapc
1867 (lambda (file-entry)
1868 (let* ((version (nth 2 file-entry))
1869 (extra (if version
1870 (format " manifest:version=\"%s\"" version)
1871 "")))
1872 (write-region
1873 (format org-odt-manifest-file-entry-tag
1874 (nth 0 file-entry) (nth 1 file-entry) extra)
1875 nil manifest-file t))) org-odt-manifest-file-entries)
1876 (write-region "\n</manifest:manifest>" nil manifest-file t)))
1878 (defun org-odt-update-meta-file (opt-plist)
1879 (let ((date (org-odt-format-date (plist-get opt-plist :date)))
1880 (author (or (plist-get opt-plist :author) ""))
1881 (email (plist-get opt-plist :email))
1882 (keywords (plist-get opt-plist :keywords))
1883 (description (plist-get opt-plist :description))
1884 (title (plist-get opt-plist :title)))
1886 (write-region
1887 (concat
1888 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
1889 <office:document-meta
1890 xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"
1891 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
1892 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
1893 xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"
1894 xmlns:ooo=\"http://openoffice.org/2004/office\"
1895 office:version=\"1.2\">
1896 <office:meta>" "\n"
1897 (org-odt-format-tags '("<dc:creator>" . "</dc:creator>") author)
1898 (org-odt-format-tags
1899 '("\n<meta:initial-creator>" . "</meta:initial-creator>") author)
1900 (org-odt-format-tags '("\n<dc:date>" . "</dc:date>") date)
1901 (org-odt-format-tags
1902 '("\n<meta:creation-date>" . "</meta:creation-date>") date)
1903 (org-odt-format-tags '("\n<meta:generator>" . "</meta:generator>")
1904 (when org-export-creator-info
1905 (format "Org-%s/Emacs-%s"
1906 org-version emacs-version)))
1907 (org-odt-format-tags '("\n<meta:keyword>" . "</meta:keyword>") keywords)
1908 (org-odt-format-tags '("\n<dc:subject>" . "</dc:subject>") description)
1909 (org-odt-format-tags '("\n<dc:title>" . "</dc:title>") title)
1910 "\n"
1911 " </office:meta>" "</office:document-meta>")
1912 nil (expand-file-name "meta.xml")))
1914 ;; create a manifest entry for meta.xml
1915 (org-odt-create-manifest-file-entry "text/xml" "meta.xml"))
1917 (defun org-odt-finalize-outfile ()
1918 (org-odt-delete-empty-paragraphs))
1920 (defun org-odt-delete-empty-paragraphs ()
1921 (goto-char (point-min))
1922 (let ((open "<text:p[^>]*>")
1923 (close "</text:p>"))
1924 (while (re-search-forward (format "%s[ \r\n\t]*%s" open close) nil t)
1925 (replace-match ""))))
1927 (defun org-odt-get (what &optional opt-plist)
1928 (case what
1929 (BACKEND 'odt)
1930 (EXPORT-DIR (org-export-directory :html opt-plist))
1931 (FILE-NAME-EXTENSION "odt")
1932 (EXPORT-BUFFER-NAME "*Org ODT Export*")
1933 (ENTITY-CONTROL org-odt-entity-control-callbacks-alist)
1934 (ENTITY-FORMAT org-odt-entity-format-callbacks-alist)
1935 (INIT-METHOD 'org-odt-init-outfile)
1936 (FINAL-METHOD 'org-odt-finalize-outfile)
1937 (SAVE-METHOD 'org-odt-save-as-outfile)
1938 ;; (OTHER-BACKENDS) ; see note in `org-xhtml-get'
1939 ;; (CONVERT-METHOD) ; see note in `org-xhtml-get'
1940 (TOPLEVEL-HLEVEL 1)
1941 (SPECIAL-STRING-REGEXPS org-export-odt-special-string-regexps)
1942 (INLINE-IMAGES 'maybe)
1943 (INLINE-IMAGE-EXTENSIONS '("png" "jpeg" "jpg" "gif" "svg"))
1944 (PLAIN-TEXT-MAP '(("&" . "&amp;") ("<" . "&lt;") (">" . "&gt;")))
1945 (TABLE-FIRST-COLUMN-AS-LABELS nil)
1946 (FOOTNOTE-SEPARATOR (org-lparse-format 'FONTIFY "," 'superscript))
1947 (CODING-SYSTEM-FOR-WRITE 'utf-8)
1948 (CODING-SYSTEM-FOR-SAVE 'utf-8)
1949 (t (error "Unknown property: %s" what))))
1951 (defvar org-lparse-latex-fragment-fallback) ; set by org-do-lparse
1952 (defvar org-lparse-opt-plist) ; bound during org-do-lparse
1953 (defun org-export-odt-do-preprocess-latex-fragments ()
1954 "Convert LaTeX fragments to images."
1955 (let* ((latex-frag-opt (plist-get org-lparse-opt-plist :LaTeX-fragments))
1956 (latex-frag-opt ; massage the options
1957 (or (and (member latex-frag-opt '(mathjax t))
1958 (not (and (fboundp 'org-format-latex-mathml-available-p)
1959 (org-format-latex-mathml-available-p)))
1960 (prog1 org-lparse-latex-fragment-fallback
1961 (org-lparse-warn
1962 (concat
1963 "LaTeX to MathML converter not available. "
1964 (format "Using %S instead."
1965 org-lparse-latex-fragment-fallback)))))
1966 latex-frag-opt))
1967 cache-dir display-msg)
1968 (cond
1969 ((eq latex-frag-opt 'dvipng)
1970 (setq cache-dir "ltxpng/")
1971 (setq display-msg "Creating LaTeX image %s"))
1972 ((member latex-frag-opt '(mathjax t))
1973 (setq latex-frag-opt 'mathml)
1974 (setq cache-dir "ltxmathml/")
1975 (setq display-msg "Creating MathML formula %s")))
1976 (when (and org-current-export-file)
1977 (org-format-latex
1978 (concat cache-dir (file-name-sans-extension
1979 (file-name-nondirectory org-current-export-file)))
1980 org-current-export-dir nil display-msg
1981 nil nil latex-frag-opt))))
1983 (defun org-export-odt-preprocess-latex-fragments ()
1984 (when (equal org-export-current-backend 'odt)
1985 (org-export-odt-do-preprocess-latex-fragments)))
1987 (defun org-export-odt-preprocess-label-references ()
1988 (goto-char (point-min))
1989 (let (label label-components category value pretty-label)
1990 (while (re-search-forward "\\\\ref{\\([^{}\n]+\\)}" nil t)
1991 (org-if-unprotected-at (match-beginning 1)
1992 (replace-match
1993 (let ((org-lparse-encode-pending t)
1994 (label (match-string 1)))
1995 ;; markup generated below is mostly an eye-candy. At
1996 ;; pre-processing stage, there is no information on which
1997 ;; entity a label reference points to. The actual markup
1998 ;; is generated as part of `org-odt-fixup-label-references'
1999 ;; which gets called at the fag end of export. By this
2000 ;; time we would have seen and collected all the label
2001 ;; definitions in `org-odt-entity-labels-alist'.
2002 (org-odt-format-tags
2003 "<text:sequence-ref text:ref-name=\"%s\"/>" "" label)) t t)))))
2005 ;; process latex fragments as part of
2006 ;; `org-export-preprocess-after-blockquote-hook'. Note that this hook
2007 ;; is the one that is closest and well before the call to
2008 ;; `org-export-attach-captions-and-attributes' in
2009 ;; `org-export-preprocess-stirng'. The above arrangement permits
2010 ;; captions, labels and attributes to be attached to png images
2011 ;; generated out of latex equations.
2012 (add-hook 'org-export-preprocess-after-blockquote-hook
2013 'org-export-odt-preprocess-latex-fragments)
2015 (defun org-export-odt-preprocess (parameters)
2016 (org-export-odt-preprocess-label-references))
2018 (declare-function archive-zip-extract "arc-mode.el" (archive name))
2019 (defun org-odt-zip-extract-one (archive member &optional target)
2020 (require 'arc-mode)
2021 (let* ((target (or target default-directory))
2022 (archive (expand-file-name archive))
2023 (archive-zip-extract
2024 (list "unzip" "-qq" "-o" "-d" target))
2025 exit-code command-output)
2026 (setq command-output
2027 (with-temp-buffer
2028 (setq exit-code (archive-zip-extract archive member))
2029 (buffer-string)))
2030 (unless (zerop exit-code)
2031 (message command-output)
2032 (error "Extraction failed"))))
2034 (defun org-odt-zip-extract (archive members &optional target)
2035 (when (atom members) (setq members (list members)))
2036 (mapc (lambda (member)
2037 (org-odt-zip-extract-one archive member target))
2038 members))
2040 (defun org-odt-copy-styles-file (&optional styles-file)
2041 ;; Non-availability of styles.xml is not a critical error. For now
2042 ;; throw an error purely for aesthetic reasons.
2043 (setq styles-file (or styles-file
2044 org-export-odt-styles-file
2045 (expand-file-name "styles/OrgOdtStyles.xml"
2046 org-odt-data-dir)
2047 (error "org-odt: Missing styles file?")))
2048 (cond
2049 ((listp styles-file)
2050 (let ((archive (nth 0 styles-file))
2051 (members (nth 1 styles-file)))
2052 (org-odt-zip-extract archive members)
2053 (mapc
2054 (lambda (member)
2055 (when (org-file-image-p member)
2056 (let* ((image-type (file-name-extension member))
2057 (media-type (format "image/%s" image-type)))
2058 (org-odt-create-manifest-file-entry media-type member))))
2059 members)))
2060 ((and (stringp styles-file) (file-exists-p styles-file))
2061 (let ((styles-file-type (file-name-extension styles-file)))
2062 (cond
2063 ((string= styles-file-type "xml")
2064 (copy-file styles-file "styles.xml" t))
2065 ((member styles-file-type '("odt" "ott"))
2066 (org-odt-zip-extract styles-file "styles.xml")))))
2068 (error (format "Invalid specification of styles.xml file: %S"
2069 org-export-odt-styles-file))))
2071 ;; create a manifest entry for styles.xml
2072 (org-odt-create-manifest-file-entry "text/xml" "styles.xml"))
2074 (defvar org-export-odt-factory-settings
2075 "d4328fb9d1b6cb211d4320ff546829f26700dc5e"
2076 "SHA1 hash of OrgOdtStyles.xml.")
2078 (defun org-odt-configure-outline-numbering (level)
2079 "Outline numbering is retained only upto LEVEL.
2080 To disable outline numbering pass a LEVEL of 0."
2081 (goto-char (point-min))
2082 (let ((regex
2083 "<text:outline-level-style\\(.*\\)text:level=\"\\([^\"]*\\)\"\\(.*\\)>")
2084 (replacement
2085 "<text:outline-level-style\\1text:level=\"\\2\" style:num-format=\"\">"))
2086 (while (re-search-forward regex nil t)
2087 (when (> (string-to-number (match-string 2)) level)
2088 (replace-match replacement t nil))))
2089 (save-buffer 0))
2091 (provide 'org-odt)
2093 ;;; org-odt.el ends here