Merge branch 'maint'
[org-mode.git] / lisp / ox-icalendar.el
blobd406f4f8fc1c0d6a44e65c29f44419eec1cdfad9
1 ;;; ox-icalendar.el --- iCalendar Back-End for Org Export Engine -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2004-2015 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 'cl-lib)
36 (require 'ox-ascii)
37 (declare-function org-bbdb-anniv-export-ical "org-bbdb" nil)
41 ;;; User-Configurable Variables
43 (defgroup org-export-icalendar nil
44 "Options specific for iCalendar export back-end."
45 :tag "Org Export iCalendar"
46 :group 'org-export)
48 (defcustom org-icalendar-combined-agenda-file "~/org.ics"
49 "The file name for the iCalendar file covering all agenda files.
50 This file is created with the command \\[org-icalendar-combine-agenda-files].
51 The file name should be absolute. It will be overwritten without warning."
52 :group 'org-export-icalendar
53 :type 'file)
55 (defcustom org-icalendar-alarm-time 0
56 "Number of minutes for triggering an alarm for exported timed events.
58 A zero value (the default) turns off the definition of an alarm trigger
59 for timed events. If non-zero, alarms are created.
61 - a single alarm per entry is defined
62 - The alarm will go off N minutes before the event
63 - only a DISPLAY action is defined."
64 :group 'org-export-icalendar
65 :version "24.1"
66 :type 'integer)
68 (defcustom org-icalendar-combined-name "OrgMode"
69 "Calendar name for the combined iCalendar representing all agenda files."
70 :group 'org-export-icalendar
71 :type 'string)
73 (defcustom org-icalendar-combined-description ""
74 "Calendar description for the combined iCalendar (all agenda files)."
75 :group 'org-export-icalendar
76 :type 'string)
78 (defcustom org-icalendar-exclude-tags nil
79 "Tags that exclude a tree from export.
80 This variable allows to specify different exclude tags from other
81 back-ends. It can also be set with the ICALENDAR_EXCLUDE_TAGS
82 keyword."
83 :group 'org-export-icalendar
84 :type '(repeat (string :tag "Tag")))
86 (defcustom org-icalendar-use-deadline '(event-if-not-todo todo-due)
87 "Contexts where iCalendar export should use a deadline time stamp.
89 This is a list with possibly several symbols in it. Valid symbols are:
91 `event-if-todo' Deadlines in TODO entries become calendar events.
92 `event-if-not-todo' Deadlines in non-TODO entries become calendar events.
93 `todo-due' Use deadlines in TODO entries as due-dates."
94 :group 'org-export-icalendar
95 :type '(set :greedy t
96 (const :tag "Deadlines in non-TODO entries become events"
97 event-if-not-todo)
98 (const :tag "Deadline in TODO entries become events"
99 event-if-todo)
100 (const :tag "Deadlines in TODO entries become due-dates"
101 todo-due)))
103 (defcustom org-icalendar-use-scheduled '(todo-start)
104 "Contexts where iCalendar export should use a scheduling time stamp.
106 This is a list with possibly several symbols in it. Valid symbols are:
108 `event-if-todo' Scheduling time stamps in TODO entries become an event.
109 `event-if-not-todo' Scheduling time stamps in non-TODO entries become an event.
110 `todo-start' Scheduling time stamps in TODO entries become start date.
111 Some calendar applications show TODO entries only after
112 that date."
113 :group 'org-export-icalendar
114 :type '(set :greedy t
115 (const :tag
116 "SCHEDULED timestamps in non-TODO entries become events"
117 event-if-not-todo)
118 (const :tag "SCHEDULED timestamps in TODO entries become events"
119 event-if-todo)
120 (const :tag "SCHEDULED in TODO entries become start date"
121 todo-start)))
123 (defcustom org-icalendar-categories '(local-tags category)
124 "Items that should be entered into the \"categories\" field.
126 This is a list of symbols, the following are valid:
127 `category' The Org mode category of the current file or tree
128 `todo-state' The todo state, if any
129 `local-tags' The tags, defined in the current line
130 `all-tags' All tags, including inherited ones."
131 :group 'org-export-icalendar
132 :type '(repeat
133 (choice
134 (const :tag "The file or tree category" category)
135 (const :tag "The TODO state" todo-state)
136 (const :tag "Tags defined in current line" local-tags)
137 (const :tag "All tags, including inherited ones" all-tags))))
139 (defcustom org-icalendar-with-timestamps 'active
140 "Non-nil means make an event from plain time stamps.
142 It can be set to `active', `inactive', t or nil, in order to make
143 an event from, respectively, only active timestamps, only
144 inactive ones, all of them or none.
146 This variable has precedence over `org-export-with-timestamps'.
147 It can also be set with the #+OPTIONS line, e.g. \"<:t\"."
148 :group 'org-export-icalendar
149 :type '(choice
150 (const :tag "All timestamps" t)
151 (const :tag "Only active timestamps" active)
152 (const :tag "Only inactive timestamps" inactive)
153 (const :tag "No timestamp" nil)))
155 (defcustom org-icalendar-include-todo nil
156 "Non-nil means create VTODO components from TODO items.
158 Valid values are:
159 nil don't include any task.
160 t include tasks that are not in DONE state.
161 `unblocked' include all TODO items that are not blocked.
162 `all' include both done and not done items."
163 :group 'org-export-icalendar
164 :type '(choice
165 (const :tag "None" nil)
166 (const :tag "Unfinished" t)
167 (const :tag "Unblocked" unblocked)
168 (const :tag "All" all)
169 (repeat :tag "Specific TODO keywords"
170 (string :tag "Keyword"))))
172 (defcustom org-icalendar-include-bbdb-anniversaries nil
173 "Non-nil means a combined iCalendar file should include anniversaries.
174 The anniversaries are defined in the BBDB database."
175 :group 'org-export-icalendar
176 :type 'boolean)
178 (defcustom org-icalendar-include-sexps t
179 "Non-nil means export to iCalendar files should also cover sexp entries.
180 These are entries like in the diary, but directly in an Org file."
181 :group 'org-export-icalendar
182 :type 'boolean)
184 (defcustom org-icalendar-include-body t
185 "Amount of text below headline to be included in iCalendar export.
186 This is a number of characters that should maximally be included.
187 Properties, scheduling and clocking lines will always be removed.
188 The text will be inserted into the DESCRIPTION field."
189 :group 'org-export-icalendar
190 :type '(choice
191 (const :tag "Nothing" nil)
192 (const :tag "Everything" t)
193 (integer :tag "Max characters")))
195 (defcustom org-icalendar-store-UID nil
196 "Non-nil means store any created UIDs in properties.
198 The iCalendar standard requires that all entries have a unique identifier.
199 Org will create these identifiers as needed. When this variable is non-nil,
200 the created UIDs will be stored in the ID property of the entry. Then the
201 next time this entry is exported, it will be exported with the same UID,
202 superseding the previous form of it. This is essential for
203 synchronization services.
205 This variable is not turned on by default because we want to avoid creating
206 a property drawer in every entry if people are only playing with this feature,
207 or if they are only using it locally."
208 :group 'org-export-icalendar
209 :type 'boolean)
211 (defcustom org-icalendar-timezone (getenv "TZ")
212 "The time zone string for iCalendar export.
213 When nil or the empty string, use output
214 from (current-time-zone)."
215 :group 'org-export-icalendar
216 :type '(choice
217 (const :tag "Unspecified" nil)
218 (string :tag "Time zone")))
220 (defcustom org-icalendar-date-time-format ":%Y%m%dT%H%M%S"
221 "Format-string for exporting icalendar DATE-TIME.
223 See `format-time-string' for a full documentation. The only
224 difference is that `org-icalendar-timezone' is used for %Z.
226 Interesting value are:
227 - \":%Y%m%dT%H%M%S\" for local time
228 - \";TZID=%Z:%Y%m%dT%H%M%S\" for local time with explicit timezone
229 - \":%Y%m%dT%H%M%SZ\" for time expressed in Universal Time"
230 :group 'org-export-icalendar
231 :version "24.1"
232 :type '(choice
233 (const :tag "Local time" ":%Y%m%dT%H%M%S")
234 (const :tag "Explicit local time" ";TZID=%Z:%Y%m%dT%H%M%S")
235 (const :tag "Universal time" ":%Y%m%dT%H%M%SZ")
236 (string :tag "Explicit format")))
238 (defvar org-icalendar-after-save-hook nil
239 "Hook run after an iCalendar file has been saved.
240 This hook is run with the name of the file as argument. A good
241 way to use this is to tell a desktop calendar application to
242 re-read the iCalendar file.")
246 ;;; Define Back-End
248 (org-export-define-derived-backend 'icalendar 'ascii
249 :translate-alist '((clock . ignore)
250 (footnote-definition . ignore)
251 (footnote-reference . ignore)
252 (headline . org-icalendar-entry)
253 (inlinetask . ignore)
254 (planning . ignore)
255 (section . ignore)
256 (inner-template . (lambda (c i) c))
257 (template . org-icalendar-template))
258 :options-alist
259 '((:exclude-tags
260 "ICALENDAR_EXCLUDE_TAGS" nil org-icalendar-exclude-tags split)
261 (:with-timestamps nil "<" org-icalendar-with-timestamps)
262 ;; Other variables.
263 (:icalendar-alarm-time nil nil org-icalendar-alarm-time)
264 (:icalendar-categories nil nil org-icalendar-categories)
265 (:icalendar-date-time-format nil nil org-icalendar-date-time-format)
266 (:icalendar-include-bbdb-anniversaries nil nil org-icalendar-include-bbdb-anniversaries)
267 (:icalendar-include-body nil nil org-icalendar-include-body)
268 (:icalendar-include-sexps nil nil org-icalendar-include-sexps)
269 (:icalendar-include-todo nil nil org-icalendar-include-todo)
270 (:icalendar-store-UID nil nil org-icalendar-store-UID)
271 (:icalendar-timezone nil nil org-icalendar-timezone)
272 (:icalendar-use-deadline nil nil org-icalendar-use-deadline)
273 (:icalendar-use-scheduled nil nil org-icalendar-use-scheduled))
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)
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."
292 (let (modified-flag)
293 (org-map-entries
294 (lambda ()
295 (let ((entry (org-element-at-point)))
296 (unless (org-element-property :ID entry)
297 (org-id-get-create)
298 (setq modified-flag t)
299 (forward-line))))
300 nil nil 'comment)
301 (when (and bell modified-flag)
302 (message "ID properties created in file \"%s\"" file)
303 (sit-for 2))))
305 (defun org-icalendar-blocked-headline-p (headline info)
306 "Non-nil when HEADLINE is considered to be blocked.
308 INFO is a plist used as a communication channel.
310 A headline is blocked when either
312 - it has children which are not all in a completed state;
314 - it has a parent with the property :ORDERED:, and there are
315 siblings prior to it with incomplete status;
317 - its parent is blocked because it has siblings that should be
318 done first or is a child of a blocked grandparent entry."
320 ;; Check if any child is not done.
321 (org-element-map headline 'headline
322 (lambda (hl) (eq (org-element-property :todo-type hl) 'todo))
323 info 'first-match)
324 ;; Check :ORDERED: node property.
325 (catch 'blockedp
326 (let ((current headline))
327 (dolist (parent (org-element-lineage headline))
328 (cond
329 ((not (org-element-property :todo-keyword parent))
330 (throw 'blockedp nil))
331 ((org-not-nil (org-element-property :ORDERED parent))
332 (let ((sibling current))
333 (while (setq sibling (org-export-get-previous-element
334 sibling info))
335 (when (eq (org-element-property :todo-type sibling) 'todo)
336 (throw 'blockedp t)))))
337 (t (setq current parent))))))))
339 (defun org-icalendar-use-UTC-date-time-p ()
340 "Non-nil when `org-icalendar-date-time-format' requires UTC time."
341 (char-equal (elt org-icalendar-date-time-format
342 (1- (length org-icalendar-date-time-format))) ?Z))
344 (defvar org-agenda-default-appointment-duration) ; From org-agenda.el.
345 (defun org-icalendar-convert-timestamp (timestamp keyword &optional end utc)
346 "Convert TIMESTAMP to iCalendar format.
348 TIMESTAMP is a timestamp object. KEYWORD is added in front of
349 it, in order to make a complete line (e.g. \"DTSTART\").
351 When optional argument END is non-nil, use end of time range.
352 Also increase the hour by two (if time string contains a time),
353 or the day by one (if it does not contain a time) when no
354 explicit ending time is specified.
356 When optional argument UTC is non-nil, time will be expressed in
357 Universal Time, ignoring `org-icalendar-date-time-format'."
358 (let* ((year-start (org-element-property :year-start timestamp))
359 (year-end (org-element-property :year-end timestamp))
360 (month-start (org-element-property :month-start timestamp))
361 (month-end (org-element-property :month-end timestamp))
362 (day-start (org-element-property :day-start timestamp))
363 (day-end (org-element-property :day-end timestamp))
364 (hour-start (org-element-property :hour-start timestamp))
365 (hour-end (org-element-property :hour-end timestamp))
366 (minute-start (org-element-property :minute-start timestamp))
367 (minute-end (org-element-property :minute-end timestamp))
368 (with-time-p minute-start)
369 (equal-bounds-p
370 (equal (list year-start month-start day-start hour-start minute-start)
371 (list year-end month-end day-end hour-end minute-end)))
372 (mi (cond ((not with-time-p) 0)
373 ((not end) minute-start)
374 ((and org-agenda-default-appointment-duration equal-bounds-p)
375 (+ minute-end org-agenda-default-appointment-duration))
376 (t minute-end)))
377 (h (cond ((not with-time-p) 0)
378 ((not end) hour-start)
379 ((or (not equal-bounds-p)
380 org-agenda-default-appointment-duration)
381 hour-end)
382 (t (+ hour-end 2))))
383 (d (cond ((not end) day-start)
384 ((not with-time-p) (1+ day-end))
385 (t day-end)))
386 (m (if end month-end month-start))
387 (y (if end year-end year-start)))
388 (concat
389 keyword
390 (format-time-string
391 (cond (utc ":%Y%m%dT%H%M%SZ")
392 ((not with-time-p) ";VALUE=DATE:%Y%m%d")
393 (t (replace-regexp-in-string "%Z"
394 org-icalendar-timezone
395 org-icalendar-date-time-format
396 t)))
397 ;; Convert timestamp into internal time in order to use
398 ;; `format-time-string' and fix any mistake (i.e. MI >= 60).
399 (encode-time 0 mi h d m y)
400 (or utc (and with-time-p (org-icalendar-use-UTC-date-time-p)))))))
402 (defun org-icalendar-dtstamp ()
403 "Return DTSTAMP property, as a string."
404 (format-time-string "DTSTAMP:%Y%m%dT%H%M%SZ" nil t))
406 (defun org-icalendar-get-categories (entry info)
407 "Return categories according to `org-icalendar-categories'.
408 ENTRY is a headline or an inlinetask element. INFO is a plist
409 used as a communication channel."
410 (mapconcat
411 #'identity
412 (org-uniquify
413 (let (categories)
414 (dolist (type org-icalendar-categories (nreverse categories))
415 (case type
416 (category
417 (push (org-export-get-category entry info) categories))
418 (todo-state
419 (let ((todo (org-element-property :todo-keyword entry)))
420 (and todo (push todo categories))))
421 (local-tags
422 (setq categories
423 (append (nreverse (org-export-get-tags entry info))
424 categories)))
425 (all-tags
426 (setq categories
427 (append (nreverse (org-export-get-tags entry info nil t))
428 categories)))))))
429 ","))
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 (let ((todo-type (org-element-property :todo-type entry))
527 (uid (or (org-element-property :ID entry) (org-id-new)))
528 (summary (org-icalendar-cleanup-string
529 (or (org-element-property :SUMMARY entry)
530 (org-export-data
531 (org-element-property :title entry) info))))
532 (loc (org-icalendar-cleanup-string
533 (org-element-property :LOCATION entry)))
534 ;; Build description of the entry from associated section
535 ;; (headline) or contents (inlinetask).
536 (desc
537 (org-icalendar-cleanup-string
538 (or (org-element-property :DESCRIPTION entry)
539 (let ((contents (org-export-data inside info)))
540 (cond
541 ((not (org-string-nw-p contents)) nil)
542 ((wholenump org-icalendar-include-body)
543 (let ((contents (org-trim contents)))
544 (substring
545 contents 0 (min (length contents)
546 org-icalendar-include-body))))
547 (org-icalendar-include-body (org-trim contents)))))))
548 (cat (org-icalendar-get-categories entry info)))
549 (concat
550 ;; Events: Delegate to `org-icalendar--vevent' to generate
551 ;; "VEVENT" component from scheduled, deadline, or any
552 ;; timestamp in the entry.
553 (let ((deadline (org-element-property :deadline entry)))
554 (and deadline
555 (memq (if todo-type 'event-if-todo 'event-if-not-todo)
556 org-icalendar-use-deadline)
557 (org-icalendar--vevent
558 entry deadline (concat "DL-" uid)
559 (concat "DL: " summary) loc desc cat)))
560 (let ((scheduled (org-element-property :scheduled entry)))
561 (and scheduled
562 (memq (if todo-type 'event-if-todo 'event-if-not-todo)
563 org-icalendar-use-scheduled)
564 (org-icalendar--vevent
565 entry scheduled (concat "SC-" uid)
566 (concat "S: " summary) loc desc cat)))
567 ;; When collecting plain timestamps from a headline and its
568 ;; title, skip inlinetasks since collection will happen once
569 ;; ENTRY is one of them.
570 (let ((counter 0))
571 (mapconcat
572 #'identity
573 (org-element-map (cons (org-element-property :title entry)
574 (org-element-contents inside))
575 'timestamp
576 (lambda (ts)
577 (when (let ((type (org-element-property :type ts)))
578 (case (plist-get info :with-timestamps)
579 (active (memq type '(active active-range)))
580 (inactive (memq type '(inactive inactive-range)))
581 ((t) t)))
582 (let ((uid (format "TS%d-%s" (incf counter) uid)))
583 (org-icalendar--vevent
584 entry ts uid summary loc desc cat))))
585 info nil (and (eq type 'headline) 'inlinetask))
586 ""))
587 ;; Task: First check if it is appropriate to export it. If
588 ;; so, call `org-icalendar--vtodo' to transcode it into
589 ;; a "VTODO" component.
590 (when (and todo-type
591 (case (plist-get info :icalendar-include-todo)
592 (all t)
593 (unblocked
594 (and (eq type 'headline)
595 (not (org-icalendar-blocked-headline-p
596 entry info))))
597 ((t) (eq todo-type 'todo))))
598 (org-icalendar--vtodo entry uid summary loc desc cat))
599 ;; Diary-sexp: Collect every diary-sexp element within ENTRY
600 ;; and its title, and transcode them. If ENTRY is
601 ;; a headline, skip inlinetasks: they will be handled
602 ;; separately.
603 (when org-icalendar-include-sexps
604 (let ((counter 0))
605 (mapconcat #'identity
606 (org-element-map
607 (cons (org-element-property :title entry)
608 (org-element-contents inside))
609 'diary-sexp
610 (lambda (sexp)
611 (org-icalendar-transcode-diary-sexp
612 (org-element-property :value sexp)
613 (format "DS%d-%s" (incf counter) uid)
614 summary))
615 info nil (and (eq type 'headline) 'inlinetask))
616 "")))))
617 ;; If ENTRY is a headline, call current function on every
618 ;; inlinetask within it. In agenda export, this is independent
619 ;; from the mark (or lack thereof) on the entry.
620 (when (eq type 'headline)
621 (mapconcat #'identity
622 (org-element-map inside 'inlinetask
623 (lambda (task) (org-icalendar-entry task nil info))
624 info) ""))
625 ;; Don't forget components from inner entries.
626 contents))))
628 (defun org-icalendar--vevent
629 (entry timestamp uid summary location description categories)
630 "Create a VEVENT component.
632 ENTRY is either a headline or an inlinetask element. TIMESTAMP
633 is a timestamp object defining the date-time of the event. UID
634 is the unique identifier for the event. SUMMARY defines a short
635 summary or subject for the event. LOCATION defines the intended
636 venue for the event. DESCRIPTION provides the complete
637 description of the event. CATEGORIES defines the categories the
638 event belongs to.
640 Return VEVENT component as a string."
641 (org-icalendar-fold-string
642 (if (eq (org-element-property :type timestamp) 'diary)
643 (org-icalendar-transcode-diary-sexp
644 (org-element-property :raw-value timestamp) uid summary)
645 (concat "BEGIN:VEVENT\n"
646 (org-icalendar-dtstamp) "\n"
647 "UID:" uid "\n"
648 (org-icalendar-convert-timestamp timestamp "DTSTART") "\n"
649 (org-icalendar-convert-timestamp timestamp "DTEND" t) "\n"
650 ;; RRULE.
651 (when (org-element-property :repeater-type timestamp)
652 (format "RRULE:FREQ=%s;INTERVAL=%d\n"
653 (case (org-element-property :repeater-unit timestamp)
654 (hour "HOURLY") (day "DAILY") (week "WEEKLY")
655 (month "MONTHLY") (year "YEARLY"))
656 (org-element-property :repeater-value timestamp)))
657 "SUMMARY:" summary "\n"
658 (and (org-string-nw-p location) (format "LOCATION:%s\n" location))
659 (and (org-string-nw-p description)
660 (format "DESCRIPTION:%s\n" description))
661 "CATEGORIES:" categories "\n"
662 ;; VALARM.
663 (org-icalendar--valarm entry timestamp summary)
664 "END:VEVENT"))))
666 (defun org-icalendar--vtodo
667 (entry uid summary location description categories)
668 "Create a VTODO component.
670 ENTRY is either a headline or an inlinetask element. UID is the
671 unique identifier for the task. SUMMARY defines a short summary
672 or subject for the task. LOCATION defines the intended venue for
673 the task. DESCRIPTION provides the complete description of the
674 task. CATEGORIES defines the categories the task belongs to.
676 Return VTODO component as a string."
677 (let ((start (or (and (memq 'todo-start org-icalendar-use-scheduled)
678 (org-element-property :scheduled entry))
679 ;; If we can't use a scheduled time for some
680 ;; reason, start task now.
681 (let ((now (decode-time)))
682 (list 'timestamp
683 (list :type 'active
684 :minute-start (nth 1 now)
685 :hour-start (nth 2 now)
686 :day-start (nth 3 now)
687 :month-start (nth 4 now)
688 :year-start (nth 5 now)))))))
689 (org-icalendar-fold-string
690 (concat "BEGIN:VTODO\n"
691 "UID:TODO-" uid "\n"
692 (org-icalendar-dtstamp) "\n"
693 (org-icalendar-convert-timestamp start "DTSTART") "\n"
694 (and (memq 'todo-due org-icalendar-use-deadline)
695 (org-element-property :deadline entry)
696 (concat (org-icalendar-convert-timestamp
697 (org-element-property :deadline entry) "DUE")
698 "\n"))
699 "SUMMARY:" summary "\n"
700 (and (org-string-nw-p location) (format "LOCATION:%s\n" location))
701 (and (org-string-nw-p description)
702 (format "DESCRIPTION:%s\n" description))
703 "CATEGORIES:" categories "\n"
704 "SEQUENCE:1\n"
705 (format "PRIORITY:%d\n"
706 (let ((pri (or (org-element-property :priority entry)
707 org-default-priority)))
708 (floor (- 9 (* 8. (/ (float (- org-lowest-priority pri))
709 (- org-lowest-priority
710 org-highest-priority)))))))
711 (format "STATUS:%s\n"
712 (if (eq (org-element-property :todo-type entry) 'todo)
713 "NEEDS-ACTION"
714 "COMPLETED"))
715 "END:VTODO"))))
717 (defun org-icalendar--valarm (entry timestamp summary)
718 "Create a VALARM component.
720 ENTRY is the calendar entry triggering the alarm. TIMESTAMP is
721 the start date-time of the entry. SUMMARY defines a short
722 summary or subject for the task.
724 Return VALARM component as a string, or nil if it isn't allowed."
725 ;; Create a VALARM entry if the entry is timed. This is not very
726 ;; general in that:
727 ;; (a) only one alarm per entry is defined,
728 ;; (b) only minutes are allowed for the trigger period ahead of the
729 ;; start time,
730 ;; (c) only a DISPLAY action is defined. [ESF]
731 (let ((alarm-time
732 (let ((warntime
733 (org-element-property :APPT_WARNTIME entry)))
734 (if warntime (string-to-number warntime) 0))))
735 (and (or (> alarm-time 0) (> org-icalendar-alarm-time 0))
736 (org-element-property :hour-start timestamp)
737 (format "BEGIN:VALARM
738 ACTION:DISPLAY
739 DESCRIPTION:%s
740 TRIGGER:-P0DT0H%dM0S
741 END:VALARM\n"
742 summary
743 (if (zerop alarm-time) org-icalendar-alarm-time alarm-time)))))
746 ;;;; Template
748 (defun org-icalendar-template (contents info)
749 "Return complete document string after iCalendar conversion.
750 CONTENTS is the transcoded contents string. INFO is a plist used
751 as a communication channel."
752 (org-icalendar--vcalendar
753 ;; Name.
754 (if (not (plist-get info :input-file)) (buffer-name (buffer-base-buffer))
755 (file-name-nondirectory
756 (file-name-sans-extension (plist-get info :input-file))))
757 ;; Owner.
758 (if (not (plist-get info :with-author)) ""
759 (org-export-data (plist-get info :author) info))
760 ;; Timezone.
761 (if (org-string-nw-p org-icalendar-timezone) org-icalendar-timezone
762 (cadr (current-time-zone)))
763 ;; Description.
764 (org-export-data (plist-get info :title) info)
765 contents))
767 (defun org-icalendar--vcalendar (name owner tz description contents)
768 "Create a VCALENDAR component.
769 NAME, OWNER, TZ, DESCRIPTION and CONTENTS are all strings giving,
770 respectively, the name of the calendar, its owner, the timezone
771 used, a short description and the other components included."
772 (concat (format "BEGIN:VCALENDAR
773 VERSION:2.0
774 X-WR-CALNAME:%s
775 PRODID:-//%s//Emacs with Org mode//EN
776 X-WR-TIMEZONE:%s
777 X-WR-CALDESC:%s
778 CALSCALE:GREGORIAN\n"
779 (org-icalendar-cleanup-string name)
780 (org-icalendar-cleanup-string owner)
781 (org-icalendar-cleanup-string tz)
782 (org-icalendar-cleanup-string description))
783 contents
784 "END:VCALENDAR\n"))
788 ;;; Interactive Functions
790 ;;;###autoload
791 (defun org-icalendar-export-to-ics
792 (&optional async subtreep visible-only body-only)
793 "Export current buffer to an iCalendar file.
795 If narrowing is active in the current buffer, only export its
796 narrowed part.
798 If a region is active, export that region.
800 A non-nil optional argument ASYNC means the process should happen
801 asynchronously. The resulting file should be accessible through
802 the `org-export-stack' interface.
804 When optional argument SUBTREEP is non-nil, export the sub-tree
805 at point, extracting information from the headline properties
806 first.
808 When optional argument VISIBLE-ONLY is non-nil, don't export
809 contents of hidden elements.
811 When optional argument BODY-ONLY is non-nil, only write code
812 between \"BEGIN:VCALENDAR\" and \"END:VCALENDAR\".
814 Return ICS file name."
815 (interactive)
816 (let ((file (buffer-file-name (buffer-base-buffer))))
817 (when (and file org-icalendar-store-UID)
818 (org-icalendar-create-uid file 'warn-user)))
819 ;; Export part. Since this back-end is backed up by `ascii', ensure
820 ;; links will not be collected at the end of sections.
821 (let ((outfile (org-export-output-file-name ".ics" subtreep)))
822 (org-export-to-file 'icalendar outfile
823 async subtreep visible-only body-only
824 '(:ascii-charset utf-8 :ascii-links-to-notes nil)
825 (lambda (file)
826 (run-hook-with-args 'org-icalendar-after-save-hook file) nil))))
828 ;;;###autoload
829 (defun org-icalendar-export-agenda-files (&optional async)
830 "Export all agenda files to iCalendar files.
831 When optional argument ASYNC is non-nil, export happens in an
832 external process."
833 (interactive)
834 (if async
835 ;; Asynchronous export is not interactive, so we will not call
836 ;; `org-check-agenda-file'. Instead we remove any non-existent
837 ;; agenda file from the list.
838 (let ((files (cl-remove-if-not #'file-exists-p (org-agenda-files t))))
839 (org-export-async-start
840 (lambda (results)
841 (dolist (f results) (org-export-add-to-stack f 'icalendar)))
842 `(let (output-files)
843 (dolist (file ',files outputfiles)
844 (with-current-buffer (org-get-agenda-file-buffer file)
845 (push (expand-file-name (org-icalendar-export-to-ics))
846 output-files))))))
847 (let ((files (org-agenda-files t)))
848 (org-agenda-prepare-buffers files)
849 (unwind-protect
850 (dolist (file files)
851 (catch 'nextfile
852 (org-check-agenda-file file)
853 (with-current-buffer (org-get-agenda-file-buffer file)
854 (org-icalendar-export-to-ics))))
855 (org-release-buffers org-agenda-new-buffers)))))
857 ;;;###autoload
858 (defun org-icalendar-combine-agenda-files (&optional async)
859 "Combine all agenda files into a single iCalendar file.
861 A non-nil optional argument ASYNC means the process should happen
862 asynchronously. The resulting file should be accessible through
863 the `org-export-stack' interface.
865 The file is stored under the name chosen in
866 `org-icalendar-combined-agenda-file'."
867 (interactive)
868 (if async
869 (let ((files (cl-remove-if-not #'file-exists-p (org-agenda-files t))))
870 (org-export-async-start
871 (lambda (_)
872 (org-export-add-to-stack
873 (expand-file-name org-icalendar-combined-agenda-file)
874 'icalendar))
875 `(apply #'org-icalendar--combine-files ',files)))
876 (apply #'org-icalendar--combine-files (org-agenda-files t))))
878 (defun org-icalendar-export-current-agenda (file)
879 "Export current agenda view to an iCalendar FILE.
880 This function assumes major mode for current buffer is
881 `org-agenda-mode'."
882 (let* ((org-export-babel-evaluate) ; Don't evaluate Babel block.
883 (contents
884 (org-export-string-as
885 (with-output-to-string
886 (save-excursion
887 (let ((p (point-min)))
888 (while (setq p (next-single-property-change p 'org-hd-marker))
889 (let ((m (get-text-property p 'org-hd-marker)))
890 (when m
891 (with-current-buffer (marker-buffer m)
892 (org-with-wide-buffer
893 (goto-char (marker-position m))
894 (princ
895 (org-element-normalize-string
896 (buffer-substring
897 (point) (progn (outline-next-heading) (point)))))))))
898 (forward-line)))))
899 'icalendar t
900 '(:ascii-charset utf-8 :ascii-links-to-notes nil
901 :icalendar-include-todo all))))
902 (with-temp-file file
903 (insert
904 (org-icalendar--vcalendar
905 org-icalendar-combined-name
906 user-full-name
907 org-icalendar-combined-description
908 (or (org-string-nw-p org-icalendar-timezone) (cadr (current-time-zone)))
909 contents)))
910 (run-hook-with-args 'org-icalendar-after-save-hook file)))
912 (defun org-icalendar--combine-files (&rest files)
913 "Combine entries from multiple files into an iCalendar file.
914 FILES is a list of files to build the calendar from."
915 (org-agenda-prepare-buffers files)
916 (unwind-protect
917 (progn
918 (with-temp-file org-icalendar-combined-agenda-file
919 (insert
920 (org-icalendar--vcalendar
921 ;; Name.
922 org-icalendar-combined-name
923 ;; Owner.
924 user-full-name
925 ;; Timezone.
926 (or (org-string-nw-p org-icalendar-timezone)
927 (cadr (current-time-zone)))
928 ;; Description.
929 org-icalendar-combined-description
930 ;; Contents.
931 (concat
932 ;; Agenda contents.
933 (mapconcat
934 (lambda (file)
935 (catch 'nextfile
936 (org-check-agenda-file file)
937 (with-current-buffer (org-get-agenda-file-buffer file)
938 ;; Create ID if necessary.
939 (when org-icalendar-store-UID
940 (org-icalendar-create-uid file t))
941 (org-export-as
942 'icalendar nil nil t
943 '(:ascii-charset utf-8 :ascii-links-to-notes nil)))))
944 files "")
945 ;; BBDB anniversaries.
946 (when (and org-icalendar-include-bbdb-anniversaries
947 (require 'org-bbdb nil t))
948 (with-output-to-string (org-bbdb-anniv-export-ical)))))))
949 (run-hook-with-args 'org-icalendar-after-save-hook
950 org-icalendar-combined-agenda-file))
951 (org-release-buffers org-agenda-new-buffers)))
954 (provide 'ox-icalendar)
956 ;; Local variables:
957 ;; generated-autoload-file: "org-loaddefs.el"
958 ;; End:
960 ;;; ox-icalendar.el ends here