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