Better document LATEX_HEADER_EXTRA keywords
[org-mode.git] / lisp / ox-icalendar.el
blob49299b014ad0bab392911efde55f030075473ee6
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 h-markers)
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. With optional argument
292 H-MARKERS non-nil, it is a list of markers for the headlines
293 which will be updated."
294 (let ((pt (if h-markers (goto-char (car h-markers)) (point-min)))
295 modified-flag)
296 (org-map-entries
297 (lambda ()
298 (let ((entry (org-element-at-point)))
299 (unless (or (< (point) pt) (org-element-property :ID entry))
300 (org-id-get-create)
301 (setq modified-flag t)
302 (forward-line))
303 (when h-markers (setq org-map-continue-from (pop h-markers)))))
304 nil nil 'comment)
305 (when (and bell modified-flag)
306 (message "ID properties created in file \"%s\"" file)
307 (sit-for 2))))
309 (defun org-icalendar-blocked-headline-p (headline info)
310 "Non-nil when HEADLINE is considered to be blocked.
312 INFO is a plist used as a communication channel.
314 a headline is blocked when either:
316 - It has children which are not all in a completed state.
318 - It has a parent with the property :ORDERED:, and there are
319 siblings prior to it with incomplete status.
321 - Its parent is blocked because it has siblings that should be
322 done first or is a child of a blocked grandparent entry."
324 ;; Check if any child is not done.
325 (org-element-map headline 'headline
326 (lambda (hl) (eq (org-element-property :todo-type hl) 'todo))
327 info 'first-match)
328 ;; Check :ORDERED: node property.
329 (catch 'blockedp
330 (let ((current headline))
331 (mapc (lambda (parent)
332 (cond
333 ((not (org-element-property :todo-keyword parent))
334 (throw 'blockedp nil))
335 ((org-not-nil (org-element-property :ORDERED parent))
336 (let ((sibling current))
337 (while (setq sibling (org-export-get-previous-element
338 sibling info))
339 (when (eq (org-element-property :todo-type sibling) 'todo)
340 (throw 'blockedp t)))))
341 (t (setq current parent))))
342 (org-export-get-genealogy headline))
343 nil))))
345 (defun org-icalendar-use-UTC-date-time-p ()
346 "Non-nil when `org-icalendar-date-time-format' requires UTC time."
347 (char-equal (elt org-icalendar-date-time-format
348 (1- (length org-icalendar-date-time-format))) ?Z))
350 (defvar org-agenda-default-appointment-duration) ; From org-agenda.el.
351 (defun org-icalendar-convert-timestamp (timestamp keyword &optional end utc)
352 "Convert TIMESTAMP to iCalendar format.
354 TIMESTAMP is a timestamp object. KEYWORD is added in front of
355 it, in order to make a complete line (e.g. \"DTSTART\").
357 When optional argument END is non-nil, use end of time range.
358 Also increase the hour by two (if time string contains a time),
359 or the day by one (if it does not contain a time) when no
360 explicit ending time is specified.
362 When optional argument UTC is non-nil, time will be expressed in
363 Universal Time, ignoring `org-icalendar-date-time-format'."
364 (let* ((year-start (org-element-property :year-start timestamp))
365 (year-end (org-element-property :year-end timestamp))
366 (month-start (org-element-property :month-start timestamp))
367 (month-end (org-element-property :month-end timestamp))
368 (day-start (org-element-property :day-start timestamp))
369 (day-end (org-element-property :day-end timestamp))
370 (hour-start (org-element-property :hour-start timestamp))
371 (hour-end (org-element-property :hour-end timestamp))
372 (minute-start (org-element-property :minute-start timestamp))
373 (minute-end (org-element-property :minute-end timestamp))
374 (with-time-p minute-start)
375 (equal-bounds-p
376 (equal (list year-start month-start day-start hour-start minute-start)
377 (list year-end month-end day-end hour-end minute-end)))
378 (mi (cond ((not with-time-p) 0)
379 ((not end) minute-start)
380 ((and org-agenda-default-appointment-duration equal-bounds-p)
381 (+ minute-end org-agenda-default-appointment-duration))
382 (t minute-end)))
383 (h (cond ((not with-time-p) 0)
384 ((not end) hour-start)
385 ((or (not equal-bounds-p)
386 org-agenda-default-appointment-duration)
387 hour-end)
388 (t (+ hour-end 2))))
389 (d (cond ((not end) day-start)
390 ((not with-time-p) (1+ day-end))
391 (t day-end)))
392 (m (if end month-end month-start))
393 (y (if end year-end year-start)))
394 (concat
395 keyword
396 (format-time-string
397 (cond (utc ":%Y%m%dT%H%M%SZ")
398 ((not with-time-p) ";VALUE=DATE:%Y%m%d")
399 (t (replace-regexp-in-string "%Z"
400 org-icalendar-timezone
401 org-icalendar-date-time-format
402 t)))
403 ;; Convert timestamp into internal time in order to use
404 ;; `format-time-string' and fix any mistake (i.e. MI >= 60).
405 (encode-time 0 mi h d m y)
406 (or utc (and with-time-p (org-icalendar-use-UTC-date-time-p)))))))
408 (defun org-icalendar-dtstamp ()
409 "Return DTSTAMP property, as a string."
410 (format-time-string "DTSTAMP:%Y%m%dT%H%M%SZ" nil t))
412 (defun org-icalendar-get-categories (entry info)
413 "Return categories according to `org-icalendar-categories'.
414 ENTRY is a headline or an inlinetask element. INFO is a plist
415 used as a communication channel."
416 (mapconcat
417 'identity
418 (org-uniquify
419 (let (categories)
420 (mapc (lambda (type)
421 (case type
422 (category
423 (push (org-export-get-category entry info) categories))
424 (todo-state
425 (let ((todo (org-element-property :todo-keyword entry)))
426 (and todo (push todo categories))))
427 (local-tags
428 (setq categories
429 (append (nreverse (org-export-get-tags entry info))
430 categories)))
431 (all-tags
432 (setq categories
433 (append (nreverse (org-export-get-tags entry info nil t))
434 categories)))))
435 org-icalendar-categories)
436 ;; Return list of categories, following specified order.
437 (nreverse categories))) ","))
439 (defun org-icalendar-transcode-diary-sexp (sexp uid summary)
440 "Transcode a diary sexp into iCalendar format.
441 SEXP is the diary sexp being transcoded, as a string. UID is the
442 unique identifier for the entry. SUMMARY defines a short summary
443 or subject for the event."
444 (when (require 'icalendar nil t)
445 (org-element-normalize-string
446 (with-temp-buffer
447 (let ((sexp (if (not (string-match "\\`<%%" sexp)) sexp
448 (concat (substring sexp 1 -1) " " summary))))
449 (put-text-property 0 1 'uid uid sexp)
450 (insert sexp "\n"))
451 (org-diary-to-ical-string (current-buffer))))))
453 (defun org-icalendar-cleanup-string (s)
454 "Cleanup string S according to RFC 5545."
455 (when s
456 ;; Protect "\", "," and ";" characters. and replace newline
457 ;; characters with literal \n.
458 (replace-regexp-in-string
459 "[ \t]*\n" "\\n"
460 (replace-regexp-in-string "[\\,;]" "\\\&" s)
461 nil t)))
463 (defun org-icalendar-fold-string (s)
464 "Fold string S according to RFC 5545."
465 (org-element-normalize-string
466 (mapconcat
467 (lambda (line)
468 ;; Limit each line to a maximum of 75 characters. If it is
469 ;; longer, fold it by using "\n " as a continuation marker.
470 (let ((len (length line)))
471 (if (<= len 75) line
472 (let ((folded-line (substring line 0 75))
473 (chunk-start 75)
474 chunk-end)
475 ;; Since continuation marker takes up one character on the
476 ;; line, real contents must be split at 74 chars.
477 (while (< (setq chunk-end (+ chunk-start 74)) len)
478 (setq folded-line
479 (concat folded-line "\n "
480 (substring line chunk-start chunk-end))
481 chunk-start chunk-end))
482 (concat folded-line "\n " (substring line chunk-start))))))
483 (org-split-string s "\n") "\n")))
487 ;;; Filters
489 (defun org-icalendar-clear-blank-lines (headline back-end info)
490 "Remove trailing blank lines in HEADLINE export.
491 HEADLINE is a string representing a transcoded headline.
492 BACK-END and INFO are ignored."
493 (replace-regexp-in-string "^\\(?:[ \t]*\n\\)*" "" headline))
497 ;;; Transcode Functions
499 ;;;; Headline and Inlinetasks
501 ;; The main function is `org-icalendar-entry', which extracts
502 ;; information from a headline or an inlinetask (summary,
503 ;; description...) and then delegates code generation to
504 ;; `org-icalendar--vtodo' and `org-icalendar--vevent', depending
505 ;; on the component needed.
507 ;; Obviously, `org-icalendar--valarm' handles alarms, which can
508 ;; happen within a VTODO component.
510 (defun org-icalendar-entry (entry contents info)
511 "Transcode ENTRY element into iCalendar format.
513 ENTRY is either a headline or an inlinetask. CONTENTS is
514 ignored. INFO is a plist used as a communication channel.
516 This function is called on every headline, the section below
517 it (minus inlinetasks) being its contents. It tries to create
518 VEVENT and VTODO components out of scheduled date, deadline date,
519 plain timestamps, diary sexps. It also calls itself on every
520 inlinetask within the section."
521 (unless (org-element-property :footnote-section-p entry)
522 (let* ((type (org-element-type entry))
523 ;; Determine contents really associated to the entry. For
524 ;; a headline, limit them to section, if any. For an
525 ;; inlinetask, this is every element within the task.
526 (inside
527 (if (eq type 'inlinetask)
528 (cons 'org-data (cons nil (org-element-contents entry)))
529 (let ((first (car (org-element-contents entry))))
530 (and (eq (org-element-type first) 'section)
531 (cons 'org-data
532 (cons nil (org-element-contents first))))))))
533 (concat
534 (unless (and (plist-get info :icalendar-agenda-view)
535 (not (org-element-property :ICALENDAR-MARK entry)))
536 (let ((todo-type (org-element-property :todo-type entry))
537 (uid (or (org-element-property :ID entry) (org-id-new)))
538 (summary (org-icalendar-cleanup-string
539 (or (org-element-property :SUMMARY entry)
540 (org-export-data
541 (org-element-property :title entry) info))))
542 (loc (org-icalendar-cleanup-string
543 (org-element-property :LOCATION entry)))
544 ;; Build description of the entry from associated
545 ;; section (headline) or contents (inlinetask).
546 (desc
547 (org-icalendar-cleanup-string
548 (or (org-element-property :DESCRIPTION entry)
549 (let ((contents (org-export-data inside info)))
550 (cond
551 ((not (org-string-nw-p contents)) nil)
552 ((wholenump org-icalendar-include-body)
553 (let ((contents (org-trim contents)))
554 (substring
555 contents 0 (min (length contents)
556 org-icalendar-include-body))))
557 (org-icalendar-include-body (org-trim contents)))))))
558 (cat (org-icalendar-get-categories entry info)))
559 (concat
560 ;; Events: Delegate to `org-icalendar--vevent' to
561 ;; generate "VEVENT" component from scheduled, deadline,
562 ;; or any timestamp in the entry.
563 (let ((deadline (org-element-property :deadline entry)))
564 (and deadline
565 (memq (if todo-type 'event-if-todo 'event-if-not-todo)
566 org-icalendar-use-deadline)
567 (org-icalendar--vevent
568 entry deadline (concat "DL-" uid)
569 (concat "DL: " summary) loc desc cat)))
570 (let ((scheduled (org-element-property :scheduled entry)))
571 (and scheduled
572 (memq (if todo-type 'event-if-todo 'event-if-not-todo)
573 org-icalendar-use-scheduled)
574 (org-icalendar--vevent
575 entry scheduled (concat "SC-" uid)
576 (concat "S: " summary) loc desc cat)))
577 ;; When collecting plain timestamps from a headline and
578 ;; its title, skip inlinetasks since collection will
579 ;; happen once ENTRY is one of them.
580 (let ((counter 0))
581 (mapconcat
582 'identity
583 (org-element-map (cons (org-element-property :title entry)
584 (org-element-contents inside))
585 'timestamp
586 (lambda (ts)
587 (let ((uid (format "TS%d-%s" (incf counter) uid)))
588 (org-icalendar--vevent entry ts uid summary loc desc cat)))
589 info nil (and (eq type 'headline) 'inlinetask))
590 ""))
591 ;; Task: First check if it is appropriate to export it.
592 ;; If so, call `org-icalendar--vtodo' to transcode it
593 ;; into a "VTODO" component.
594 (when (and todo-type
595 (case (plist-get info :with-vtodo)
596 (all t)
597 (unblocked
598 (and (eq type 'headline)
599 (not (org-icalendar-blocked-headline-p
600 entry info))))
601 ('t (eq todo-type 'todo))))
602 (org-icalendar--vtodo entry uid summary loc desc cat))
603 ;; Diary-sexp: Collect every diary-sexp element within
604 ;; ENTRY and its title, and transcode them. If ENTRY is
605 ;; a headline, skip inlinetasks: they will be handled
606 ;; separately.
607 (when org-icalendar-include-sexps
608 (let ((counter 0))
609 (mapconcat 'identity
610 (org-element-map
611 (cons (org-element-property :title entry)
612 (org-element-contents inside))
613 'diary-sexp
614 (lambda (sexp)
615 (org-icalendar-transcode-diary-sexp
616 (org-element-property :value sexp)
617 (format "DS%d-%s" (incf counter) uid)
618 summary))
619 info nil (and (eq type 'headline) 'inlinetask))
620 ""))))))
621 ;; If ENTRY is a headline, call current function on every
622 ;; inlinetask within it. In agenda export, this is independent
623 ;; from the mark (or lack thereof) on the entry.
624 (when (eq type 'headline)
625 (mapconcat 'identity
626 (org-element-map inside 'inlinetask
627 (lambda (task) (org-icalendar-entry task nil info))
628 info) ""))
629 ;; Don't forget components from inner entries.
630 contents))))
632 (defun org-icalendar--vevent
633 (entry timestamp uid summary location description categories)
634 "Create a VEVENT component.
636 ENTRY is either a headline or an inlinetask element. TIMESTAMP
637 is a timestamp object defining the date-time of the event. UID
638 is the unique identifier for the event. SUMMARY defines a short
639 summary or subject for the event. LOCATION defines the intended
640 venue for the event. DESCRIPTION provides the complete
641 description of the event. CATEGORIES defines the categories the
642 event belongs to.
644 Return VEVENT component as a string."
645 (org-icalendar-fold-string
646 (if (eq (org-element-property :type timestamp) 'diary)
647 (org-icalendar-transcode-diary-sexp
648 (org-element-property :raw-value timestamp) uid summary)
649 (concat "BEGIN:VEVENT\n"
650 (org-icalendar-dtstamp) "\n"
651 "UID:" uid "\n"
652 (org-icalendar-convert-timestamp timestamp "DTSTART") "\n"
653 (org-icalendar-convert-timestamp timestamp "DTEND" t) "\n"
654 ;; RRULE.
655 (when (org-element-property :repeater-type timestamp)
656 (format "RRULE:FREQ=%s;INTERVAL=%d\n"
657 (case (org-element-property :repeater-unit timestamp)
658 (hour "HOURLY") (day "DAILY") (week "WEEKLY")
659 (month "MONTHLY") (year "YEARLY"))
660 (org-element-property :repeater-value timestamp)))
661 "SUMMARY:" summary "\n"
662 (and (org-string-nw-p location) (format "LOCATION:%s\n" location))
663 (and (org-string-nw-p description)
664 (format "DESCRIPTION:%s\n" description))
665 "CATEGORIES:" categories "\n"
666 ;; VALARM.
667 (org-icalendar--valarm entry timestamp summary)
668 "END:VEVENT"))))
670 (defun org-icalendar--vtodo
671 (entry uid summary location description categories)
672 "Create a VTODO component.
674 ENTRY is either a headline or an inlinetask element. UID is the
675 unique identifier for the task. SUMMARY defines a short summary
676 or subject for the task. LOCATION defines the intended venue for
677 the task. DESCRIPTION provides the complete description of the
678 task. CATEGORIES defines the categories the task belongs to.
680 Return VTODO component as a string."
681 (let ((start (or (and (memq 'todo-start org-icalendar-use-scheduled)
682 (org-element-property :scheduled entry))
683 ;; If we can't use a scheduled time for some
684 ;; reason, start task now.
685 (let ((now (decode-time (current-time))))
686 (list 'timestamp
687 (list :type 'active
688 :minute-start (nth 1 now)
689 :hour-start (nth 2 now)
690 :day-start (nth 3 now)
691 :month-start (nth 4 now)
692 :year-start (nth 5 now)))))))
693 (org-icalendar-fold-string
694 (concat "BEGIN:VTODO\n"
695 "UID:TODO-" uid "\n"
696 (org-icalendar-dtstamp) "\n"
697 (org-icalendar-convert-timestamp start "DTSTART") "\n"
698 (and (memq 'todo-due org-icalendar-use-deadline)
699 (org-element-property :deadline entry)
700 (concat (org-icalendar-convert-timestamp
701 (org-element-property :deadline entry) "DUE")
702 "\n"))
703 "SUMMARY:" summary "\n"
704 (and (org-string-nw-p location) (format "LOCATION:%s\n" location))
705 (and (org-string-nw-p description)
706 (format "DESCRIPTION:%s\n" description))
707 "CATEGORIES:" categories "\n"
708 "SEQUENCE:1\n"
709 (format "PRIORITY:%d\n"
710 (let ((pri (or (org-element-property :priority entry)
711 org-default-priority)))
712 (floor (- 9 (* 8. (/ (float (- org-lowest-priority pri))
713 (- org-lowest-priority
714 org-highest-priority)))))))
715 (format "STATUS:%s\n"
716 (if (eq (org-element-property :todo-type entry) 'todo)
717 "NEEDS-ACTION"
718 "COMPLETED"))
719 "END:VTODO"))))
721 (defun org-icalendar--valarm (entry timestamp summary)
722 "Create a VALARM component.
724 ENTRY is the calendar entry triggering the alarm. TIMESTAMP is
725 the start date-time of the entry. SUMMARY defines a short
726 summary or subject for the task.
728 Return VALARM component as a string, or nil if it isn't allowed."
729 ;; Create a VALARM entry if the entry is timed. This is not very
730 ;; general in that:
731 ;; (a) only one alarm per entry is defined,
732 ;; (b) only minutes are allowed for the trigger period ahead of the
733 ;; start time,
734 ;; (c) only a DISPLAY action is defined. [ESF]
735 (let ((alarm-time
736 (let ((warntime
737 (org-element-property :APPT_WARNTIME entry)))
738 (if warntime (string-to-number warntime) 0))))
739 (and (or (> alarm-time 0) (> org-icalendar-alarm-time 0))
740 (org-element-property :hour-start timestamp)
741 (format "BEGIN:VALARM
742 ACTION:DISPLAY
743 DESCRIPTION:%s
744 TRIGGER:-P0DT0H%dM0S
745 END:VALARM\n"
746 summary
747 (if (zerop alarm-time) org-icalendar-alarm-time alarm-time)))))
750 ;;;; Template
752 (defun org-icalendar-template (contents info)
753 "Return complete document string after iCalendar conversion.
754 CONTENTS is the transcoded contents string. INFO is a plist used
755 as a communication channel."
756 (org-icalendar--vcalendar
757 ;; Name.
758 (if (not (plist-get info :input-file)) (buffer-name (buffer-base-buffer))
759 (file-name-nondirectory
760 (file-name-sans-extension (plist-get info :input-file))))
761 ;; Owner.
762 (if (not (plist-get info :with-author)) ""
763 (org-export-data (plist-get info :author) info))
764 ;; Timezone.
765 (if (org-string-nw-p org-icalendar-timezone) org-icalendar-timezone
766 (cadr (current-time-zone)))
767 ;; Description.
768 (org-export-data (plist-get info :title) info)
769 contents))
771 (defun org-icalendar--vcalendar (name owner tz description contents)
772 "Create a VCALENDAR component.
773 NAME, OWNER, TZ, DESCRIPTION and CONTENTS are all strings giving,
774 respectively, the name of the calendar, its owner, the timezone
775 used, a short description and the other components included."
776 (concat (format "BEGIN:VCALENDAR
777 VERSION:2.0
778 X-WR-CALNAME:%s
779 PRODID:-//%s//Emacs with Org mode//EN
780 X-WR-TIMEZONE:%s
781 X-WR-CALDESC:%s
782 CALSCALE:GREGORIAN\n"
783 (org-icalendar-cleanup-string name)
784 (org-icalendar-cleanup-string owner)
785 (org-icalendar-cleanup-string tz)
786 (org-icalendar-cleanup-string description))
787 contents
788 "END:VCALENDAR\n"))
792 ;;; Interactive Functions
794 ;;;###autoload
795 (defun org-icalendar-export-to-ics
796 (&optional async subtreep visible-only body-only)
797 "Export current buffer to an iCalendar file.
799 If narrowing is active in the current buffer, only export its
800 narrowed part.
802 If a region is active, export that region.
804 A non-nil optional argument ASYNC means the process should happen
805 asynchronously. The resulting file should be accessible through
806 the `org-export-stack' interface.
808 When optional argument SUBTREEP is non-nil, export the sub-tree
809 at point, extracting information from the headline properties
810 first.
812 When optional argument VISIBLE-ONLY is non-nil, don't export
813 contents of hidden elements.
815 When optional argument BODY-ONLY is non-nil, only write code
816 between \"BEGIN:VCALENDAR\" and \"END:VCALENDAR\".
818 Return ICS file name."
819 (interactive)
820 (let ((file (buffer-file-name (buffer-base-buffer))))
821 (when (and file org-icalendar-store-UID)
822 (org-icalendar-create-uid file 'warn-user)))
823 ;; Export part. Since this back-end is backed up by `ascii', ensure
824 ;; links will not be collected at the end of sections.
825 (let ((outfile (org-export-output-file-name ".ics" subtreep)))
826 (if async
827 (org-export-async-start
828 (lambda (f)
829 (org-export-add-to-stack f 'icalendar)
830 (run-hook-with-args 'org-icalendar-after-save-hook f))
831 `(let ((org-ascii-links-to-notes nil))
832 (expand-file-name
833 (org-export-to-file
834 'icalendar ,outfile ,subtreep ,visible-only ,body-only
835 '(:ascii-charset utf-8)))))
836 (let ((org-ascii-links-to-notes nil))
837 (org-export-to-file 'icalendar outfile subtreep visible-only body-only
838 '(:ascii-charset utf-8)))
839 (run-hook-with-args 'org-icalendar-after-save-hook outfile)
840 outfile)))
842 ;;;###autoload
843 (defun org-icalendar-export-agenda-files (&optional async)
844 "Export all agenda files to iCalendar files.
845 When optional argument ASYNC is non-nil, export happens in an
846 external process."
847 (interactive)
848 (if async
849 ;; Asynchronous export is not interactive, so we will not call
850 ;; `org-check-agenda-file'. Instead we remove any non-existent
851 ;; agenda file from the list.
852 (let ((files (org-remove-if-not 'file-exists-p (org-agenda-files t))))
853 (org-export-async-start
854 (lambda (results)
855 (mapc (lambda (f) (org-export-add-to-stack f 'icalendar))
856 results))
857 `(let (output-files)
858 (mapc (lambda (file)
859 (with-current-buffer (org-get-agenda-file-buffer file)
860 (push (expand-file-name (org-icalendar-export-to-ics))
861 output-files)))
862 ',files)
863 output-files)))
864 (let ((files (org-agenda-files t)))
865 (org-agenda-prepare-buffers files)
866 (unwind-protect
867 (mapc (lambda (file)
868 (catch 'nextfile
869 (org-check-agenda-file file)
870 (with-current-buffer (org-get-agenda-file-buffer file)
871 (org-icalendar-export-to-ics))))
872 files)
873 (org-release-buffers org-agenda-new-buffers)))))
875 ;;;###autoload
876 (defun org-icalendar-combine-agenda-files (&optional async)
877 "Combine all agenda files into a single iCalendar file.
879 A non-nil optional argument ASYNC means the process should happen
880 asynchronously. The resulting file should be accessible through
881 the `org-export-stack' interface.
883 The file is stored under the name chosen in
884 `org-icalendar-combined-agenda-file'."
885 (interactive)
886 (if async
887 (let ((files (org-remove-if-not 'file-exists-p (org-agenda-files t))))
888 (org-export-async-start
889 (lambda (dummy)
890 (org-export-add-to-stack
891 (expand-file-name org-icalendar-combined-agenda-file)
892 'icalendar))
893 `(apply 'org-icalendar--combine-files nil ',files)))
894 (apply 'org-icalendar--combine-files nil (org-agenda-files t))))
896 (defun org-icalendar-export-current-agenda (file)
897 "Export current agenda view to an iCalendar FILE.
898 This function assumes major mode for current buffer is
899 `org-agenda-mode'."
900 (let (org-export-babel-evaluate ; Don't evaluate Babel block
901 (org-icalendar-combined-agenda-file file)
902 (marker-list
903 ;; Collect the markers pointing to entries in the current
904 ;; agenda buffer.
905 (let (markers)
906 (save-excursion
907 (goto-char (point-min))
908 (while (not (eobp))
909 (let ((m (or (org-get-at-bol 'org-hd-marker)
910 (org-get-at-bol 'org-marker))))
911 (and m (push m markers)))
912 (beginning-of-line 2)))
913 (nreverse markers))))
914 (apply 'org-icalendar--combine-files
915 ;; Build restriction alist.
916 (let (restriction)
917 ;; Sort markers in each association within RESTRICTION.
918 (mapcar (lambda (x) (setcdr x (sort (copy-sequence (cdr x)) '<)) x)
919 (dolist (m marker-list restriction)
920 (let* ((pos (marker-position m))
921 (file (buffer-file-name
922 (org-base-buffer (marker-buffer m))))
923 (file-markers (assoc file restriction)))
924 ;; Add POS in FILE association if one exists
925 ;; or create a new association for FILE.
926 (if file-markers (push pos (cdr file-markers))
927 (push (list file pos) restriction))))))
928 (org-agenda-files nil 'ifmode))))
930 (defun org-icalendar--combine-files (restriction &rest files)
931 "Combine entries from multiple files into an iCalendar file.
932 RESTRICTION, when non-nil, is an alist where key is a file name
933 and value a list of buffer positions pointing to entries that
934 should appear in the calendar. It only makes sense if the
935 function was called from an agenda buffer. FILES is a list of
936 files to build the calendar from."
937 (org-agenda-prepare-buffers files)
938 (unwind-protect
939 (progn
940 (with-temp-file org-icalendar-combined-agenda-file
941 (insert
942 (org-icalendar--vcalendar
943 ;; Name.
944 org-icalendar-combined-name
945 ;; Owner.
946 user-full-name
947 ;; Timezone.
948 (if (org-string-nw-p org-icalendar-timezone)
949 org-icalendar-timezone
950 (cadr (current-time-zone)))
951 ;; Description.
952 org-icalendar-combined-description
953 ;; Contents.
954 (concat
955 ;; Agenda contents.
956 (mapconcat
957 (lambda (file)
958 (catch 'nextfile
959 (org-check-agenda-file file)
960 (with-current-buffer (org-get-agenda-file-buffer file)
961 (let ((marks (cdr (assoc (expand-file-name file) restriction))))
962 ;; Create ID if necessary.
963 (when org-icalendar-store-UID
964 (org-icalendar-create-uid file t marks))
965 (unless (and restriction (not marks))
966 ;; Add a hook adding :ICALENDAR_MARK: property
967 ;; to each entry appearing in agenda view.
968 ;; Use `apply-partially' because the function
969 ;; still has to accept one argument.
970 (let ((org-export-before-processing-hook
971 (cons (apply-partially
972 (lambda (m-list dummy)
973 (mapc (lambda (m)
974 (org-entry-put
975 m "ICALENDAR-MARK" "t"))
976 m-list))
977 (sort marks '>))
978 org-export-before-processing-hook)))
979 (org-export-as
980 'icalendar nil nil t
981 (list :ascii-charset 'utf-8
982 :icalendar-agenda-view restriction))))))))
983 files "")
984 ;; BBDB anniversaries.
985 (when (and org-icalendar-include-bbdb-anniversaries
986 (require 'org-bbdb nil t))
987 (with-temp-buffer
988 (org-bbdb-anniv-export-ical)
989 (buffer-string)))))))
990 (run-hook-with-args 'org-icalendar-after-save-hook
991 org-icalendar-combined-agenda-file))
992 (org-release-buffers org-agenda-new-buffers)))
995 (provide 'ox-icalendar)
997 ;; Local variables:
998 ;; generated-autoload-file: "org-loaddefs.el"
999 ;; End:
1001 ;;; ox-icalendar.el ends here