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