Merge branch 'maint'
[org-mode.git] / lisp / ox-icalendar.el
blob498a43fe51fcb6219b7a67fbf1d82f7431f708c1
1 ;;; ox-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-icalendar-export-to-ics' (current
30 ;; file), `org-icalendar-export-agenda-files' (agenda files into
31 ;; separate calendars) and `org-icalendar-combined-agenda-file'
32 ;; (agenda files into one combined calendar).
34 ;; It also provides `org-icalendar-export-current-agenda' function,
35 ;; which will create a calendar file from current agenda view. It is
36 ;; 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 'ox-ascii)
47 (declare-function org-bbdb-anniv-export-ical "org-bbdb" nil)
51 ;;; User-Configurable Variables
53 (defgroup org-export-icalendar nil
54 "Options specific for iCalendar export back-end."
55 :tag "Org iCalendar"
56 :group 'org-export)
58 (defcustom org-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-icalendar-combine-agenda-files].
61 The file name should be absolute. It will be overwritten without warning."
62 :group 'org-export-icalendar
63 :type 'file)
65 (defcustom org-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-icalendar
75 :version "24.1"
76 :type 'integer)
78 (defcustom org-icalendar-combined-name "OrgMode"
79 "Calendar name for the combined iCalendar representing all agenda files."
80 :group 'org-export-icalendar
81 :type 'string)
83 (defcustom org-icalendar-combined-description ""
84 "Calendar description for the combined iCalendar (all agenda files)."
85 :group 'org-export-icalendar
86 :type 'string)
88 (defcustom org-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-icalendar
94 :type '(repeat (string :tag "Tag")))
96 (defcustom org-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-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-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-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-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-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-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-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-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-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-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-icalendar
184 :type 'boolean)
186 (defcustom org-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-icalendar
191 :type 'boolean)
193 (defcustom org-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-icalendar
199 :type '(choice
200 (const :tag "Nothing" nil)
201 (const :tag "Everything" t)
202 (integer :tag "Max characters")))
204 (defcustom org-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-icalendar
218 :type 'boolean)
220 (defcustom org-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-icalendar
225 :type '(choice
226 (const :tag "Unspecified" nil)
227 (string :tag "Time zone")))
229 (defcustom org-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-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-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-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 icalendar ascii
258 :translate-alist ((clock . ignore)
259 (headline . org-icalendar-entry)
260 (inlinetask . ignore)
261 (planning . ignore)
262 (section . ignore)
263 (template . org-icalendar-template))
264 :options-alist
265 ((:exclude-tags
266 "ICALENDAR_EXCLUDE_TAGS" nil org-icalendar-exclude-tags split)
267 (:with-timestamps nil "<" org-icalendar-with-timestamps)
268 (:with-vtodo nil nil org-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-icalendar-clear-blank-lines))
275 :menu-entry
276 (?c "Export to iCalendar"
277 ((?f "Current file" org-icalendar-export-to-ics)
278 (?a "All agenda files"
279 (lambda (a s v b) (org-icalendar-export-agenda-files a)))
280 (?c "Combine all agenda files"
281 (lambda (a s v b) (org-icalendar-combine-agenda-files a))))))
285 ;;; Internal Functions
287 (defun org-icalendar-create-uid (file &optional bell)
288 "Set ID property on headlines missing it in FILE.
289 When optional argument BELL is non-nil, inform the user with
290 a message if the file was modified."
291 (let (modified-flag)
292 (org-map-entries
293 (lambda ()
294 (let ((entry (org-element-at-point)))
295 (unless (org-element-property :id entry)
296 (org-id-get-create)
297 (setq modified-flag t)
298 (forward-line))
299 (when (eq (org-element-type entry) 'inlinetask)
300 (setq org-map-continue-from (org-element-property :end entry)))))
301 nil nil 'comment)
302 (when (and bell modified-flag)
303 (message "ID properties created in file \"%s\"" file)
304 (sit-for 2))))
306 (defun org-icalendar-blocked-headline-p (headline info)
307 "Non-nil when HEADLINE is considered to be blocked.
309 INFO is a plist used as a communication channel.
311 An headline is blocked when either:
313 - It has children which are not all in a completed state.
315 - It has a parent with the property :ORDERED:, and there are
316 siblings prior to it with incomplete status.
318 - Its parent is blocked because it has siblings that should be
319 done first or is a child of a blocked grandparent entry."
321 ;; Check if any child is not done.
322 (org-element-map headline 'headline
323 (lambda (hl) (eq (org-element-property :todo-type hl) 'todo))
324 info 'first-match)
325 ;; Check :ORDERED: node property.
326 (catch 'blockedp
327 (let ((current headline))
328 (mapc (lambda (parent)
329 (cond
330 ((not (org-element-property :todo-keyword parent))
331 (throw 'blockedp nil))
332 ((org-not-nil (org-element-property :ordered parent))
333 (let ((sibling current))
334 (while (setq sibling (org-export-get-previous-element
335 sibling info))
336 (when (eq (org-element-property :todo-type sibling) 'todo)
337 (throw 'blockedp t)))))
338 (t (setq current parent))))
339 (org-export-get-genealogy headline))
340 nil))))
342 (defun org-icalendar-use-UTC-date-time-p ()
343 "Non-nil when `org-icalendar-date-time-format' requires UTC time."
344 (char-equal (elt org-icalendar-date-time-format
345 (1- (length org-icalendar-date-time-format))) ?Z))
347 (defvar org-agenda-default-appointment-duration) ; From org-agenda.el.
348 (defun org-icalendar-convert-timestamp (timestamp keyword &optional end utc)
349 "Convert TIMESTAMP to iCalendar format.
351 TIMESTAMP is a timestamp object. KEYWORD is added in front of
352 it, in order to make a complete line (e.g. \"DTSTART\").
354 When optional argument END is non-nil, use end of time range.
355 Also increase the hour by two (if time string contains a time),
356 or the day by one (if it does not contain a time) when no
357 explicit ending time is specified.
359 When optional argument UTC is non-nil, time will be expressed in
360 Universal Time, ignoring `org-icalendar-date-time-format'.
361 This is mandatory for \"DTSTAMP\" property."
362 (let* ((year-start (org-element-property :year-start timestamp))
363 (year-end (org-element-property :year-end timestamp))
364 (month-start (org-element-property :month-start timestamp))
365 (month-end (org-element-property :month-end timestamp))
366 (day-start (org-element-property :day-start timestamp))
367 (day-end (org-element-property :day-end timestamp))
368 (hour-start (org-element-property :hour-start timestamp))
369 (hour-end (org-element-property :hour-end timestamp))
370 (minute-start (org-element-property :minute-start timestamp))
371 (minute-end (org-element-property :minute-end timestamp))
372 (with-time-p minute-start)
373 (equal-bounds-p
374 (equal (list year-start month-start day-start hour-start minute-start)
375 (list year-end month-end day-end hour-end minute-end)))
376 (mi (cond ((not with-time-p) 0)
377 ((not end) minute-start)
378 ((and org-agenda-default-appointment-duration equal-bounds-p)
379 (+ minute-end org-agenda-default-appointment-duration))
380 (t minute-end)))
381 (h (cond ((not with-time-p) 0)
382 ((not end) hour-start)
383 ((or (not equal-bounds-p)
384 org-agenda-default-appointment-duration)
385 hour-end)
386 (t (+ hour-end 2))))
387 (d (cond ((not end) day-start)
388 ((not with-time-p) (1+ day-end))
389 (t day-end)))
390 (m (if end month-end month-start))
391 (y (if end year-end year-start)))
392 (concat
393 keyword
394 (format-time-string
395 (cond (utc ":%Y%m%dT%H%M%SZ")
396 ((not with-time-p) ";VALUE=DATE:%Y%m%d")
397 (t (replace-regexp-in-string "%Z"
398 org-icalendar-timezone
399 org-icalendar-date-time-format
400 t)))
401 ;; Convert timestamp into internal time in order to use
402 ;; `format-time-string' and fix any mistake (i.e. MI >= 60).
403 (encode-time 0 mi h d m y)
404 (or utc (and with-time-p (org-icalendar-use-UTC-date-time-p)))))))
406 (defun org-icalendar-get-categories (entry info)
407 "Return categories according to `org-icalendar-categories'.
408 ENTRY is an headline or an inlinetask element. INFO is a plist
409 used as a communication channel."
410 (mapconcat
411 'identity
412 (org-uniquify
413 (let (categories)
414 (mapc (lambda (type)
415 (case type
416 (category
417 (push (org-export-get-category entry info) categories))
418 (todo-state
419 (let ((todo (org-element-property :todo-keyword entry)))
420 (and todo (push todo categories))))
421 (local-tags
422 (setq categories
423 (append (nreverse (org-export-get-tags entry info))
424 categories)))
425 (all-tags
426 (setq categories
427 (append (nreverse (org-export-get-tags entry info nil t))
428 categories)))))
429 org-icalendar-categories)
430 ;; Return list of categories, following specified order.
431 (nreverse categories))) ","))
433 (defun org-icalendar-transcode-diary-sexp (sexp uid summary)
434 "Transcode a diary sexp into iCalendar format.
435 SEXP is the diary sexp being transcoded, as a string. UID is the
436 unique identifier for the entry. SUMMARY defines a short summary
437 or subject for the event."
438 (when (require 'icalendar nil t)
439 (org-element-normalize-string
440 (with-temp-buffer
441 (let ((sexp (if (not (string-match "\\`<%%" sexp)) sexp
442 (concat (substring sexp 1 -1) " " summary))))
443 (put-text-property 0 1 'uid uid sexp)
444 (insert sexp "\n"))
445 (org-diary-to-ical-string (current-buffer))))))
447 (defun org-icalendar-cleanup-string (s)
448 "Cleanup string S according to RFC 5545."
449 (when s
450 ;; Protect "\", "," and ";" characters. and replace newline
451 ;; characters with literal \n.
452 (replace-regexp-in-string
453 "[ \t]*\n" "\\n"
454 (replace-regexp-in-string "[\\,;]" "\\\&" s)
455 nil t)))
457 (defun org-icalendar-fold-string (s)
458 "Fold string S according to RFC 5545."
459 (org-element-normalize-string
460 (mapconcat
461 (lambda (line)
462 ;; Limit each line to a maximum of 75 characters. If it is
463 ;; longer, fold it by using "\n " as a continuation marker.
464 (let ((len (length line)))
465 (if (<= len 75) line
466 (let ((folded-line (substring line 0 75))
467 (chunk-start 75)
468 chunk-end)
469 ;; Since continuation marker takes up one character on the
470 ;; line, real contents must be split at 74 chars.
471 (while (< (setq chunk-end (+ chunk-start 74)) len)
472 (setq folded-line
473 (concat folded-line "\n "
474 (substring line chunk-start chunk-end))
475 chunk-start chunk-end))
476 (concat folded-line "\n " (substring line chunk-start))))))
477 (org-split-string s "\n") "\n")))
481 ;;; Filters
483 (defun org-icalendar-clear-blank-lines (headline back-end info)
484 "Remove trailing blank lines in HEADLINE export.
485 HEADLINE is a string representing a transcoded headline.
486 BACK-END and INFO are ignored."
487 (replace-regexp-in-string "^\\(?:[ \t]*\n\\)*" "" headline))
491 ;;; Transcode Functions
493 ;;;; Headline and Inlinetasks
495 ;; The main function is `org-icalendar-entry', which extracts
496 ;; information from an headline or an inlinetask (summary,
497 ;; description...) and then delegates code generation to
498 ;; `org-icalendar--vtodo' and `org-icalendar--vevent', depending
499 ;; on the component needed.
501 ;; Obviously, `org-icalendar--valarm' handles alarms, which can
502 ;; happen within a VTODO component.
504 (defun org-icalendar-entry (entry contents info)
505 "Transcode ENTRY element into iCalendar format.
507 ENTRY is either an headline or an inlinetask. CONTENTS is
508 ignored. INFO is a plist used as a communication channel.
510 This function is called on every headline, the section below
511 it (minus inlinetasks) being its contents. It tries to create
512 VEVENT and VTODO components out of scheduled date, deadline date,
513 plain timestamps, diary sexps. It also calls itself on every
514 inlinetask within the section."
515 (unless (org-element-property :footnote-section-p entry)
516 (let* ((type (org-element-type entry))
517 ;; Determine contents really associated to the entry. For
518 ;; an headline, limit them to section, if any. For an
519 ;; inlinetask, this is every element within the task.
520 (inside
521 (if (eq type 'inlinetask)
522 (cons 'org-data (cons nil (org-element-contents entry)))
523 (let ((first (car (org-element-contents entry))))
524 (and (eq (org-element-type first) 'section)
525 (cons 'org-data
526 (cons nil (org-element-contents first))))))))
527 (concat
528 (unless (and (plist-get info :icalendar-agenda-view)
529 (not (org-element-property :icalendar-mark entry)))
530 (let ((todo-type (org-element-property :todo-type entry))
531 (uid (or (org-element-property :id entry) (org-id-new)))
532 (summary (org-icalendar-cleanup-string
533 (or (org-element-property :summary entry)
534 (org-export-data
535 (org-element-property :title entry) info))))
536 (loc (org-icalendar-cleanup-string
537 (org-element-property :location entry)))
538 ;; Build description of the entry from associated
539 ;; section (headline) or contents (inlinetask).
540 (desc
541 (org-icalendar-cleanup-string
542 (or (org-element-property :description entry)
543 (let ((contents (org-export-data inside info)))
544 (cond
545 ((not (org-string-nw-p contents)) nil)
546 ((wholenump org-icalendar-include-body)
547 (let ((contents (org-trim contents)))
548 (substring
549 contents 0 (min (length contents)
550 org-icalendar-include-body))))
551 (org-icalendar-include-body (org-trim contents)))))))
552 (cat (org-icalendar-get-categories entry info)))
553 (concat
554 ;; Events: Delegate to `org-icalendar--vevent' to
555 ;; generate "VEVENT" component from scheduled, deadline,
556 ;; or any timestamp in the entry.
557 (let ((deadline (org-element-property :deadline entry)))
558 (and deadline
559 (memq (if todo-type 'event-if-todo 'event-if-not-todo)
560 org-icalendar-use-deadline)
561 (org-icalendar--vevent
562 entry deadline (concat "DL-" uid)
563 (concat "DL: " summary) loc desc cat)))
564 (let ((scheduled (org-element-property :scheduled entry)))
565 (and scheduled
566 (memq (if todo-type 'event-if-todo 'event-if-not-todo)
567 org-icalendar-use-scheduled)
568 (org-icalendar--vevent
569 entry scheduled (concat "SC-" uid)
570 (concat "S: " summary) loc desc cat)))
571 ;; When collecting plain timestamps from an headline and
572 ;; its title, skip inlinetasks since collection will
573 ;; happen once ENTRY is one of them.
574 (let ((counter 0))
575 (mapconcat
576 'identity
577 (org-element-map (cons (org-element-property :title entry)
578 (org-element-contents inside))
579 'timestamp
580 (lambda (ts)
581 (let ((uid (format "TS%d-%s" (incf counter) uid)))
582 (org-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-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-icalendar-blocked-headline-p
594 entry info))))
595 ('t (eq todo-type 'todo))))
596 (org-icalendar--vtodo entry uid summary loc desc cat))
597 ;; Diary-sexp: Collect every diary-sexp element within
598 ;; ENTRY and its title, and transcode them. If ENTRY is
599 ;; an headline, skip inlinetasks: they will be handled
600 ;; separately.
601 (when org-icalendar-include-sexps
602 (let ((counter 0))
603 (mapconcat 'identity
604 (org-element-map
605 (cons (org-element-property :title entry)
606 (org-element-contents inside))
607 'diary-sexp
608 (lambda (sexp)
609 (org-icalendar-transcode-diary-sexp
610 (org-element-property :value sexp)
611 (format "DS%d-%s" (incf counter) uid)
612 summary))
613 info nil (and (eq type 'headline) 'inlinetask))
614 ""))))))
615 ;; If ENTRY is an headline, call current function on every
616 ;; inlinetask within it. In agenda export, this is independent
617 ;; from the mark (or lack thereof) on the entry.
618 (when (eq type 'headline)
619 (mapconcat 'identity
620 (org-element-map inside 'inlinetask
621 (lambda (task) (org-icalendar-entry task nil info))
622 info) ""))
623 ;; Don't forget components from inner entries.
624 contents))))
626 (defun org-icalendar--vevent
627 (entry timestamp uid summary location description categories)
628 "Create a VEVENT component.
630 ENTRY is either an headline or an inlinetask element. TIMESTAMP
631 is a timestamp object defining the date-time of the event. UID
632 is the unique identifier for the event. SUMMARY defines a short
633 summary or subject for the event. LOCATION defines the intended
634 venue for the event. DESCRIPTION provides the complete
635 description of the event. CATEGORIES defines the categories the
636 event belongs to.
638 Return VEVENT component as a string."
639 (org-icalendar-fold-string
640 (if (eq (org-element-property :type timestamp) 'diary)
641 (org-icalendar-transcode-diary-sexp
642 (org-element-property :raw-value timestamp) uid summary)
643 (concat "BEGIN:VEVENT\n"
644 (org-icalendar-convert-timestamp timestamp "DTSTAMP" nil t) "\n"
645 "UID:" uid "\n"
646 (org-icalendar-convert-timestamp timestamp "DTSTART") "\n"
647 (org-icalendar-convert-timestamp timestamp "DTEND" t) "\n"
648 ;; RRULE.
649 (when (org-element-property :repeater-type timestamp)
650 (format "RRULE:FREQ=%s;INTERVAL=%d\n"
651 (case (org-element-property :repeater-unit timestamp)
652 (hour "HOURLY") (day "DAILY") (week "WEEKLY")
653 (month "MONTHLY") (year "YEARLY"))
654 (org-element-property :repeater-value timestamp)))
655 "SUMMARY:" summary "\n"
656 (and (org-string-nw-p location) (format "LOCATION:%s\n" location))
657 (and (org-string-nw-p description)
658 (format "DESCRIPTION:%s\n" description))
659 "CATEGORIES:" categories "\n"
660 ;; VALARM.
661 (org-icalendar--valarm entry timestamp summary)
662 "END:VEVENT"))))
664 (defun org-icalendar--vtodo
665 (entry uid summary location description categories)
666 "Create a VTODO component.
668 ENTRY is either an headline or an inlinetask element. UID is the
669 unique identifier for the task. SUMMARY defines a short summary
670 or subject for the task. LOCATION defines the intended venue for
671 the task. DESCRIPTION provides the complete description of the
672 task. CATEGORIES defines the categories the task belongs to.
674 Return VTODO component as a string."
675 (let ((start (or (and (memq 'todo-start org-icalendar-use-scheduled)
676 (org-element-property :scheduled entry))
677 ;; If we can't use a scheduled time for some
678 ;; reason, start task now.
679 (let ((now (decode-time (current-time))))
680 (list 'timestamp
681 (list :type 'active
682 :minute-start (nth 1 now)
683 :hour-start (nth 2 now)
684 :day-start (nth 3 now)
685 :month-start (nth 4 now)
686 :year-start (nth 5 now)))))))
687 (org-icalendar-fold-string
688 (concat "BEGIN:VTODO\n"
689 "UID:TODO-" uid "\n"
690 (org-icalendar-convert-timestamp start "DTSTAMP" nil t) "\n"
691 (org-icalendar-convert-timestamp start "DTSTART") "\n"
692 (and (memq 'todo-due org-icalendar-use-deadline)
693 (org-element-property :deadline entry)
694 (concat (org-icalendar-convert-timestamp
695 (org-element-property :deadline entry) "DUE")
696 "\n"))
697 "SUMMARY:" summary "\n"
698 (and (org-string-nw-p location) (format "LOCATION:%s\n" location))
699 (and (org-string-nw-p description)
700 (format "DESCRIPTION:%s\n" description))
701 "CATEGORIES:" categories "\n"
702 "SEQUENCE:1\n"
703 (format "PRIORITY:%d\n"
704 (let ((pri (or (org-element-property :priority entry)
705 org-default-priority)))
706 (floor (- 9 (* 8. (/ (float (- org-lowest-priority pri))
707 (- org-lowest-priority
708 org-highest-priority)))))))
709 (format "STATUS:%s\n"
710 (if (eq (org-element-property :todo-type entry) 'todo)
711 "NEEDS-ACTION"
712 "COMPLETED"))
713 "END:VTODO"))))
715 (defun org-icalendar--valarm (entry timestamp summary)
716 "Create a VALARM component.
718 ENTRY is the calendar entry triggering the alarm. TIMESTAMP is
719 the start date-time of the entry. SUMMARY defines a short
720 summary or subject for the task.
722 Return VALARM component as a string, or nil if it isn't allowed."
723 ;; Create a VALARM entry if the entry is timed. This is not very
724 ;; general in that:
725 ;; (a) only one alarm per entry is defined,
726 ;; (b) only minutes are allowed for the trigger period ahead of the
727 ;; start time,
728 ;; (c) only a DISPLAY action is defined. [ESF]
729 (let ((alarm-time
730 (let ((warntime
731 (org-element-property :appt-warntime entry)))
732 (if warntime (string-to-number warntime) 0))))
733 (and (or (> alarm-time 0) (> org-icalendar-alarm-time 0))
734 (org-element-property :hour-start timestamp)
735 (format "BEGIN:VALARM
736 ACTION:DISPLAY
737 DESCRIPTION:%s
738 TRIGGER:-P0DT0H%dM0S
739 END:VALARM\n"
740 summary
741 (if (zerop alarm-time) org-icalendar-alarm-time alarm-time)))))
744 ;;;; Template
746 (defun org-icalendar-template (contents info)
747 "Return complete document string after iCalendar conversion.
748 CONTENTS is the transcoded contents string. INFO is a plist used
749 as a communication channel."
750 (org-icalendar--vcalendar
751 ;; Name.
752 (if (not (plist-get info :input-file)) (buffer-name (buffer-base-buffer))
753 (file-name-nondirectory
754 (file-name-sans-extension (plist-get info :input-file))))
755 ;; Owner.
756 (if (not (plist-get info :with-author)) ""
757 (org-export-data (plist-get info :author) info))
758 ;; Timezone.
759 (if (org-string-nw-p org-icalendar-timezone) org-icalendar-timezone
760 (cadr (current-time-zone)))
761 ;; Description.
762 (org-export-data (plist-get info :title) info)
763 contents))
765 (defun org-icalendar--vcalendar (name owner tz description contents)
766 "Create a VCALENDAR component.
767 NAME, OWNER, TZ, DESCRIPTION and CONTENTS are all strings giving,
768 respectively, the name of the calendar, its owner, the timezone
769 used, a short description and the other components included."
770 (concat (format "BEGIN:VCALENDAR
771 VERSION:2.0
772 X-WR-CALNAME:%s
773 PRODID:-//%s//Emacs with Org mode//EN
774 X-WR-TIMEZONE:%s
775 X-WR-CALDESC:%s
776 CALSCALE:GREGORIAN\n"
777 (org-icalendar-cleanup-string name)
778 (org-icalendar-cleanup-string owner)
779 (org-icalendar-cleanup-string tz)
780 (org-icalendar-cleanup-string description))
781 contents
782 "END:VCALENDAR\n"))
786 ;;; Interactive Functions
788 ;;;###autoload
789 (defun org-icalendar-export-to-ics
790 (&optional async subtreep visible-only body-only)
791 "Export current buffer to an iCalendar file.
793 If narrowing is active in the current buffer, only export its
794 narrowed part.
796 If a region is active, export that region.
798 A non-nil optional argument ASYNC means the process should happen
799 asynchronously. The resulting file should be accessible through
800 the `org-export-stack' interface.
802 When optional argument SUBTREEP is non-nil, export the sub-tree
803 at point, extracting information from the headline properties
804 first.
806 When optional argument VISIBLE-ONLY is non-nil, don't export
807 contents of hidden elements.
809 When optional argument BODY-ONLY is non-nil, only write code
810 between \"BEGIN:VCALENDAR\" and \"END:VCALENDAR\".
812 Return ICS file name."
813 (interactive)
814 (let ((file (buffer-file-name (buffer-base-buffer))))
815 (when (and file org-icalendar-store-UID)
816 (org-icalendar-create-uid file 'warn-user)))
817 ;; Export part. Since this back-end is backed up by `e-ascii',
818 ;; ensure links will not be collected at the end of sections.
819 (let ((outfile (org-export-output-file-name ".ics" subtreep)))
820 (if async
821 (org-export-async-start
822 (lambda (f)
823 (org-export-add-to-stack f 'icalendar)
824 (run-hook-with-args 'org-icalendar-after-save-hook f))
825 `(let ((org-ascii-links-to-notes nil))
826 (expand-file-name
827 (org-export-to-file
828 'icalendar ,outfile ,subtreep ,visible-only ,body-only
829 '(:ascii-charset utf-8)))))
830 (let ((org-ascii-links-to-notes nil))
831 (org-export-to-file 'icalendar outfile subtreep visible-only body-only
832 '(:ascii-charset utf-8)))
833 (run-hook-with-args 'org-icalendar-after-save-hook outfile)
834 outfile)))
836 ;;;###autoload
837 (defun org-icalendar-export-agenda-files (&optional async)
838 "Export all agenda files to iCalendar files.
839 When optional argument ASYNC is non-nil, export happens in an
840 external process."
841 (interactive)
842 (if async
843 ;; Asynchronous export is not interactive, so we will not call
844 ;; `org-check-agenda-file'. Instead we remove any non-existent
845 ;; agenda file from the list.
846 (let ((files (org-remove-if-not 'file-exists-p (org-agenda-files t))))
847 (org-export-async-start
848 (lambda (results)
849 (mapc (lambda (f) (org-export-add-to-stack f 'icalendar))
850 results))
851 `(let (output-files)
852 (mapc (lambda (file)
853 (with-current-buffer (org-get-agenda-file-buffer file)
854 (push (expand-file-name (org-icalendar-export-to-ics))
855 output-files)))
856 ',files)
857 output-files)))
858 (let ((files (org-agenda-files t)))
859 (org-agenda-prepare-buffers files)
860 (unwind-protect
861 (mapc (lambda (file)
862 (catch 'nextfile
863 (org-check-agenda-file file)
864 (with-current-buffer (org-get-agenda-file-buffer file)
865 (org-icalendar-export-to-ics))))
866 files)
867 (org-release-buffers org-agenda-new-buffers)))))
869 ;;;###autoload
870 (defun org-icalendar-combine-agenda-files (&optional async)
871 "Combine all agenda files into a single iCalendar file.
873 A non-nil optional argument ASYNC means the process should happen
874 asynchronously. The resulting file should be accessible through
875 the `org-export-stack' interface.
877 The file is stored under the name chosen in
878 `org-icalendar-combined-agenda-file'."
879 (interactive)
880 (if async
881 (let ((files (org-remove-if-not 'file-exists-p (org-agenda-files t))))
882 (org-export-async-start
883 (lambda (dummy)
884 (org-export-add-to-stack
885 (expand-file-name org-icalendar-combined-agenda-file)
886 'icalendar))
887 `(apply 'org-icalendar--combine-files nil ',files)))
888 (apply 'org-icalendar--combine-files nil (org-agenda-files t))))
890 (declare-function org-agenda-collect-markers "org-agenda" ())
891 (declare-function org-create-marker-find-array "org-agenda" (marker-list))
892 (defun org-icalendar-export-current-agenda (file)
893 "Export current agenda view to an iCalendar FILE.
894 This function assumes major mode for current buffer is
895 `org-agenda-mode'."
896 (let ((org-icalendar-combined-agenda-file file))
897 (apply 'org-icalendar--combine-files
898 (org-create-marker-find-array (org-agenda-collect-markers))
899 (org-agenda-files nil 'ifmode))))
901 (defun org-icalendar--combine-files (restriction &rest files)
902 "Combine entries from multiple files into an iCalendar file.
903 RESTRICTION, when non-nil, is an alist where key is a file name
904 and value a list of buffer positions pointing to entries that
905 should appear in the calendar. It only makes sense if the
906 function was called from an agenda buffer. FILES is a list of
907 files to build the calendar from."
908 (org-agenda-prepare-buffers files)
909 (unwind-protect
910 (progn
911 (with-temp-file org-icalendar-combined-agenda-file
912 (insert
913 (org-icalendar--vcalendar
914 ;; Name.
915 org-icalendar-combined-name
916 ;; Owner.
917 user-full-name
918 ;; Timezone.
919 (if (org-string-nw-p org-icalendar-timezone)
920 org-icalendar-timezone
921 (cadr (current-time-zone)))
922 ;; Description.
923 org-icalendar-combined-description
924 ;; Contents.
925 (concat
926 ;; Agenda contents.
927 (mapconcat
928 (lambda (file)
929 (catch 'nextfile
930 (org-check-agenda-file file)
931 (with-current-buffer (org-get-agenda-file-buffer file)
932 ;; Create ID if necessary.
933 (when org-icalendar-store-UID
934 (org-icalendar-create-uid file))
935 (let ((marks (cdr (assoc (expand-file-name file)
936 restriction))))
937 (unless (and restriction (not marks))
938 ;; Add a hook adding :ICALENDAR_MARK: property
939 ;; to each entry appearing in agenda view.
940 ;; Use `apply-partially' because the function
941 ;; still has to accept one argument.
942 (let ((org-export-before-processing-hook
943 (cons (apply-partially
944 (lambda (m-list dummy)
945 (mapc (lambda (m)
946 (org-entry-put
947 m "ICALENDAR_MARK" "t"))
948 m-list))
949 (sort marks '>))
950 org-export-before-processing-hook)))
951 (org-export-as
952 'icalendar nil nil t
953 (list :ascii-charset 'utf-8
954 :icalendar-agenda-view restriction))))))))
955 files "")
956 ;; BBDB anniversaries.
957 (when (and org-icalendar-include-bbdb-anniversaries
958 (require 'org-bbdb nil t))
959 (with-temp-buffer
960 (org-bbdb-anniv-export-ical)
961 (buffer-string)))))))
962 (run-hook-with-args 'org-icalendar-after-save-hook
963 org-icalendar-combined-agenda-file))
964 (org-release-buffers org-agenda-new-buffers)))
967 (provide 'ox-icalendar)
969 ;; Local variables:
970 ;; generated-autoload-file: "org-loaddefs.el"
971 ;; End:
973 ;;; ox-icalendar.el ends here