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