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