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