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