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