ox-ascii: Fix indentation in the first paragraph of a section
[org-mode.git] / lisp / ox-icalendar.el
blobcd48bbf9aef9d9df2fa1bd16dba5756d16f70fe0
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 several symbols in it. Valid symbol are:
89 `event-if-todo' Deadlines in TODO entries become calendar events.
90 `event-if-not-todo' Deadlines in non-TODO entries become calendar events.
91 `todo-due' Use deadlines in TODO entries as due-dates"
92 :group 'org-export-icalendar
93 :type '(set :greedy t
94 (const :tag "Deadlines in non-TODO entries become events"
95 event-if-not-todo)
96 (const :tag "Deadline in TODO entries become events"
97 event-if-todo)
98 (const :tag "Deadlines in TODO entries become due-dates"
99 todo-due)))
101 (defcustom org-icalendar-use-scheduled '(todo-start)
102 "Contexts where iCalendar export should use a scheduling time stamp.
104 This is a list with several symbols in it. Valid symbol are:
105 `event-if-todo' Scheduling time stamps in TODO entries become an event.
106 `event-if-not-todo' Scheduling time stamps in non-TODO entries become an event.
107 `todo-start' Scheduling time stamps in TODO entries become start date.
108 Some calendar applications show TODO entries only after
109 that date."
110 :group 'org-export-icalendar
111 :type '(set :greedy t
112 (const :tag
113 "SCHEDULED timestamps in non-TODO entries become events"
114 event-if-not-todo)
115 (const :tag "SCHEDULED timestamps in TODO entries become events"
116 event-if-todo)
117 (const :tag "SCHEDULED in TODO entries become start date"
118 todo-start)))
120 (defcustom org-icalendar-categories '(local-tags category)
121 "Items that should be entered into the \"categories\" field.
123 This is a list of symbols, the following are valid:
124 `category' The Org mode category of the current file or tree
125 `todo-state' The todo state, if any
126 `local-tags' The tags, defined in the current line
127 `all-tags' All tags, including inherited ones."
128 :group 'org-export-icalendar
129 :type '(repeat
130 (choice
131 (const :tag "The file or tree category" category)
132 (const :tag "The TODO state" todo-state)
133 (const :tag "Tags defined in current line" local-tags)
134 (const :tag "All tags, including inherited ones" all-tags))))
136 (defcustom org-icalendar-with-timestamps 'active
137 "Non-nil means make an event from plain time stamps.
139 It can be set to `active', `inactive', t or nil, in order to make
140 an event from, respectively, only active timestamps, only
141 inactive ones, all of them or none.
143 This variable has precedence over `org-export-with-timestamps'.
144 It can also be set with the #+OPTIONS line, e.g. \"<:t\"."
145 :group 'org-export-icalendar
146 :type '(choice
147 (const :tag "All timestamps" t)
148 (const :tag "Only active timestamps" active)
149 (const :tag "Only inactive timestamps" inactive)
150 (const :tag "No timestamp" nil)))
152 (defcustom org-icalendar-include-todo nil
153 "Non-nil means create VTODO components from TODO items.
155 Valid values are:
156 nil don't include any task.
157 t include tasks that are not in DONE state.
158 `unblocked' include all TODO items that are not blocked.
159 `all' include both done and not done items."
160 :group 'org-export-icalendar
161 :type '(choice
162 (const :tag "None" nil)
163 (const :tag "Unfinished" t)
164 (const :tag "Unblocked" unblocked)
165 (const :tag "All" all)
166 (repeat :tag "Specific TODO keywords"
167 (string :tag "Keyword"))))
169 (defcustom org-icalendar-include-bbdb-anniversaries nil
170 "Non-nil means a combined iCalendar file should include anniversaries.
171 The anniversaries are defined in the BBDB database."
172 :group 'org-export-icalendar
173 :type 'boolean)
175 (defcustom org-icalendar-include-sexps t
176 "Non-nil means export to iCalendar files should also cover sexp entries.
177 These are entries like in the diary, but directly in an Org file."
178 :group 'org-export-icalendar
179 :type 'boolean)
181 (defcustom org-icalendar-include-body t
182 "Amount of text below headline to be included in iCalendar export.
183 This is a number of characters that should maximally be included.
184 Properties, scheduling and clocking lines will always be removed.
185 The text will be inserted into the DESCRIPTION field."
186 :group 'org-export-icalendar
187 :type '(choice
188 (const :tag "Nothing" nil)
189 (const :tag "Everything" t)
190 (integer :tag "Max characters")))
192 (defcustom org-icalendar-store-UID nil
193 "Non-nil means store any created UIDs in properties.
195 The iCalendar standard requires that all entries have a unique identifier.
196 Org will create these identifiers as needed. When this variable is non-nil,
197 the created UIDs will be stored in the ID property of the entry. Then the
198 next time this entry is exported, it will be exported with the same UID,
199 superseding the previous form of it. This is essential for
200 synchronization services.
202 This variable is not turned on by default because we want to avoid creating
203 a property drawer in every entry if people are only playing with this feature,
204 or if they are only using it locally."
205 :group 'org-export-icalendar
206 :type 'boolean)
208 (defcustom org-icalendar-timezone (getenv "TZ")
209 "The time zone string for iCalendar export.
210 When nil or the empty string, use output
211 from (current-time-zone)."
212 :group 'org-export-icalendar
213 :type '(choice
214 (const :tag "Unspecified" nil)
215 (string :tag "Time zone")))
217 (defcustom org-icalendar-date-time-format ":%Y%m%dT%H%M%S"
218 "Format-string for exporting icalendar DATE-TIME.
220 See `format-time-string' for a full documentation. The only
221 difference is that `org-icalendar-timezone' is used for %Z.
223 Interesting value are:
224 - \":%Y%m%dT%H%M%S\" for local time
225 - \";TZID=%Z:%Y%m%dT%H%M%S\" for local time with explicit timezone
226 - \":%Y%m%dT%H%M%SZ\" for time expressed in Universal Time"
227 :group 'org-export-icalendar
228 :version "24.1"
229 :type '(choice
230 (const :tag "Local time" ":%Y%m%dT%H%M%S")
231 (const :tag "Explicit local time" ";TZID=%Z:%Y%m%dT%H%M%S")
232 (const :tag "Universal time" ":%Y%m%dT%H%M%SZ")
233 (string :tag "Explicit format")))
235 (defvar org-icalendar-after-save-hook nil
236 "Hook run after an iCalendar file has been saved.
237 This hook is run with the name of the file as argument. A good
238 way to use this is to tell a desktop calendar application to
239 re-read the iCalendar file.")
243 ;;; Define Back-End
245 (org-export-define-derived-backend 'icalendar 'ascii
246 :translate-alist '((clock . ignore)
247 (footnote-definition . ignore)
248 (footnote-reference . ignore)
249 (headline . org-icalendar-entry)
250 (inlinetask . ignore)
251 (planning . ignore)
252 (section . ignore)
253 (inner-template . (lambda (c i) c))
254 (template . org-icalendar-template))
255 :options-alist
256 '((:exclude-tags
257 "ICALENDAR_EXCLUDE_TAGS" nil org-icalendar-exclude-tags split)
258 (:with-timestamps nil "<" org-icalendar-with-timestamps)
259 (:with-vtodo nil nil org-icalendar-include-todo)
260 ;; The following property will be non-nil when export has been
261 ;; started from org-agenda-mode. In this case, any entry without
262 ;; a non-nil "ICALENDAR_MARK" property will be ignored.
263 (:icalendar-agenda-view nil nil nil))
264 :filters-alist
265 '((:filter-headline . org-icalendar-clear-blank-lines))
266 :menu-entry
267 '(?c "Export to iCalendar"
268 ((?f "Current file" org-icalendar-export-to-ics)
269 (?a "All agenda files"
270 (lambda (a s v b) (org-icalendar-export-agenda-files a)))
271 (?c "Combine all agenda files"
272 (lambda (a s v b) (org-icalendar-combine-agenda-files a))))))
276 ;;; Internal Functions
278 (defun org-icalendar-create-uid (file &optional bell h-markers)
279 "Set ID property on headlines missing it in FILE.
280 When optional argument BELL is non-nil, inform the user with
281 a message if the file was modified. With optional argument
282 H-MARKERS non-nil, it is a list of markers for the headlines
283 which will be updated."
284 (let ((pt (if h-markers (goto-char (car h-markers)) (point-min)))
285 modified-flag)
286 (org-map-entries
287 (lambda ()
288 (let ((entry (org-element-at-point)))
289 (unless (or (< (point) pt) (org-element-property :ID entry))
290 (org-id-get-create)
291 (setq modified-flag t)
292 (forward-line))
293 (when h-markers (setq org-map-continue-from (pop h-markers)))))
294 nil nil 'comment)
295 (when (and bell modified-flag)
296 (message "ID properties created in file \"%s\"" file)
297 (sit-for 2))))
299 (defun org-icalendar-blocked-headline-p (headline info)
300 "Non-nil when HEADLINE is considered to be blocked.
302 INFO is a plist used as a communication channel.
304 A headline is blocked when either
306 - it has children which are not all in a completed state;
308 - it has a parent with the property :ORDERED:, and there are
309 siblings prior to it with incomplete status;
311 - its parent is blocked because it has siblings that should be
312 done first or is a child of a blocked grandparent entry."
314 ;; Check if any child is not done.
315 (org-element-map headline 'headline
316 (lambda (hl) (eq (org-element-property :todo-type hl) 'todo))
317 info 'first-match)
318 ;; Check :ORDERED: node property.
319 (catch 'blockedp
320 (let ((current headline))
321 (mapc (lambda (parent)
322 (cond
323 ((not (org-element-property :todo-keyword parent))
324 (throw 'blockedp nil))
325 ((org-not-nil (org-element-property :ORDERED parent))
326 (let ((sibling current))
327 (while (setq sibling (org-export-get-previous-element
328 sibling info))
329 (when (eq (org-element-property :todo-type sibling) 'todo)
330 (throw 'blockedp t)))))
331 (t (setq current parent))))
332 (org-export-get-genealogy headline))
333 nil))))
335 (defun org-icalendar-use-UTC-date-time-p ()
336 "Non-nil when `org-icalendar-date-time-format' requires UTC time."
337 (char-equal (elt org-icalendar-date-time-format
338 (1- (length org-icalendar-date-time-format))) ?Z))
340 (defvar org-agenda-default-appointment-duration) ; From org-agenda.el.
341 (defun org-icalendar-convert-timestamp (timestamp keyword &optional end utc)
342 "Convert TIMESTAMP to iCalendar format.
344 TIMESTAMP is a timestamp object. KEYWORD is added in front of
345 it, in order to make a complete line (e.g. \"DTSTART\").
347 When optional argument END is non-nil, use end of time range.
348 Also increase the hour by two (if time string contains a time),
349 or the day by one (if it does not contain a time) when no
350 explicit ending time is specified.
352 When optional argument UTC is non-nil, time will be expressed in
353 Universal Time, ignoring `org-icalendar-date-time-format'."
354 (let* ((year-start (org-element-property :year-start timestamp))
355 (year-end (org-element-property :year-end timestamp))
356 (month-start (org-element-property :month-start timestamp))
357 (month-end (org-element-property :month-end timestamp))
358 (day-start (org-element-property :day-start timestamp))
359 (day-end (org-element-property :day-end timestamp))
360 (hour-start (org-element-property :hour-start timestamp))
361 (hour-end (org-element-property :hour-end timestamp))
362 (minute-start (org-element-property :minute-start timestamp))
363 (minute-end (org-element-property :minute-end timestamp))
364 (with-time-p minute-start)
365 (equal-bounds-p
366 (equal (list year-start month-start day-start hour-start minute-start)
367 (list year-end month-end day-end hour-end minute-end)))
368 (mi (cond ((not with-time-p) 0)
369 ((not end) minute-start)
370 ((and org-agenda-default-appointment-duration equal-bounds-p)
371 (+ minute-end org-agenda-default-appointment-duration))
372 (t minute-end)))
373 (h (cond ((not with-time-p) 0)
374 ((not end) hour-start)
375 ((or (not equal-bounds-p)
376 org-agenda-default-appointment-duration)
377 hour-end)
378 (t (+ hour-end 2))))
379 (d (cond ((not end) day-start)
380 ((not with-time-p) (1+ day-end))
381 (t day-end)))
382 (m (if end month-end month-start))
383 (y (if end year-end year-start)))
384 (concat
385 keyword
386 (format-time-string
387 (cond (utc ":%Y%m%dT%H%M%SZ")
388 ((not with-time-p) ";VALUE=DATE:%Y%m%d")
389 (t (replace-regexp-in-string "%Z"
390 org-icalendar-timezone
391 org-icalendar-date-time-format
392 t)))
393 ;; Convert timestamp into internal time in order to use
394 ;; `format-time-string' and fix any mistake (i.e. MI >= 60).
395 (encode-time 0 mi h d m y)
396 (or utc (and with-time-p (org-icalendar-use-UTC-date-time-p)))))))
398 (defun org-icalendar-dtstamp ()
399 "Return DTSTAMP property, as a string."
400 (format-time-string "DTSTAMP:%Y%m%dT%H%M%SZ" nil t))
402 (defun org-icalendar-get-categories (entry info)
403 "Return categories according to `org-icalendar-categories'.
404 ENTRY is a headline or an inlinetask element. INFO is a plist
405 used as a communication channel."
406 (mapconcat
407 'identity
408 (org-uniquify
409 (let (categories)
410 (mapc (lambda (type)
411 (case type
412 (category
413 (push (org-export-get-category entry info) categories))
414 (todo-state
415 (let ((todo (org-element-property :todo-keyword entry)))
416 (and todo (push todo categories))))
417 (local-tags
418 (setq categories
419 (append (nreverse (org-export-get-tags entry info))
420 categories)))
421 (all-tags
422 (setq categories
423 (append (nreverse (org-export-get-tags entry info nil t))
424 categories)))))
425 org-icalendar-categories)
426 ;; Return list of categories, following specified order.
427 (nreverse categories))) ","))
429 (defun org-icalendar-transcode-diary-sexp (sexp uid summary)
430 "Transcode a diary sexp into iCalendar format.
431 SEXP is the diary sexp being transcoded, as a string. UID is the
432 unique identifier for the entry. SUMMARY defines a short summary
433 or subject for the event."
434 (when (require 'icalendar nil t)
435 (org-element-normalize-string
436 (with-temp-buffer
437 (let ((sexp (if (not (string-match "\\`<%%" sexp)) sexp
438 (concat (substring sexp 1 -1) " " summary))))
439 (put-text-property 0 1 'uid uid sexp)
440 (insert sexp "\n"))
441 (org-diary-to-ical-string (current-buffer))))))
443 (defun org-icalendar-cleanup-string (s)
444 "Cleanup string S according to RFC 5545."
445 (when s
446 ;; Protect "\", "," and ";" characters. and replace newline
447 ;; characters with literal \n.
448 (replace-regexp-in-string
449 "[ \t]*\n" "\\n"
450 (replace-regexp-in-string "[\\,;]" "\\\&" s)
451 nil t)))
453 (defun org-icalendar-fold-string (s)
454 "Fold string S according to RFC 5545."
455 (org-element-normalize-string
456 (mapconcat
457 (lambda (line)
458 ;; Limit each line to a maximum of 75 characters. If it is
459 ;; longer, fold it by using "\n " as a continuation marker.
460 (let ((len (length line)))
461 (if (<= len 75) line
462 (let ((folded-line (substring line 0 75))
463 (chunk-start 75)
464 chunk-end)
465 ;; Since continuation marker takes up one character on the
466 ;; line, real contents must be split at 74 chars.
467 (while (< (setq chunk-end (+ chunk-start 74)) len)
468 (setq folded-line
469 (concat folded-line "\n "
470 (substring line chunk-start chunk-end))
471 chunk-start chunk-end))
472 (concat folded-line "\n " (substring line chunk-start))))))
473 (org-split-string s "\n") "\n")))
477 ;;; Filters
479 (defun org-icalendar-clear-blank-lines (headline back-end info)
480 "Remove blank lines in HEADLINE export.
481 HEADLINE is a string representing a transcoded headline.
482 BACK-END and INFO are ignored."
483 (replace-regexp-in-string "^\\(?:[ \t]*\n\\)+" "" headline))
487 ;;; Transcode Functions
489 ;;;; Headline and Inlinetasks
491 ;; The main function is `org-icalendar-entry', which extracts
492 ;; information from a headline or an inlinetask (summary,
493 ;; description...) and then delegates code generation to
494 ;; `org-icalendar--vtodo' and `org-icalendar--vevent', depending
495 ;; on the component needed.
497 ;; Obviously, `org-icalendar--valarm' handles alarms, which can
498 ;; happen within a VTODO component.
500 (defun org-icalendar-entry (entry contents info)
501 "Transcode ENTRY element into iCalendar format.
503 ENTRY is either a headline or an inlinetask. CONTENTS is
504 ignored. INFO is a plist used as a communication channel.
506 This function is called on every headline, the section below
507 it (minus inlinetasks) being its contents. It tries to create
508 VEVENT and VTODO components out of scheduled date, deadline date,
509 plain timestamps, diary sexps. It also calls itself on every
510 inlinetask within the section."
511 (unless (org-element-property :footnote-section-p entry)
512 (let* ((type (org-element-type entry))
513 ;; Determine contents really associated to the entry. For
514 ;; a headline, limit them to section, if any. For an
515 ;; inlinetask, this is every element within the task.
516 (inside
517 (if (eq type 'inlinetask)
518 (cons 'org-data (cons nil (org-element-contents entry)))
519 (let ((first (car (org-element-contents entry))))
520 (and (eq (org-element-type first) 'section)
521 (cons 'org-data
522 (cons nil (org-element-contents first))))))))
523 (concat
524 (unless (and (plist-get info :icalendar-agenda-view)
525 (not (org-element-property :ICALENDAR-MARK entry)))
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
535 ;; section (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
551 ;; generate "VEVENT" component from scheduled, deadline,
552 ;; or any 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
568 ;; its title, skip inlinetasks since collection will
569 ;; happen once 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.
588 ;; If so, call `org-icalendar--vtodo' to transcode it
589 ;; into a "VTODO" component.
590 (when (and todo-type
591 (case (plist-get info :with-vtodo)
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
600 ;; ENTRY 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 (current-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 '(:ascii-charset utf-8)
824 (lambda (file)
825 (run-hook-with-args 'org-icalendar-after-save-hook file) nil))))
827 ;;;###autoload
828 (defun org-icalendar-export-agenda-files (&optional async)
829 "Export all agenda files to iCalendar files.
830 When optional argument ASYNC is non-nil, export happens in an
831 external process."
832 (interactive)
833 (if async
834 ;; Asynchronous export is not interactive, so we will not call
835 ;; `org-check-agenda-file'. Instead we remove any non-existent
836 ;; agenda file from the list.
837 (let ((files (org-remove-if-not 'file-exists-p (org-agenda-files t))))
838 (org-export-async-start
839 (lambda (results)
840 (mapc (lambda (f) (org-export-add-to-stack f 'icalendar))
841 results))
842 `(let (output-files)
843 (mapc (lambda (file)
844 (with-current-buffer (org-get-agenda-file-buffer file)
845 (push (expand-file-name (org-icalendar-export-to-ics))
846 output-files)))
847 ',files)
848 output-files)))
849 (let ((files (org-agenda-files t)))
850 (org-agenda-prepare-buffers files)
851 (unwind-protect
852 (mapc (lambda (file)
853 (catch 'nextfile
854 (org-check-agenda-file file)
855 (with-current-buffer (org-get-agenda-file-buffer file)
856 (org-icalendar-export-to-ics))))
857 files)
858 (org-release-buffers org-agenda-new-buffers)))))
860 ;;;###autoload
861 (defun org-icalendar-combine-agenda-files (&optional async)
862 "Combine all agenda files into a single iCalendar file.
864 A non-nil optional argument ASYNC means the process should happen
865 asynchronously. The resulting file should be accessible through
866 the `org-export-stack' interface.
868 The file is stored under the name chosen in
869 `org-icalendar-combined-agenda-file'."
870 (interactive)
871 (if async
872 (let ((files (org-remove-if-not 'file-exists-p (org-agenda-files t))))
873 (org-export-async-start
874 (lambda (dummy)
875 (org-export-add-to-stack
876 (expand-file-name org-icalendar-combined-agenda-file)
877 'icalendar))
878 `(apply 'org-icalendar--combine-files nil ',files)))
879 (apply 'org-icalendar--combine-files nil (org-agenda-files t))))
881 (defun org-icalendar-export-current-agenda (file)
882 "Export current agenda view to an iCalendar FILE.
883 This function assumes major mode for current buffer is
884 `org-agenda-mode'."
885 (let (org-export-babel-evaluate ; Don't evaluate Babel block
886 (org-icalendar-combined-agenda-file file)
887 (marker-list
888 ;; Collect the markers pointing to entries in the current
889 ;; agenda buffer.
890 (let (markers)
891 (save-excursion
892 (goto-char (point-min))
893 (while (not (eobp))
894 (let ((m (or (org-get-at-bol 'org-hd-marker)
895 (org-get-at-bol 'org-marker))))
896 (and m (push m markers)))
897 (beginning-of-line 2)))
898 (nreverse markers))))
899 (apply 'org-icalendar--combine-files
900 ;; Build restriction alist.
901 (let (restriction)
902 ;; Sort markers in each association within RESTRICTION.
903 (mapcar (lambda (x) (setcdr x (sort (copy-sequence (cdr x)) '<)) x)
904 (dolist (m marker-list restriction)
905 (let* ((pos (marker-position m))
906 (file (buffer-file-name
907 (org-base-buffer (marker-buffer m))))
908 (file-markers (assoc file restriction)))
909 ;; Add POS in FILE association if one exists
910 ;; or create a new association for FILE.
911 (if file-markers (push pos (cdr file-markers))
912 (push (list file pos) restriction))))))
913 (org-agenda-files nil 'ifmode))))
915 (defun org-icalendar--combine-files (restriction &rest files)
916 "Combine entries from multiple files into an iCalendar file.
917 RESTRICTION, when non-nil, is an alist where key is a file name
918 and value a list of buffer positions pointing to entries that
919 should appear in the calendar. It only makes sense if the
920 function was called from an agenda buffer. FILES is a list of
921 files to build the calendar from."
922 (org-agenda-prepare-buffers files)
923 (unwind-protect
924 (progn
925 (with-temp-file org-icalendar-combined-agenda-file
926 (insert
927 (org-icalendar--vcalendar
928 ;; Name.
929 org-icalendar-combined-name
930 ;; Owner.
931 user-full-name
932 ;; Timezone.
933 (or (org-string-nw-p org-icalendar-timezone)
934 (cadr (current-time-zone)))
935 ;; Description.
936 org-icalendar-combined-description
937 ;; Contents.
938 (concat
939 ;; Agenda contents.
940 (mapconcat
941 (lambda (file)
942 (catch 'nextfile
943 (org-check-agenda-file file)
944 (with-current-buffer (org-get-agenda-file-buffer file)
945 (let ((marks (cdr (assoc (expand-file-name file)
946 restriction))))
947 ;; Create ID if necessary.
948 (when org-icalendar-store-UID
949 (org-icalendar-create-uid file t marks))
950 (unless (and restriction (not marks))
951 ;; Add a hook adding :ICALENDAR_MARK: property
952 ;; to each entry appearing in agenda view.
953 ;; Use `apply-partially' because the function
954 ;; still has to accept one argument.
955 (let ((org-export-before-processing-hook
956 (cons (apply-partially
957 (lambda (m-list dummy)
958 (mapc (lambda (m)
959 (org-entry-put
960 m "ICALENDAR-MARK" "t"))
961 m-list))
962 (sort marks '>))
963 org-export-before-processing-hook)))
964 (org-export-as
965 'icalendar nil nil t
966 (list :ascii-charset 'utf-8
967 :icalendar-agenda-view restriction))))))))
968 files "")
969 ;; BBDB anniversaries.
970 (when (and org-icalendar-include-bbdb-anniversaries
971 (require 'org-bbdb nil t))
972 (with-output-to-string (org-bbdb-anniv-export-ical)))))))
973 (run-hook-with-args 'org-icalendar-after-save-hook
974 org-icalendar-combined-agenda-file))
975 (org-release-buffers org-agenda-new-buffers)))
978 (provide 'ox-icalendar)
980 ;; Local variables:
981 ;; generated-autoload-file: "org-loaddefs.el"
982 ;; End:
984 ;;; ox-icalendar.el ends here