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