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