Fix bug.
[org-mode.git] / lisp / org-icalendar.el
blob93ddd2836308f250345318f1158addea47d570e4
1 ;;; org-icalendar.el --- iCalendar export for Org-mode
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
4 ;; Free Software Foundation, Inc.
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.26trans
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 (require 'org-exp)
31 (defgroup org-export-icalendar nil
32 "Options specific for iCalendar export of Org-mode files."
33 :tag "Org Export iCalendar"
34 :group 'org-export)
36 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
37 "The file name for the iCalendar file covering all agenda files.
38 This file is created with the command \\[org-export-icalendar-all-agenda-files].
39 The file name should be absolute, the file will be overwritten without warning."
40 :group 'org-export-icalendar
41 :type 'file)
43 (defcustom org-icalendar-combined-name "OrgMode"
44 "Calendar name for the combined iCalendar representing all agenda files."
45 :group 'org-export-icalendar
46 :type 'string)
48 (defcustom org-icalendar-use-deadline '(event-if-not-todo todo-due)
49 "Contexts where iCalendar export should use a deadline time stamp.
50 This is a list with several symbols in it. Valid symbol are:
52 event-if-todo Deadlines in TODO entries become calendar events.
53 event-if-not-todo Deadlines in non-TODO entries become calendar events.
54 todo-due Use deadlines in TODO entries as due-dates"
55 :group 'org-export-icalendar
56 :type '(set :greedy t
57 (const :tag "Deadlines in non-TODO entries become events"
58 event-if-not-todo)
59 (const :tag "Deadline in TODO entries become events"
60 event-if-todo)
61 (const :tag "Deadlines in TODO entries become due-dates"
62 todo-due)))
64 (defcustom org-icalendar-use-scheduled '(todo-start)
65 "Contexts where iCalendar export should use a scheduling time stamp.
66 This is a list with several symbols in it. Valid symbol are:
68 event-if-todo Scheduling time stamps in TODO entries become an event.
69 event-if-not-todo Scheduling time stamps in non-TODO entries become an event.
70 todo-start Scheduling time stamps in TODO entries become start date.
71 Some calendar applications show TODO entries only after
72 that date."
73 :group 'org-export-icalendar
74 :type '(set :greedy t
75 (const :tag
76 "SCHEDULED timestamps in non-TODO entries become events"
77 event-if-not-todo)
78 (const :tag "SCHEDULED timestamps in TODO entries become events"
79 event-if-todo)
80 (const :tag "SCHEDULED in TODO entries become start date"
81 todo-start)))
83 (defcustom org-icalendar-categories '(local-tags category)
84 "Items that should be entered into the categories field.
85 This is a list of symbols, the following are valid:
87 category The Org-mode category of the current file or tree
88 todo-state The todo state, if any
89 local-tags The tags, defined in the current line
90 all-tags All tags, including inherited ones."
91 :group 'org-export-icalendar
92 :type '(repeat
93 (choice
94 (const :tag "The file or tree category" category)
95 (const :tag "The TODO state" todo-state)
96 (const :tag "Tags defined in current line" local-tags)
97 (const :tag "All tags, including inherited ones" all-tags))))
99 (defcustom org-icalendar-include-todo nil
100 "Non-nil means, export to iCalendar files should also cover TODO items."
101 :group 'org-export-icalendar
102 :type '(choice
103 (const :tag "None" nil)
104 (const :tag "Unfinished" t)
105 (const :tag "All" all)))
107 (defcustom org-icalendar-include-sexps t
108 "Non-nil means, export to iCalendar files should also cover sexp entries.
109 These are entries like in the diary, but directly in an Org-mode file."
110 :group 'org-export-icalendar
111 :type 'boolean)
113 (defcustom org-icalendar-include-body 100
114 "Amount of text below headline to be included in iCalendar export.
115 This is a number of characters that should maximally be included.
116 Properties, scheduling and clocking lines will always be removed.
117 The text will be inserted into the DESCRIPTION field."
118 :group 'org-export-icalendar
119 :type '(choice
120 (const :tag "Nothing" nil)
121 (const :tag "Everything" t)
122 (integer :tag "Max characters")))
124 (defcustom org-icalendar-store-UID nil
125 "Non-nil means, store any created UIDs in properties.
126 The iCalendar standard requires that all entries have a unique identifier.
127 Org will create these identifiers as needed. When this variable is non-nil,
128 the created UIDs will be stored in the ID property of the entry. Then the
129 next time this entry is exported, it will be exported with the same UID,
130 superceding the previous form of it. This is essential for
131 synchronization services.
132 This variable is not turned on by default because we want to avoid creating
133 a property drawer in every entry if people are only playing with this feature,
134 or if they are only using it locally."
135 :group 'org-export-icalendar
136 :type 'boolean)
138 (defcustom org-icalendar-timezone ""
139 "The time zone string for iCalendar export.
140 When nil of the empty string, use the abbreviation retrived from Emacs."
141 :group 'org-export-icalendar
142 :type 'string)
144 ;;; iCalendar export
146 ;;;###autoload
147 (defun org-export-icalendar-this-file ()
148 "Export current file as an iCalendar file.
149 The iCalendar file will be located in the same directory as the Org-mode
150 file, but with extension `.ics'."
151 (interactive)
152 (org-export-icalendar nil buffer-file-name))
154 ;;;###autoload
155 (defun org-export-icalendar-all-agenda-files ()
156 "Export all files in `org-agenda-files' to iCalendar .ics files.
157 Each iCalendar file will be located in the same directory as the Org-mode
158 file, but with extension `.ics'."
159 (interactive)
160 (apply 'org-export-icalendar nil (org-agenda-files t)))
162 ;;;###autoload
163 (defun org-export-icalendar-combine-agenda-files ()
164 "Export all files in `org-agenda-files' to a single combined iCalendar file.
165 The file is stored under the name `org-combined-agenda-icalendar-file'."
166 (interactive)
167 (apply 'org-export-icalendar t (org-agenda-files t)))
169 (defun org-export-icalendar (combine &rest files)
170 "Create iCalendar files for all elements of FILES.
171 If COMBINE is non-nil, combine all calendar entries into a single large
172 file and store it under the name `org-combined-agenda-icalendar-file'."
173 (save-excursion
174 (org-prepare-agenda-buffers files)
175 (let* ((dir (org-export-directory
176 :ical (list :publishing-directory
177 org-export-publishing-directory)))
178 file ical-file ical-buffer category started org-agenda-new-buffers)
179 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
180 (when combine
181 (setq ical-file
182 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
183 org-combined-agenda-icalendar-file
184 (expand-file-name org-combined-agenda-icalendar-file dir))
185 ical-buffer (org-get-agenda-file-buffer ical-file))
186 (set-buffer ical-buffer) (erase-buffer))
187 (while (setq file (pop files))
188 (catch 'nextfile
189 (org-check-agenda-file file)
190 (set-buffer (org-get-agenda-file-buffer file))
191 (unless combine
192 (setq ical-file (concat (file-name-as-directory dir)
193 (file-name-sans-extension
194 (file-name-nondirectory buffer-file-name))
195 ".ics"))
196 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
197 (with-current-buffer ical-buffer (erase-buffer)))
198 (setq category (or org-category
199 (file-name-sans-extension
200 (file-name-nondirectory buffer-file-name))))
201 (if (symbolp category) (setq category (symbol-name category)))
202 (let ((standard-output ical-buffer))
203 (if combine
204 (and (not started) (setq started t)
205 (org-start-icalendar-file org-icalendar-combined-name))
206 (org-start-icalendar-file category))
207 (org-print-icalendar-entries combine)
208 (when (or (and combine (not files)) (not combine))
209 (org-finish-icalendar-file)
210 (set-buffer ical-buffer)
211 (run-hooks 'org-before-save-iCalendar-file-hook)
212 (save-buffer)
213 (run-hooks 'org-after-save-iCalendar-file-hook)
214 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
215 ))))
216 (org-release-buffers org-agenda-new-buffers))))
218 (defvar org-before-save-iCalendar-file-hook nil
219 "Hook run before an iCalendar file has been saved.
220 This can be used to modify the result of the export.")
222 (defvar org-after-save-iCalendar-file-hook nil
223 "Hook run after an iCalendar file has been saved.
224 The iCalendar buffer is still current when this hook is run.
225 A good way to use this is to tell a desktop calendar application to re-read
226 the iCalendar file.")
228 (defvar org-agenda-default-appointment-duration) ; defined in org-agenda.el
229 (defun org-print-icalendar-entries (&optional combine)
230 "Print iCalendar entries for the current Org-mode file to `standard-output'.
231 When COMBINE is non nil, add the category to each line."
232 (require 'org-agenda)
233 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
234 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
235 (dts (org-ical-ts-to-string
236 (format-time-string (cdr org-time-stamp-formats) (current-time))
237 "DTSTART"))
238 hd ts ts2 state status (inc t) pos b sexp rrule
239 scheduledp deadlinep todo prefix due start
240 tmp pri categories location summary desc uid
241 (sexp-buffer (get-buffer-create "*ical-tmp*")))
242 (org-refresh-category-properties)
243 (save-excursion
244 (goto-char (point-min))
245 (while (re-search-forward re1 nil t)
246 (catch :skip
247 (org-agenda-skip)
248 (when (boundp 'org-icalendar-verify-function)
249 (unless (funcall org-icalendar-verify-function)
250 (outline-next-heading)
251 (backward-char 1)
252 (throw :skip nil)))
253 (setq pos (match-beginning 0)
254 ts (match-string 0)
255 inc t
256 hd (condition-case nil
257 (org-icalendar-cleanup-string
258 (org-get-heading))
259 (error (throw :skip nil)))
260 summary (org-icalendar-cleanup-string
261 (org-entry-get nil "SUMMARY"))
262 desc (org-icalendar-cleanup-string
263 (or (org-entry-get nil "DESCRIPTION")
264 (and org-icalendar-include-body (org-get-entry)))
265 t org-icalendar-include-body)
266 location (org-icalendar-cleanup-string
267 (org-entry-get nil "LOCATION" 'selective))
268 uid (if org-icalendar-store-UID
269 (org-id-get-create)
270 (or (org-id-get) (org-id-new)))
271 categories (org-export-get-categories)
272 deadlinep nil scheduledp nil)
273 (if (looking-at re2)
274 (progn
275 (goto-char (match-end 0))
276 (setq ts2 (match-string 1)
277 inc (not (string-match "[0-9]\\{1,2\\}:[0-9][0-9]" ts2))))
278 (setq tmp (buffer-substring (max (point-min)
279 (- pos org-ds-keyword-length))
280 pos)
281 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
282 (progn
283 (setq inc nil)
284 (replace-match "\\1" t nil ts))
286 deadlinep (string-match org-deadline-regexp tmp)
287 scheduledp (string-match org-scheduled-regexp tmp)
288 todo (org-get-todo-state)
289 ;; donep (org-entry-is-done-p)
291 (when (and
292 deadlinep
293 (if todo
294 (not (memq 'event-if-todo org-icalendar-use-deadline))
295 (not (memq 'event-if-not-todo org-icalendar-use-deadline))))
296 (throw :skip t))
297 (when (and
298 scheduledp
299 (if todo
300 (not (memq 'event-if-todo org-icalendar-use-scheduled))
301 (not (memq 'event-if-not-todo org-icalendar-use-scheduled))))
302 (throw :skip t))
303 (setq prefix (if deadlinep "DL-" (if scheduledp "SC-" "TS-")))
304 (if (or (string-match org-tr-regexp hd)
305 (string-match org-ts-regexp hd))
306 (setq hd (replace-match "" t t hd)))
307 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
308 (setq rrule
309 (concat "\nRRULE:FREQ="
310 (cdr (assoc
311 (match-string 2 ts)
312 '(("d" . "DAILY")("w" . "WEEKLY")
313 ("m" . "MONTHLY")("y" . "YEARLY"))))
314 ";INTERVAL=" (match-string 1 ts)))
315 (setq rrule ""))
316 (setq summary (or summary hd))
317 (if (string-match org-bracket-link-regexp summary)
318 (setq summary
319 (replace-match (if (match-end 3)
320 (match-string 3 summary)
321 (match-string 1 summary))
322 t t summary)))
323 (if deadlinep (setq summary (concat "DL: " summary)))
324 (if scheduledp (setq summary (concat "S: " summary)))
325 (if (string-match "\\`<%%" ts)
326 (with-current-buffer sexp-buffer
327 (insert (substring ts 1 -1) " " summary "\n"))
328 (princ (format "BEGIN:VEVENT
329 UID: %s
331 %s%s
332 SUMMARY:%s%s%s
333 CATEGORIES:%s
334 END:VEVENT\n"
335 (concat prefix uid)
336 (org-ical-ts-to-string ts "DTSTART")
337 (org-ical-ts-to-string ts2 "DTEND" inc)
338 rrule summary
339 (if (and desc (string-match "\\S-" desc))
340 (concat "\nDESCRIPTION: " desc) "")
341 (if (and location (string-match "\\S-" location))
342 (concat "\nLOCATION: " location) "")
343 categories)))))
344 (when (and org-icalendar-include-sexps
345 (condition-case nil (require 'icalendar) (error nil))
346 (fboundp 'icalendar-export-region))
347 ;; Get all the literal sexps
348 (goto-char (point-min))
349 (while (re-search-forward "^&?%%(" nil t)
350 (catch :skip
351 (org-agenda-skip)
352 (setq b (match-beginning 0))
353 (goto-char (1- (match-end 0)))
354 (forward-sexp 1)
355 (end-of-line 1)
356 (setq sexp (buffer-substring b (point)))
357 (with-current-buffer sexp-buffer
358 (insert sexp "\n"))))
359 (princ (org-diary-to-ical-string sexp-buffer))
360 (kill-buffer sexp-buffer))
362 (when org-icalendar-include-todo
363 (setq prefix "TODO-")
364 (goto-char (point-min))
365 (while (re-search-forward org-todo-line-regexp nil t)
366 (catch :skip
367 (org-agenda-skip)
368 (when (boundp 'org-icalendar-verify-function)
369 (unless (funcall org-icalendar-verify-function)
370 (outline-next-heading)
371 (backward-char 1)
372 (throw :skip nil)))
373 (setq state (match-string 2))
374 (setq status (if (member state org-done-keywords)
375 "COMPLETED" "NEEDS-ACTION"))
376 (when (and state
377 (or (not (member state org-done-keywords))
378 (eq org-icalendar-include-todo 'all))
379 (not (member org-archive-tag (org-get-tags-at)))
381 (setq hd (match-string 3)
382 summary (org-icalendar-cleanup-string
383 (org-entry-get nil "SUMMARY"))
384 desc (org-icalendar-cleanup-string
385 (or (org-entry-get nil "DESCRIPTION")
386 (and org-icalendar-include-body (org-get-entry)))
387 t org-icalendar-include-body)
388 location (org-icalendar-cleanup-string
389 (org-entry-get nil "LOCATION" 'selective))
390 due (and (member 'todo-due org-icalendar-use-deadline)
391 (org-entry-get nil "DEADLINE"))
392 start (and (member 'todo-start org-icalendar-use-scheduled)
393 (org-entry-get nil "SCHEDULED"))
394 categories (org-export-get-categories)
395 uid (if org-icalendar-store-UID
396 (org-id-get-create)
397 (or (org-id-get) (org-id-new))))
398 (and due (setq due (org-ical-ts-to-string due "DUE")))
399 (and start (setq start (org-ical-ts-to-string start "DTSTART")))
401 (if (string-match org-bracket-link-regexp hd)
402 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
403 (match-string 1 hd))
404 t t hd)))
405 (if (string-match org-priority-regexp hd)
406 (setq pri (string-to-char (match-string 2 hd))
407 hd (concat (substring hd 0 (match-beginning 1))
408 (substring hd (match-end 1))))
409 (setq pri org-default-priority))
410 (setq pri (floor (- 9 (* 8. (/ (float (- org-lowest-priority pri))
411 (- org-lowest-priority org-highest-priority))))))
413 (princ (format "BEGIN:VTODO
414 UID: %s
416 SUMMARY:%s%s%s%s
417 CATEGORIES:%s
418 SEQUENCE:1
419 PRIORITY:%d
420 STATUS:%s
421 END:VTODO\n"
422 (concat prefix uid)
423 (or start dts)
424 (or summary hd)
425 (if (and location (string-match "\\S-" location))
426 (concat "\nLOCATION: " location) "")
427 (if (and desc (string-match "\\S-" desc))
428 (concat "\nDESCRIPTION: " desc) "")
429 (if due (concat "\n" due) "")
430 categories
431 pri status)))))))))
433 (defun org-export-get-categories ()
434 "Get categories according to `org-icalendar-categories'."
435 (let ((cs org-icalendar-categories) c rtn tmp)
436 (while (setq c (pop cs))
437 (cond
438 ((eq c 'category) (push (org-get-category) rtn))
439 ((eq c 'todo-state)
440 (setq tmp (org-get-todo-state))
441 (and tmp (push tmp rtn)))
442 ((eq c 'local-tags)
443 (setq rtn (append (nreverse (org-get-local-tags-at (point))) rtn)))
444 ((eq c 'all-tags)
445 (setq rtn (append (nreverse (org-get-tags-at (point))) rtn)))))
446 (mapconcat 'identity (nreverse rtn) ",")))
448 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
449 "Take out stuff and quote what needs to be quoted.
450 When IS-BODY is non-nil, assume that this is the body of an item, clean up
451 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
452 characters."
453 (if (not s)
455 (when is-body
456 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
457 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
458 (while (string-match re s) (setq s (replace-match "" t t s)))
459 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
460 (let ((start 0))
461 (while (string-match "\\([,;]\\)" s start)
462 (setq start (+ (match-beginning 0) 2)
463 s (replace-match "\\\\\\1" nil nil s))))
464 (setq s (org-trim s))
465 (when is-body
466 (while (string-match "[ \t]*\n[ \t]*" s)
467 (setq s (replace-match "\\n" t t s))))
468 (if is-body
469 (if maxlength
470 (if (and (numberp maxlength)
471 (> (length s) maxlength))
472 (setq s (substring s 0 maxlength)))))
475 (defun org-icalendar-cleanup-string-rfc2455 (s &optional is-body maxlength)
476 "Take out stuff and quote what needs to be quoted.
477 When IS-BODY is non-nil, assume that this is the body of an item, clean up
478 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
479 characters.
480 This seems to be more like RFC 2455, but it causes problems, so it is
481 not used right now."
482 (if (not s)
484 (if is-body
485 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
486 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
487 (while (string-match re s) (setq s (replace-match "" t t s)))
488 (while (string-match re2 s) (setq s (replace-match "" t t s)))
489 (setq s (org-trim s))
490 (while (string-match "[ \t]*\n[ \t]*" s)
491 (setq s (replace-match "\\n" t t s)))
492 (if maxlength
493 (if (and (numberp maxlength)
494 (> (length s) maxlength))
495 (setq s (substring s 0 maxlength)))))
496 (setq s (org-trim s)))
497 (while (string-match "\"" s) (setq s (replace-match "''" t t s)))
498 (when (string-match "[;,:]" s) (setq s (concat "\"" s "\"")))
501 (defun org-start-icalendar-file (name)
502 "Start an iCalendar file by inserting the header."
503 (let ((user user-full-name)
504 (name (or name "unknown"))
505 (timezone (if (> (length org-icalendar-timezone) 0)
506 org-icalendar-timezone
507 (cadr (current-time-zone)))))
508 (princ
509 (format "BEGIN:VCALENDAR
510 VERSION:2.0
511 X-WR-CALNAME:%s
512 PRODID:-//%s//Emacs with Org-mode//EN
513 X-WR-TIMEZONE:%s
514 CALSCALE:GREGORIAN\n" name user timezone))))
516 (defun org-finish-icalendar-file ()
517 "Finish an iCalendar file by inserting the END statement."
518 (princ "END:VCALENDAR\n"))
520 (defun org-ical-ts-to-string (s keyword &optional inc)
521 "Take a time string S and convert it to iCalendar format.
522 KEYWORD is added in front, to make a complete line like DTSTART....
523 When INC is non-nil, increase the hour by two (if time string contains
524 a time), or the day by one (if it does not contain a time)."
525 (let ((t1 (org-parse-time-string s 'nodefault))
526 t2 fmt have-time time)
527 (if (and (car t1) (nth 1 t1) (nth 2 t1))
528 (setq t2 t1 have-time t)
529 (setq t2 (org-parse-time-string s)))
530 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
531 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
532 (when inc
533 (if have-time
534 (if org-agenda-default-appointment-duration
535 (setq mi (+ org-agenda-default-appointment-duration mi))
536 (setq h (+ 2 h)))
537 (setq d (1+ d))))
538 (setq time (encode-time s mi h d m y)))
539 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
540 (concat keyword (format-time-string fmt time))))
542 (provide 'org-icalendar)
544 ;; arch-tag: 2dee2b6e-9211-4aee-8a47-a3c7e5bc30cf
546 ;;; org-icalendar.el ends here