org-e-icalendar: Fix events duration when ending time is specified
[org-mode.git] / contrib / lisp / org-e-icalendar.el
blob2b38e0b8e29298d46b7c8327bc96b6e0446dd39e
1 ;;; org-e-icalendar.el --- iCalendar Back-End for Org Export Engine
3 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Nicolas Goaziou <n dot goaziou at gmail dot com>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
10 ;; This program is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; This program is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; This library implements an iCalendar back-end for Org generic
26 ;; exporter.
28 ;; It provides three commands for export, depending on the chosen
29 ;; source and desired output: `org-e-icalendar-export-to-ics' (current
30 ;; file), `org-e-icalendar-export-agenda-files' (agenda files into
31 ;; separate calendars) and `org-e-icalendar-combined-agenda-file'
32 ;; (agenda files into one combined calendar).
34 ;; It also provides the `org-e-icalendar-export-current-agenda'
35 ;; function, which will create a calendar file from current agenda
36 ;; view. It is meant to be called through `org-agenda-write'.
38 ;; This back-end introduces a new keyword, ICALENDAR_EXCLUDE_TAGS,
39 ;; which allows to specify a different set of exclude tags from other
40 ;; back-ends.
42 ;; It should follow RFC 5545 specifications.
44 ;;; Code:
46 (require 'org-e-ascii)
47 (declare-function org-bbdb-anniv-export-ical "org-bbdb" nil)
51 ;;; User-Configurable Variables
53 (defgroup org-export-e-icalendar nil
54 "Options specific for iCalendar export back-end."
55 :tag "Org iCalendar"
56 :group 'org-export)
58 (defcustom org-e-icalendar-combined-agenda-file "~/org.ics"
59 "The file name for the iCalendar file covering all agenda files.
60 This file is created with the command \\[org-e-icalendar-combine-agenda-files].
61 The file name should be absolute. It will be overwritten without warning."
62 :group 'org-export-e-icalendar
63 :type 'file)
65 (defcustom org-e-icalendar-alarm-time 0
66 "Number of minutes for triggering an alarm for exported timed events.
68 A zero value (the default) turns off the definition of an alarm trigger
69 for timed events. If non-zero, alarms are created.
71 - a single alarm per entry is defined
72 - The alarm will go off N minutes before the event
73 - only a DISPLAY action is defined."
74 :group 'org-export-e-icalendar
75 :version "24.1"
76 :type 'integer)
78 (defcustom org-e-icalendar-combined-name "OrgMode"
79 "Calendar name for the combined iCalendar representing all agenda files."
80 :group 'org-export-e-icalendar
81 :type 'string)
83 (defcustom org-e-icalendar-combined-description ""
84 "Calendar description for the combined iCalendar (all agenda files)."
85 :group 'org-export-e-icalendar
86 :type 'string)
88 (defcustom org-e-icalendar-exclude-tags nil
89 "Tags that exclude a tree from export.
90 This variable allows to specify different exclude tags from other
91 back-ends. It can also be set with the ICAL_EXCLUDE_TAGS
92 keyword."
93 :group 'org-export-e-icalendar
94 :type '(repeat (string :tag "Tag")))
96 (defcustom org-e-icalendar-use-deadline '(event-if-not-todo todo-due)
97 "Contexts where iCalendar export should use a deadline time stamp.
99 This is a list with several symbols in it. Valid symbol are:
100 `event-if-todo' Deadlines in TODO entries become calendar events.
101 `event-if-not-todo' Deadlines in non-TODO entries become calendar events.
102 `todo-due' Use deadlines in TODO entries as due-dates"
103 :group 'org-export-e-icalendar
104 :type '(set :greedy t
105 (const :tag "Deadlines in non-TODO entries become events"
106 event-if-not-todo)
107 (const :tag "Deadline in TODO entries become events"
108 event-if-todo)
109 (const :tag "Deadlines in TODO entries become due-dates"
110 todo-due)))
112 (defcustom org-e-icalendar-use-scheduled '(todo-start)
113 "Contexts where iCalendar export should use a scheduling time stamp.
115 This is a list with several symbols in it. Valid symbol are:
116 `event-if-todo' Scheduling time stamps in TODO entries become an event.
117 `event-if-not-todo' Scheduling time stamps in non-TODO entries become an event.
118 `todo-start' Scheduling time stamps in TODO entries become start date.
119 Some calendar applications show TODO entries only after
120 that date."
121 :group 'org-export-e-icalendar
122 :type '(set :greedy t
123 (const :tag
124 "SCHEDULED timestamps in non-TODO entries become events"
125 event-if-not-todo)
126 (const :tag "SCHEDULED timestamps in TODO entries become events"
127 event-if-todo)
128 (const :tag "SCHEDULED in TODO entries become start date"
129 todo-start)))
131 (defcustom org-e-icalendar-categories '(local-tags category)
132 "Items that should be entered into the \"categories\" field.
134 This is a list of symbols, the following are valid:
135 `category' The Org mode category of the current file or tree
136 `todo-state' The todo state, if any
137 `local-tags' The tags, defined in the current line
138 `all-tags' All tags, including inherited ones."
139 :group 'org-export-e-icalendar
140 :type '(repeat
141 (choice
142 (const :tag "The file or tree category" category)
143 (const :tag "The TODO state" todo-state)
144 (const :tag "Tags defined in current line" local-tags)
145 (const :tag "All tags, including inherited ones" all-tags))))
147 (defcustom org-e-icalendar-with-timestamps 'active
148 "Non-nil means make an event from plain time stamps.
150 It can be set to `active', `inactive', t or nil, in order to make
151 an event from, respectively, only active timestamps, only
152 inactive ones, all of them or none.
154 This variable has precedence over `org-export-with-timestamps'.
155 It can also be set with the #+OPTIONS line, e.g. \"<:t\"."
156 :group 'org-export-e-icalendar
157 :type '(choice
158 (const :tag "All timestamps" t)
159 (const :tag "Only active timestamps" active)
160 (const :tag "Only inactive timestamps" inactive)
161 (const :tag "No timestamp" nil)))
163 (defcustom org-e-icalendar-include-todo nil
164 "Non-nil means create VTODO components from TODO items.
166 Valid values are:
167 nil don't include any task.
168 t include tasks that are not in DONE state.
169 `unblocked' include all TODO items that are not blocked.
170 `all' include both done and not done items."
171 :group 'org-export-e-icalendar
172 :type '(choice
173 (const :tag "None" nil)
174 (const :tag "Unfinished" t)
175 (const :tag "Unblocked" unblocked)
176 (const :tag "All" all)
177 (repeat :tag "Specific TODO keywords"
178 (string :tag "Keyword"))))
180 (defcustom org-e-icalendar-include-bbdb-anniversaries nil
181 "Non-nil means a combined iCalendar file should include anniversaries.
182 The anniversaries are defined in the BBDB database."
183 :group 'org-export-e-icalendar
184 :type 'boolean)
186 (defcustom org-e-icalendar-include-sexps t
187 "Non-nil means export to iCalendar files should also cover sexp entries.
188 These are entries like in the diary, but directly in an Org mode
189 file."
190 :group 'org-export-e-icalendar
191 :type 'boolean)
193 (defcustom org-e-icalendar-include-body t
194 "Amount of text below headline to be included in iCalendar export.
195 This is a number of characters that should maximally be included.
196 Properties, scheduling and clocking lines will always be removed.
197 The text will be inserted into the DESCRIPTION field."
198 :group 'org-export-e-icalendar
199 :type '(choice
200 (const :tag "Nothing" nil)
201 (const :tag "Everything" t)
202 (integer :tag "Max characters")))
204 (defcustom org-e-icalendar-store-UID nil
205 "Non-nil means store any created UIDs in properties.
207 The iCalendar standard requires that all entries have a unique identifier.
208 Org will create these identifiers as needed. When this variable is non-nil,
209 the created UIDs will be stored in the ID property of the entry. Then the
210 next time this entry is exported, it will be exported with the same UID,
211 superseding the previous form of it. This is essential for
212 synchronization services.
214 This variable is not turned on by default because we want to avoid creating
215 a property drawer in every entry if people are only playing with this feature,
216 or if they are only using it locally."
217 :group 'org-export-e-icalendar
218 :type 'boolean)
220 (defcustom org-e-icalendar-timezone (getenv "TZ")
221 "The time zone string for iCalendar export.
222 When nil or the empty string, use output
223 from (current-time-zone)."
224 :group 'org-export-e-icalendar
225 :type '(choice
226 (const :tag "Unspecified" nil)
227 (string :tag "Time zone")))
229 (defcustom org-e-icalendar-date-time-format ":%Y%m%dT%H%M%S"
230 "Format-string for exporting icalendar DATE-TIME.
232 See `format-time-string' for a full documentation. The only
233 difference is that `org-e-icalendar-timezone' is used for %Z.
235 Interesting value are:
236 - \":%Y%m%dT%H%M%S\" for local time
237 - \";TZID=%Z:%Y%m%dT%H%M%S\" for local time with explicit timezone
238 - \":%Y%m%dT%H%M%SZ\" for time expressed in Universal Time"
239 :group 'org-export-e-icalendar
240 :version "24.1"
241 :type '(choice
242 (const :tag "Local time" ":%Y%m%dT%H%M%S")
243 (const :tag "Explicit local time" ";TZID=%Z:%Y%m%dT%H%M%S")
244 (const :tag "Universal time" ":%Y%m%dT%H%M%SZ")
245 (string :tag "Explicit format")))
247 (defvar org-e-icalendar-after-save-hook nil
248 "Hook run after an iCalendar file has been saved.
249 This hook is run with the name of the file as argument. A good
250 way to use this is to tell a desktop calendar application to
251 re-read the iCalendar file.")
255 ;;; Define Back-End
257 (org-export-define-derived-backend e-icalendar e-ascii
258 :translate-alist ((clock . ignore)
259 (headline . org-e-icalendar-entry)
260 (inlinetask . ignore)
261 (planning . ignore)
262 (section . ignore)
263 (template . org-e-icalendar-template))
264 :options-alist
265 ((:exclude-tags
266 "ICALENDAR_EXCLUDE_TAGS" nil org-e-icalendar-exclude-tags split)
267 (:with-timestamps nil "<" org-e-icalendar-with-timestamps)
268 (:with-vtodo nil nil org-e-icalendar-include-todo)
269 ;; The following property will be non-nil when export has been
270 ;; started from org-agenda-mode. In this case, any entry without
271 ;; a non-nil "ICALENDAR_MARK" property will be ignored.
272 (:icalendar-agenda-view nil nil nil))
273 :filters-alist
274 ((:filter-headline . org-e-icalendar-clear-blank-lines))
275 :menu-entry
276 (?c "Export to iCalendar"
277 ((?f "Current file"
278 (lambda (s v b) (org-e-icalendar-export-to-ics s v b)))
279 (?a "All agenda files"
280 (lambda (s v b) (org-e-icalendar-export-agenda-files)))
281 (?c "Combine all agenda files"
282 (lambda (s v b) (org-e-icalendar-combine-agenda-files))))))
286 ;;; Internal Functions
288 (defun org-e-icalendar-create-uid (file &optional bell)
289 "Set ID property on headlines missing it in FILE.
290 When optional argument BELL is non-nil, inform the user with
291 a message if the file was modified."
292 (let (modified-flag)
293 (org-map-entries
294 (lambda ()
295 (let ((entry (org-element-at-point)))
296 (unless (org-element-property :id entry)
297 (org-id-get-create)
298 (setq modified-flag t)
299 (forward-line))
300 (when (eq (org-element-type entry) 'inlinetask)
301 (setq org-map-continue-from (org-element-property :end entry)))))
302 nil nil 'comment)
303 (when (and bell modified-flag)
304 (message "ID properties created in file \"%s\"" file)
305 (sit-for 2))))
307 (defun org-e-icalendar-blocked-headline-p (headline info)
308 "Non-nil when HEADLINE is considered to be blocked.
310 INFO is a plist used as a communication channel.
312 An headline is blocked when either:
314 - It has children which are not all in a completed state.
316 - It has a parent with the property :ORDERED:, and there are
317 siblings prior to it with incomplete status.
319 - Its parent is blocked because it has siblings that should be
320 done first or is a child of a blocked grandparent entry."
322 ;; Check if any child is not done.
323 (org-element-map
324 headline 'headline
325 (lambda (hl) (eq (org-element-property :todo-type hl) 'todo))
326 info 'first-match)
327 ;; Check :ORDERED: node property.
328 (catch 'blockedp
329 (let ((current headline))
330 (mapc (lambda (parent)
331 (cond
332 ((not (org-element-property :todo-keyword parent))
333 (throw 'blockedp nil))
334 ((org-not-nil (org-element-property :ordered parent))
335 (let ((sibling current))
336 (while (setq sibling (org-export-get-previous-element
337 sibling info))
338 (when (eq (org-element-property :todo-type sibling) 'todo)
339 (throw 'blockedp t)))))
340 (t (setq current parent))))
341 (org-export-get-genealogy headline))
342 nil))))
344 (defun org-e-icalendar-use-UTC-date-time-p ()
345 "Non-nil when `org-e-icalendar-date-time-format' requires UTC time."
346 (char-equal (elt org-e-icalendar-date-time-format
347 (1- (length org-e-icalendar-date-time-format))) ?Z))
349 (defvar org-agenda-default-appointment-duration) ; From org-agenda.el.
350 (defun org-e-icalendar-convert-timestamp (timestamp keyword &optional end utc)
351 "Convert TIMESTAMP to iCalendar format.
353 TIMESTAMP is a timestamp object. KEYWORD is added in front of
354 it, in order to make a complete line (e.g. \"DTSTART\").
356 When optional argument END is non-nil, use end of time range.
357 Also increase the hour by two (if time string contains a time),
358 or the day by one (if it does not contain a time) when no
359 explicit ending time is specified.
361 When optional argument UTC is non-nil, time will be expressed in
362 Universal Time, ignoring `org-e-icalendar-date-time-format'.
363 This is mandatory for \"DTSTAMP\" property."
364 (let* ((year-start (org-element-property :year-start timestamp))
365 (year-end (org-element-property :year-end timestamp))
366 (month-start (org-element-property :month-start timestamp))
367 (month-end (org-element-property :month-end timestamp))
368 (day-start (org-element-property :day-start timestamp))
369 (day-end (org-element-property :day-end timestamp))
370 (hour-start (org-element-property :hour-start timestamp))
371 (hour-end (org-element-property :hour-end timestamp))
372 (minute-start (org-element-property :minute-start timestamp))
373 (minute-end (org-element-property :minute-end timestamp))
374 (with-time-p minute-start)
375 (equal-bounds-p
376 (equal (list year-start month-start day-start hour-start minute-start)
377 (list year-end month-end day-end hour-end minute-end)))
378 (mi (cond ((not with-time-p) 0)
379 ((not end) minute-start)
380 ((and org-agenda-default-appointment-duration equal-bounds-p)
381 (+ minute-end org-agenda-default-appointment-duration))
382 (t minute-end)))
383 (h (cond ((not with-time-p) 0)
384 ((not end) hour-start)
385 ((or (not equal-bounds-p)
386 org-agenda-default-appointment-duration)
387 hour-end)
388 (t (+ hour-end 2))))
389 (d (cond ((not end) day-start)
390 ((not with-time-p) (1+ day-end))
391 (t day-end)))
392 (m (if end month-end month-start))
393 (y (if end year-end year-start)))
394 (concat
395 keyword
396 (format-time-string
397 (cond (utc ":%Y%m%dT%H%M%SZ")
398 ((not with-time-p) ";VALUE=DATE:%Y%m%d")
399 (t (replace-regexp-in-string "%Z"
400 org-e-icalendar-timezone
401 org-e-icalendar-date-time-format)))
402 ;; Convert timestamp into internal time in order to use
403 ;; `format-time-string' and fix any mistake (i.e. MI >= 60).
404 (encode-time 0 mi h d m y)
405 (or utc (and with-time-p (org-e-icalendar-use-UTC-date-time-p)))))))
407 (defun org-e-icalendar-get-categories (entry info)
408 "Return categories according to `org-e-icalendar-categories'.
409 ENTRY is an headline or an inlinetask element. INFO is a plist
410 used as a communication channel."
411 (mapconcat
412 'identity
413 (org-uniquify
414 (let (categories)
415 (mapc (lambda (type)
416 (case type
417 (category
418 (push (org-export-get-category entry info) categories))
419 (todo-state
420 (let ((todo (org-element-property :todo-keyword entry)))
421 (and todo (push todo categories))))
422 (local-tags
423 (setq categories
424 (append (nreverse (org-export-get-tags entry info))
425 categories)))
426 (all-tags
427 (setq categories
428 (append (nreverse (org-export-get-tags entry info nil t))
429 categories)))))
430 org-e-icalendar-categories)
431 ;; Return list of categories, following specified order.
432 (nreverse categories))) ","))
434 (defun org-e-icalendar-transcode-diary-sexp (sexp uid summary)
435 "Transcode a diary sexp into iCalendar format.
436 SEXP is the diary sexp being transcoded, as a string. UID is the
437 unique identifier for the entry. SUMMARY defines a short summary
438 or subject for the event."
439 (when (require 'icalendar nil t)
440 (org-element-normalize-string
441 (with-temp-buffer
442 (let ((sexp (if (not (string-match "\\`<%%" sexp)) sexp
443 (concat (substring sexp 1 -1) " " summary))))
444 (put-text-property 0 1 'uid uid sexp)
445 (insert sexp "\n"))
446 (org-diary-to-ical-string (current-buffer))))))
448 (defun org-e-icalendar-cleanup-string (s)
449 "Cleanup string S according to RFC 5545."
450 (when s
451 ;; Protect "\", "," and ";" characters. and replace newline
452 ;; characters with literal \n.
453 (replace-regexp-in-string
454 "[ \t]*\n" "\\n"
455 (replace-regexp-in-string "[\\,;]" "\\\&" s)
456 nil t)))
458 (defun org-e-icalendar-fold-string (s)
459 "Fold string S according to RFC 5545."
460 (org-element-normalize-string
461 (mapconcat
462 (lambda (line)
463 ;; Limit each line to a maximum of 75 characters. If it is
464 ;; longer, fold it by using "\n " as a continuation marker.
465 (let ((len (length line)))
466 (if (<= len 75) line
467 (let ((folded-line (substring line 0 75))
468 (chunk-start 75)
469 chunk-end)
470 ;; Since continuation marker takes up one character on the
471 ;; line, real contents must be split at 74 chars.
472 (while (< (setq chunk-end (+ chunk-start 74)) len)
473 (setq folded-line
474 (concat folded-line "\n "
475 (substring line chunk-start chunk-end))
476 chunk-start chunk-end))
477 (concat folded-line "\n " (substring line chunk-start))))))
478 (org-split-string s "\n") "\n")))
482 ;;; Filters
484 (defun org-e-icalendar-clear-blank-lines (headline back-end info)
485 "Remove trailing blank lines in HEADLINE export.
486 HEADLINE is a string representing a transcoded headline.
487 BACK-END and INFO are ignored."
488 (replace-regexp-in-string "^\\(?:[ \t]*\n\\)*" "" headline))
492 ;;; Transcode Functions
494 ;;;; Headline and Inlinetasks
496 ;; The main function is `org-e-icalendar-entry', which extracts
497 ;; information from an headline or an inlinetask (summary,
498 ;; description...) and then delegates code generation to
499 ;; `org-e-icalendar--vtodo' and `org-e-icalendar--vevent', depending
500 ;; on the component needed.
502 ;; Obviously, `org-e-icalendar--valarm' handles alarms, which can
503 ;; happen within a VTODO component.
505 (defun org-e-icalendar-entry (entry contents info)
506 "Transcode ENTRY element into iCalendar format.
508 ENTRY is either an headline or an inlinetask. CONTENTS is
509 ignored. INFO is a plist used as a communication channel.
511 This function is called on every headline, the section below
512 it (minus inlinetasks) being its contents. It tries to create
513 VEVENT and VTODO components out of scheduled date, deadline date,
514 plain timestamps, diary sexps. It also calls itself on every
515 inlinetask within the section."
516 (unless (org-element-property :footnote-section-p entry)
517 (let* ((type (org-element-type entry))
518 ;; Determine contents really associated to the entry. For
519 ;; an headline, limit them to section, if any. For an
520 ;; inlinetask, this is every element within the task.
521 (inside
522 (if (eq type 'inlinetask)
523 (cons 'org-data (cons nil (org-element-contents entry)))
524 (let ((first (car (org-element-contents entry))))
525 (and (eq (org-element-type first) 'section)
526 (cons 'org-data
527 (cons nil (org-element-contents first))))))))
528 (concat
529 (unless (and (plist-get info :icalendar-agenda-view)
530 (not (org-element-property :icalendar-mark entry)))
531 (let ((todo-type (org-element-property :todo-type entry))
532 (uid (or (org-element-property :id entry) (org-id-new)))
533 (summary (org-e-icalendar-cleanup-string
534 (or (org-element-property :summary entry)
535 (org-export-data
536 (org-element-property :title entry) info))))
537 (loc (org-e-icalendar-cleanup-string
538 (org-element-property :location entry)))
539 ;; Build description of the entry from associated
540 ;; section (headline) or contents (inlinetask).
541 (desc
542 (org-e-icalendar-cleanup-string
543 (or (org-element-property :description entry)
544 (let ((contents (org-export-data inside info)))
545 (cond
546 ((not (org-string-nw-p contents)) nil)
547 ((wholenump org-e-icalendar-include-body)
548 (let ((contents (org-trim contents)))
549 (substring
550 contents 0 (min (length contents)
551 org-e-icalendar-include-body))))
552 (org-e-icalendar-include-body (org-trim contents)))))))
553 (cat (org-e-icalendar-get-categories entry info)))
554 (concat
555 ;; Events: Delegate to `org-e-icalendar--vevent' to
556 ;; generate "VEVENT" component from scheduled, deadline,
557 ;; or any timestamp in the entry.
558 (let ((deadline (org-element-property :deadline entry)))
559 (and deadline
560 (memq (if todo-type 'event-if-todo 'event-if-not-todo)
561 org-e-icalendar-use-deadline)
562 (org-e-icalendar--vevent
563 entry deadline (concat "DL-" uid)
564 (concat "DL: " summary) loc desc cat)))
565 (let ((scheduled (org-element-property :scheduled entry)))
566 (and scheduled
567 (memq (if todo-type 'event-if-todo 'event-if-not-todo)
568 org-e-icalendar-use-scheduled)
569 (org-e-icalendar--vevent
570 entry scheduled (concat "SC-" uid)
571 (concat "S: " summary) loc desc cat)))
572 ;; When collecting plain timestamps from an headline, skip
573 ;; inlinetasks since collection will happen once ENTRY is
574 ;; one of them.
575 (let ((counter 0))
576 (mapconcat
577 'identity
578 (org-element-map
579 inside 'timestamp
580 (lambda (ts)
581 (let ((uid (format "TS%d-%s" (incf counter) uid)))
582 (org-e-icalendar--vevent entry ts uid summary loc desc cat)))
583 info nil (and (eq type 'headline) 'inlinetask))
584 ""))
585 ;; Task: First check if it is appropriate to export it.
586 ;; If so, call `org-e-icalendar--vtodo' to transcode it
587 ;; into a "VTODO" component.
588 (when (and todo-type
589 (case (plist-get info :with-vtodo)
590 (all t)
591 (unblocked
592 (and (eq type 'headline)
593 (not (org-e-icalendar-blocked-headline-p
594 entry info))))
595 ('t (eq todo-type 'todo))))
596 (org-e-icalendar--vtodo entry uid summary loc desc cat))
597 ;; Diary-sexp: Collect every diary-sexp element within
598 ;; ENTRY and transcode them. If ENTRY is an headline,
599 ;; skip inlinetasks: they will be handled separately.
600 (when org-e-icalendar-include-sexps
601 (let ((counter 0))
602 (mapconcat 'identity
603 (org-element-map
604 inside 'diary-sexp
605 (lambda (sexp)
606 (org-e-icalendar-transcode-diary-sexp
607 (org-element-property :value sexp)
608 (format "DS%d-%s" (incf counter) uid)
609 summary))
610 info nil (and (eq type 'headline) 'inlinetask))
611 ""))))))
612 ;; If ENTRY is an headline, call current function on every
613 ;; inlinetask within it. In agenda export, this is independent
614 ;; from the mark (or lack thereof) on the entry.
615 (when (eq type 'headline)
616 (mapconcat 'identity
617 (org-element-map
618 inside 'inlinetask
619 (lambda (task) (org-e-icalendar-entry task nil info))
620 info) ""))
621 ;; Don't forget components from inner entries.
622 contents))))
624 (defun org-e-icalendar--vevent
625 (entry timestamp uid summary location description categories)
626 "Create a VEVENT component.
628 ENTRY is either an headline or an inlinetask element. TIMESTAMP
629 is a timestamp object defining the date-time of the event. UID
630 is the unique identifier for the event. SUMMARY defines a short
631 summary or subject for the event. LOCATION defines the intended
632 venue for the event. DESCRIPTION provides the complete
633 description of the event. CATEGORIES defines the categories the
634 event belongs to.
636 Return VEVENT component as a string."
637 (org-e-icalendar-fold-string
638 (if (eq (org-element-property :type timestamp) 'diary)
639 (org-e-icalendar-transcode-diary-sexp
640 (org-element-property :raw-value timestamp) uid summary)
641 (concat "BEGIN:VEVENT\n"
642 (org-e-icalendar-convert-timestamp timestamp "DTSTAMP" nil t) "\n"
643 "UID:" uid "\n"
644 (org-e-icalendar-convert-timestamp timestamp "DTSTART") "\n"
645 (org-e-icalendar-convert-timestamp timestamp "DTEND" t) "\n"
646 ;; RRULE.
647 (when (org-element-property :repeater-type timestamp)
648 (format "RRULE:FREQ=%s;INTERVAL=%d\n"
649 (case (org-element-property :repeater-unit timestamp)
650 (hour "HOURLY") (day "DAILY") (week "WEEKLY")
651 (month "MONTHLY") (year "YEARLY"))
652 (org-element-property :repeater-value timestamp)))
653 "SUMMARY:" summary "\n"
654 (and (org-string-nw-p location) (format "LOCATION:%s\n" location))
655 (and (org-string-nw-p description)
656 (format "DESCRIPTION:%s\n" description))
657 "CATEGORIES:" categories "\n"
658 ;; VALARM.
659 (org-e-icalendar--valarm entry timestamp summary)
660 "END:VEVENT"))))
662 (defun org-e-icalendar--vtodo
663 (entry uid summary location description categories)
664 "Create a VTODO component.
666 ENTRY is either an headline or an inlinetask element. UID is the
667 unique identifier for the task. SUMMARY defines a short summary
668 or subject for the task. LOCATION defines the intended venue for
669 the task. DESCRIPTION provides the complete description of the
670 task. CATEGORIES defines the categories the task belongs to.
672 Return VTODO component as a string."
673 (let ((start (or (and (memq 'todo-start org-e-icalendar-use-scheduled)
674 (org-element-property :scheduled entry))
675 ;; If we can't use a scheduled time for some
676 ;; reason, start task now.
677 (let ((now (decode-time (current-time))))
678 (list 'timestamp
679 (list :type 'active
680 :minute-start (nth 1 now)
681 :hour-start (nth 2 now)
682 :day-start (nth 3 now)
683 :month-start (nth 4 now)
684 :year-start (nth 5 now)))))))
685 (org-e-icalendar-fold-string
686 (concat "BEGIN:VTODO\n"
687 "UID:TODO-" uid "\n"
688 (org-e-icalendar-convert-timestamp start "DTSTAMP" nil t) "\n"
689 (org-e-icalendar-convert-timestamp start "DTSTART") "\n"
690 (and (memq 'todo-due org-e-icalendar-use-deadline)
691 (org-element-property :deadline entry)
692 (concat (org-e-icalendar-convert-timestamp
693 (org-element-property :deadline entry) "DUE")
694 "\n"))
695 "SUMMARY:" summary "\n"
696 (and (org-string-nw-p location) (format "LOCATION:%s\n" location))
697 (and (org-string-nw-p description)
698 (format "DESCRIPTION:%s\n" description))
699 "CATEGORIES:" categories "\n"
700 "SEQUENCE:1\n"
701 (format "PRIORITY:%d\n"
702 (let ((pri (or (org-element-property :priority entry)
703 org-default-priority)))
704 (floor (- 9 (* 8. (/ (float (- org-lowest-priority pri))
705 (- org-lowest-priority
706 org-highest-priority)))))))
707 (format "STATUS:%s\n"
708 (if (eq (org-element-property :todo-type entry) 'todo)
709 "NEEDS-ACTION"
710 "COMPLETED"))
711 "END:VTODO"))))
713 (defun org-e-icalendar--valarm (entry timestamp summary)
714 "Create a VALARM component.
716 ENTRY is the calendar entry triggering the alarm. TIMESTAMP is
717 the start date-time of the entry. SUMMARY defines a short
718 summary or subject for the task.
720 Return VALARM component as a string, or nil if it isn't allowed."
721 ;; Create a VALARM entry if the entry is timed. This is not very
722 ;; general in that:
723 ;; (a) only one alarm per entry is defined,
724 ;; (b) only minutes are allowed for the trigger period ahead of the
725 ;; start time,
726 ;; (c) only a DISPLAY action is defined. [ESF]
727 (let ((alarm-time
728 (let ((warntime
729 (org-element-property :appt-warntime entry)))
730 (if warntime (string-to-number warntime) 0))))
731 (and (or (> alarm-time 0) (> org-e-icalendar-alarm-time 0))
732 (org-element-property :hour-start timestamp)
733 (format "BEGIN:VALARM
734 ACTION:DISPLAY
735 DESCRIPTION:%s
736 TRIGGER:-P0DT0H%dM0S
737 END:VALARM\n"
738 summary
739 (if (zerop alarm-time) org-e-icalendar-alarm-time alarm-time)))))
742 ;;;; Template
744 (defun org-e-icalendar-template (contents info)
745 "Return complete document string after iCalendar conversion.
746 CONTENTS is the transcoded contents string. INFO is a plist used
747 as a communication channel."
748 (org-e-icalendar--vcalendar
749 ;; Name.
750 (if (not (plist-get info :input-file)) (buffer-name (buffer-base-buffer))
751 (file-name-nondirectory
752 (file-name-sans-extension (plist-get info :input-file))))
753 ;; Owner.
754 (if (not (plist-get info :with-author)) ""
755 (org-export-data (plist-get info :author) info))
756 ;; Timezone.
757 (if (org-string-nw-p org-e-icalendar-timezone) org-e-icalendar-timezone
758 (cadr (current-time-zone)))
759 ;; Description.
760 (org-export-data (plist-get info :title) info)
761 contents))
763 (defun org-e-icalendar--vcalendar (name owner tz description contents)
764 "Create a VCALENDAR component.
765 NAME, OWNER, TZ, DESCRIPTION and CONTENTS are all strings giving,
766 respectively, the name of the calendar, its owner, the timezone
767 used, a short description and the other components included."
768 (concat (format "BEGIN:VCALENDAR
769 VERSION:2.0
770 X-WR-CALNAME:%s
771 PRODID:-//%s//Emacs with Org mode//EN
772 X-WR-TIMEZONE:%s
773 X-WR-CALDESC:%s
774 CALSCALE:GREGORIAN\n"
775 (org-e-icalendar-cleanup-string name)
776 (org-e-icalendar-cleanup-string owner)
777 (org-e-icalendar-cleanup-string tz)
778 (org-e-icalendar-cleanup-string description))
779 contents
780 "END:VCALENDAR\n"))
784 ;;; Interactive Functions
786 ;;;###autoload
787 (defun org-e-icalendar-export-to-ics (&optional subtreep visible-only body-only)
788 "Export current buffer to an iCalendar file.
790 If narrowing is active in the current buffer, only export its
791 narrowed part.
793 If a region is active, export that region.
795 When optional argument SUBTREEP is non-nil, export the sub-tree
796 at point, extracting information from the headline properties
797 first.
799 When optional argument VISIBLE-ONLY is non-nil, don't export
800 contents of hidden elements.
802 When optional argument BODY-ONLY is non-nil, only write code
803 between \"BEGIN:VCALENDAR\" and \"END:VCALENDAR\".
805 Return ICS file name."
806 (interactive)
807 (let ((file (buffer-file-name (buffer-base-buffer))))
808 (when (and file org-e-icalendar-store-UID)
809 (org-e-icalendar-create-uid file 'warn-user)))
810 ;; Export part. Since this back-end is backed up by `e-ascii',
811 ;; ensure links will not be collected at the end of sections.
812 (let ((outfile (org-export-output-file-name ".ics" subtreep))
813 (org-e-ascii-links-to-notes nil))
814 (org-export-to-file 'e-icalendar outfile subtreep visible-only body-only
815 '(:ascii-charset utf-8))
816 (run-hook-with-args 'org-e-icalendar-after-save-hook outfile)
817 outfile))
819 ;;;###autoload
820 (defun org-e-icalendar-export-agenda-files ()
821 "Export all agenda files to iCalendar files."
822 (interactive)
823 (let ((files (org-agenda-files t)))
824 (org-agenda-prepare-buffers files)
825 (unwind-protect
826 (mapc (lambda (file)
827 (catch 'nextfile
828 (org-check-agenda-file file)
829 (with-current-buffer (org-get-agenda-file-buffer file)
830 (org-e-icalendar-export-to-ics))))
831 files)
832 (org-release-buffers org-agenda-new-buffers))))
834 ;;;###autoload
835 (defun org-e-icalendar-combine-agenda-files ()
836 "Combine all agenda files into a single iCalendar file.
837 The file is stored under the name
838 `org-e-icalendar-combined-agenda-file'."
839 (interactive)
840 (apply 'org-e-icalendar--combine-files nil (org-agenda-files t)))
842 (defun org-e-icalendar-export-current-agenda ()
843 "Export current agenda view to an iCalendar file.
844 The file is stored under the name
845 `org-e-icalendar-combined-agenda-file'. This function assumes
846 major mode for current buffer is `org-agenda-mode'."
847 (apply 'org-e-icalendar--combine-files
848 (org-create-marker-find-array (org-agenda-collect-markers))
849 (org-agenda-files nil 'ifmode)))
851 (defun org-e-icalendar--combine-files (restriction &rest files)
852 "Combine entries from multiple files into an iCalendar file.
853 RESTRICTION, when non-nil, is an alist where key is a file name
854 and value a list of buffer positions pointing to entries that
855 should appear in the calendar. It only makes sense if the
856 function was called from an agenda buffer. FILES is a list of
857 files to build the calendar from."
858 (org-agenda-prepare-buffers files)
859 (unwind-protect
860 (progn
861 (with-temp-file org-e-icalendar-combined-agenda-file
862 (insert
863 (org-e-icalendar--vcalendar
864 ;; Name.
865 org-e-icalendar-combined-name
866 ;; Owner.
867 user-full-name
868 ;; Timezone.
869 (if (org-string-nw-p org-e-icalendar-timezone)
870 org-e-icalendar-timezone
871 (cadr (current-time-zone)))
872 ;; Description.
873 org-e-icalendar-combined-description
874 ;; Contents.
875 (concat
876 ;; Agenda contents.
877 (mapconcat
878 (lambda (file)
879 (catch 'nextfile
880 (org-check-agenda-file file)
881 (with-current-buffer (org-get-agenda-file-buffer file)
882 ;; Create ID if necessary.
883 (when org-e-icalendar-store-UID
884 (org-e-icalendar-create-uid file))
885 (let ((marks (cdr (assoc (expand-file-name file)
886 restriction))))
887 (unless (and restriction (not marks))
888 ;; Add a hook adding :ICALENDAR_MARK: property
889 ;; to each entry appearing in agenda view.
890 ;; Use `apply-partially' because the function
891 ;; still has to accept one argument.
892 (let ((org-export-before-processing-hook
893 (cons (apply-partially
894 (lambda (m-list dummy)
895 (mapc (lambda (m)
896 (org-entry-put
897 m "ICALENDAR_MARK" "t"))
898 m-list))
899 (sort marks '>))
900 org-export-before-processing-hook)))
901 (org-export-as
902 'e-icalendar nil nil t
903 (list :ascii-charset 'utf-8
904 :icalendar-agenda-view restriction))))))))
905 files "")
906 ;; BBDB anniversaries.
907 (when (and org-e-icalendar-include-bbdb-anniversaries
908 (require 'org-bbdb nil t))
909 (with-temp-buffer
910 (org-bbdb-anniv-export-ical)
911 (buffer-string)))))))
912 (run-hook-with-args 'org-e-icalendar-after-save-hook
913 org-e-icalendar-combined-agenda-file))
914 (org-release-buffers org-agenda-new-buffers)))
917 (provide 'org-e-icalendar)
919 ;;; org-e-icalendar.el ends here