icalendar.el 83.6 KB
Newer Older
1
;;; icalendar.el --- iCalendar implementation -*-coding: utf-8 -*-
2

Glenn Morris's avatar
Glenn Morris committed
3
;; Copyright (C) 2002, 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
4

5 6 7
;; Author:         Ulf Jasper <ulf.jasper@web.de>
;; Created:        August 2002
;; Keywords:       calendar
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
;; Human-Keywords: calendar, diary, iCalendar, vCalendar

;; This file is part of GNU Emacs.

;; GNU Emacs is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to the
Lute Kamstra's avatar
Lute Kamstra committed
24 25
;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
26 27 28 29 30

;;; Commentary:

;; This package is documented in the Emacs Manual.

31 32 33 34 35 36 37
;;   Please note:
;; - Diary entries which have a start time but no end time are assumed to
;;   last for one hour when they are exported.
;; - Weekly diary entries are assumed to occur the first time in the first
;;   week of the year 2000 when they are exported.
;; - Yearly diary entries are assumed to occur the first time in the year
;;   1900 when they are exported.
38 39 40

;;; History:

41
;;  0.07 onwards: see lisp/ChangeLog
42 43 44 45

;;  0.06: Bugfixes regarding icalendar-import-format-*.
;;        Fix in icalendar-convert-diary-to-ical -- thanks to Philipp
;;        Grau.
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

;;  0.05: New import format scheme: Replaced icalendar-import-prefix-*,
;;        icalendar-import-ignored-properties, and
;;        icalendar-import-separator with icalendar-import-format(-*).
;;        icalendar-import-file and icalendar-convert-diary-to-ical
;;        have an extra parameter which should prevent them from
;;        erasing their target files (untested!).
;;        Tested with Emacs 21.3.2

;;  0.04: Bugfix: import: double quoted param values did not work
;;        Read DURATION property when importing.
;;        Added parameter icalendar-duration-correction.

;;  0.03: Export takes care of european-calendar-style.
;;        Tested with Emacs 21.3.2 and XEmacs 21.4.12

;;  0.02: Should work in XEmacs now.  Thanks to Len Trigg for the
;;        XEmacs patches!
;;        Added exporting from Emacs diary to ical.
;;        Some bugfixes, after testing with calendars from
;;        http://icalshare.com.
;;        Tested with Emacs 21.3.2 and XEmacs 21.4.12

;;  0.01: First published version.  Trial version.  Alpha version.

;; ======================================================================
;; To Do:

74
;;  * Import from ical to diary:
75 76 77 78 79 80 81 82 83 84
;;    + Need more properties for icalendar-import-format
;;    + check vcalendar version
;;    + check (unknown) elements
;;    + recurring events!
;;    + works for european style calendars only! Does it?
;;    + alarm
;;    + exceptions in recurring events
;;    + the parser is too soft
;;    + error log is incomplete
;;    + nice to have: #include "webcal://foo.com/some-calendar.ics"
85
;;    + timezones, currently all times are local!
86

87
;;  * Export from diary to ical
88 89 90 91 92 93 94 95 96 97 98 99
;;    + diary-date, diary-float, and self-made sexp entries are not
;;      understood

;;  * Other things
;;    + clean up all those date/time parsing functions
;;    + Handle todo items?
;;    + Check iso 8601 for datetime and period
;;    + Which chars to (un)escape?


;;; Code:

100
(defconst icalendar-version "0.13"
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
  "Version number of icalendar.el.")

;; ======================================================================
;; Customizables
;; ======================================================================
(defgroup icalendar nil
  "Icalendar support."
  :prefix "icalendar-"
  :group 'calendar)

(defcustom icalendar-import-format
  "%s%d%l%o"
  "Format string for importing events from iCalendar into Emacs diary.
This string defines how iCalendar events are inserted into diary
file.  Meaning of the specifiers:
116
%c Class, see `icalendar-import-format-class'
117 118 119
%d Description, see `icalendar-import-format-description'
%l Location, see `icalendar-import-format-location'
%o Organizer, see `icalendar-import-format-organizer'
120 121 122
%s Summary, see `icalendar-import-format-summary'
%t Status, see `icalendar-import-format-status'
%u URL, see `icalendar-import-format-url'"
123 124 125
  :type 'string
  :group 'icalendar)

126
(defcustom icalendar-import-format-summary
127
  "%s"
128 129 130
  "Format string defining how the summary element is formatted.
This applies only if the summary is not empty! `%s' is replaced
by the summary."
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
  :type 'string
  :group 'icalendar)

(defcustom icalendar-import-format-description
  "\n Desc: %s"
  "Format string defining how the description element is formatted.
This applies only if the description is not empty! `%s' is
replaced by the description."
  :type 'string
  :group 'icalendar)

(defcustom icalendar-import-format-location
  "\n Location: %s"
  "Format string defining how the location element is formatted.
This applies only if the location is not empty! `%s' is replaced
by the location."
  :type 'string
  :group 'icalendar)

(defcustom icalendar-import-format-organizer
  "\n Organizer: %s"
  "Format string defining how the organizer element is formatted.
This applies only if the organizer is not empty! `%s' is
replaced by the organizer."
  :type 'string
  :group 'icalendar)

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
(defcustom icalendar-import-format-url
  "\n URL: %s"
  "Format string defining how the URL element is formatted.
This applies only if the URL is not empty! `%s' is replaced by
the URL."
  :type 'string
  :group 'icalendar)

(defcustom icalendar-import-format-status
  "\n Status: %s"
  "Format string defining how the status element is formatted.
This applies only if the status is not empty! `%s' is replaced by
the status."
  :type 'string
  :group 'icalendar)

(defcustom icalendar-import-format-class
  "\n Class: %s"
  "Format string defining how the class element is formatted.
This applies only if the class is not empty! `%s' is replaced by
the class."
  :type 'string
  :group 'icalendar)

182 183
(defvar icalendar-debug nil
  "Enable icalendar debug messages.")
184 185 186 187 188

;; ======================================================================
;; NO USER SERVICABLE PARTS BELOW THIS LINE
;; ======================================================================

189
(defconst icalendar--weekday-array ["SU" "MO" "TU" "WE" "TH" "FR" "SA"])
190 191 192 193 194 195

;; ======================================================================
;; all the other libs we need
;; ======================================================================
(require 'calendar)

196 197 198 199 200 201 202 203
;; ======================================================================
;; misc
;; ======================================================================
(defun icalendar--dmsg (&rest args)
  "Print message ARGS if `icalendar-debug' is non-nil."
  (if icalendar-debug
      (apply 'message args)))

204 205 206 207 208
;; ======================================================================
;; Core functionality
;; Functions for parsing icalendars, importing and so on
;; ======================================================================

209
(defun icalendar--get-unfolded-buffer (folded-ical-buffer)
210 211 212 213 214 215 216 217 218
  "Return a new buffer containing the unfolded contents of a buffer.
Folding is the iCalendar way of wrapping long lines.  In the
created buffer all occurrences of CR LF BLANK are replaced by the
empty string.  Argument FOLDED-ICAL-BUFFER is the unfolded input
buffer."
  (let ((unfolded-buffer (get-buffer-create " *icalendar-work*")))
    (save-current-buffer
      (set-buffer unfolded-buffer)
      (erase-buffer)
219 220
      (insert-buffer-substring folded-ical-buffer)
      (goto-char (point-min))
221
      (while (re-search-forward "\r?\n[ \t]" nil t)
222
        (replace-match "" nil nil)))
223 224
    unfolded-buffer))

225 226 227 228
(defsubst icalendar--rris (&rest args)
  "Replace regular expression in string.
Pass ARGS to `replace-regexp-in-string' (Emacs) or to
`replace-in-string' (XEmacs)."
229 230 231
  ;; XEmacs:
  (if (fboundp 'replace-in-string)
      (save-match-data ;; apparently XEmacs needs save-match-data
232
        (apply 'replace-in-string args))
233
    ;; Emacs:
234
    (apply 'replace-regexp-in-string args)))
235

236
(defun icalendar--read-element (invalue inparams)
237 238 239 240 241 242 243
  "Recursively read the next iCalendar element in the current buffer.
INVALUE gives the current iCalendar element we are reading.
INPARAMS gives the current parameters.....
This function calls itself recursively for each nested calendar element
it finds"
  (let (element children line name params param param-name param-value
                value
244
                (continue t))
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
    (setq children '())
    (while (and continue
                (re-search-forward "^\\([A-Za-z0-9-]+\\)[;:]" nil t))
      (setq name (intern (match-string 1)))
      (backward-char 1)
      (setq params '())
      (setq line '())
      (while (looking-at ";")
        (re-search-forward ";\\([A-Za-z0-9-]+\\)=" nil nil)
        (setq param-name (intern (match-string 1)))
        (re-search-forward "\\(\\([^;,:\"]+\\)\\|\"\\([^\"]+\\)\"\\)[;:]"
                           nil t)
        (backward-char 1)
        (setq param-value (or (match-string 2) (match-string 3)))
        (setq param (list param-name param-value))
        (while (looking-at ",")
          (re-search-forward "\\(\\([^;,:]+\\)\\|\"\\([^\"]+\\)\"\\)"
                             nil t)
          (if (match-string 2)
              (setq param-value (match-string 2))
            (setq param-value (match-string 3)))
          (setq param (append param param-value)))
        (setq params (append params param)))
      (unless (looking-at ":")
        (error "Oops"))
      (forward-char 1)
      (re-search-forward  "\\(.*\\)\\(\r?\n[ \t].*\\)*" nil t)
272
      (setq value (icalendar--rris "\r?\n[ \t]" "" (match-string 0)))
273 274 275 276
      (setq line (list name params value))
      (cond ((eq name 'BEGIN)
             (setq children
                   (append children
277 278
                           (list (icalendar--read-element (intern value)
                                                          params)))))
279 280 281 282 283 284 285 286 287 288 289 290
            ((eq name 'END)
             (setq continue nil))
            (t
             (setq element (append element (list line))))))
    (if invalue
        (list invalue inparams element children)
      children)))

;; ======================================================================
;; helper functions for examining events
;; ======================================================================

291 292 293
;;(defsubst icalendar--get-all-event-properties (event)
;;  "Return the list of properties in this EVENT."
;;  (car (cddr event)))
294

295
(defun icalendar--get-event-property (event prop)
296
  "For the given EVENT return the value of the first occurence of PROP."
297 298 299 300 301 302 303 304 305
  (catch 'found
    (let ((props (car (cddr event))) pp)
      (while props
        (setq pp (car props))
        (if (eq (car pp) prop)
            (throw 'found (car (cddr pp))))
        (setq props (cdr props))))
    nil))

306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
(defun icalendar--get-event-property-attributes (event prop)
  "For the given EVENT return attributes of the first occurence of PROP."
  (catch 'found
    (let ((props (car (cddr event))) pp)
      (while props
        (setq pp (car props))
        (if (eq (car pp) prop)
            (throw 'found (cadr pp)))
        (setq props (cdr props))))
    nil))

(defun icalendar--get-event-properties (event prop)
  "For the given EVENT return a list of all values of the property PROP."
  (let ((props (car (cddr event))) pp result)
    (while props
      (setq pp (car props))
      (if (eq (car pp) prop)
323
          (setq result (append (split-string (car (cddr pp)) ",") result)))
324 325 326
      (setq props (cdr props)))
    result))

327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
;; (defun icalendar--set-event-property (event prop new-value)
;;   "For the given EVENT set the property PROP to the value NEW-VALUE."
;;   (catch 'found
;;     (let ((props (car (cddr event))) pp)
;;       (while props
;;         (setq pp (car props))
;;         (when (eq (car pp) prop)
;;           (setcdr (cdr pp) new-value)
;;           (throw 'found (car (cddr pp))))
;;         (setq props (cdr props)))
;;       (setq props (car (cddr event)))
;;       (setcar (cddr event)
;;               (append props (list (list prop nil new-value)))))))

(defun icalendar--get-children (node name)
342 343 344 345 346 347 348 349 350 351 352
  "Return all children of the given NODE which have a name NAME.
For instance the VCALENDAR node can have VEVENT children as well as VTODO
children."
  (let ((result nil)
        (children (cadr (cddr node))))
    (when (eq (car node) name)
      (setq result node))
    ;;(message "%s" node)
    (when children
      (let ((subresult
             (delq nil
353 354 355
                   (mapcar (lambda (n)
                             (icalendar--get-children n name))
                           children))))
356 357 358 359 360 361
        (if subresult
            (if result
                (setq result (append result subresult))
              (setq result subresult)))))
    result))

362 363
                                        ; private
(defun icalendar--all-events (icalendar)
364
  "Return the list of all existing events in the given ICALENDAR."
365
  (icalendar--get-children (car icalendar) 'VEVENT))
366

367
(defun icalendar--split-value (value-string)
368
  "Split VALUE-STRING at ';='."
369 370 371 372
  (let ((result '())
        param-name param-value)
    (when value-string
      (save-current-buffer
373
        (set-buffer (get-buffer-create " *icalendar-work*"))
374 375 376 377 378
        (set-buffer-modified-p nil)
        (erase-buffer)
        (insert value-string)
        (goto-char (point-min))
        (while
379 380 381
            (re-search-forward
             "\\([A-Za-z0-9-]+\\)=\\(\\([^;,:]+\\)\\|\"\\([^\"]+\\)\"\\);?"
             nil t)
382 383 384
          (setq param-name (intern (match-string 1)))
          (setq param-value (match-string 2))
          (setq result
385
                (append result (list (list param-name param-value)))))))
386 387
    result))

388
(defun icalendar--decode-isodatetime (isodatetimestring &optional day-shift)
389
  "Return ISODATETIMESTRING in format like `decode-time'.
390 391 392 393 394 395 396 397
Converts from ISO-8601 to Emacs representation.  If
ISODATETIMESTRING specifies UTC time (trailing letter Z) the
decoded time is given in the local time zone!  If optional
parameter DAY-SHIFT is non-nil the result is shifted by DAY-SHIFT
days.

FIXME: TZID-attributes are ignored....!
FIXME: multiple comma-separated values should be allowed!"
398
  (icalendar--dmsg isodatetimestring)
399 400 401 402 403 404 405 406 407
  (if isodatetimestring
      ;; day/month/year must be present
      (let ((year  (read (substring isodatetimestring 0 4)))
            (month (read (substring isodatetimestring 4 6)))
            (day   (read (substring isodatetimestring 6 8)))
            (hour 0)
            (minute 0)
            (second 0))
        (when (> (length isodatetimestring) 12)
408
          ;; hour/minute present
409 410 411
          (setq hour (read (substring isodatetimestring 9 11)))
          (setq minute (read (substring isodatetimestring 11 13))))
        (when (> (length isodatetimestring) 14)
412
          ;; seconds present
413 414
          (setq second (read (substring isodatetimestring 13 15))))
        (when (and (> (length isodatetimestring) 15)
415
                   ;; UTC specifier present
416 417 418
                   (char-equal ?Z (aref isodatetimestring 15)))
          ;; if not UTC add current-time-zone offset
          (setq second (+ (car (current-time-zone)) second)))
419 420 421 422 423 424 425 426 427
        ;; shift if necessary
        (if day-shift
            (let ((mdy (calendar-gregorian-from-absolute
                        (+ (calendar-absolute-from-gregorian
                            (list month day year))
                           day-shift))))
              (setq month (nth 0 mdy))
              (setq day   (nth 1 mdy))
              (setq year  (nth 2 mdy))))
428 429 430 431 432 433 434 435 436 437 438
        ;; create the decoded date-time
        ;; FIXME!?!
        (condition-case nil
            (decode-time (encode-time second minute hour day month year))
          (error
           (message "Cannot decode \"%s\"" isodatetimestring)
           ;; hope for the best...
           (list second minute hour day month year 0 nil 0))))
    ;; isodatetimestring == nil
    nil))

439 440 441
(defun icalendar--decode-isoduration (isodurationstring
                                      &optional duration-correction)
  "Convert ISODURATIONSTRING into format provided by `decode-time'.
442 443
Converts from ISO-8601 to Emacs representation.  If ISODURATIONSTRING
specifies UTC time (trailing letter Z) the decoded time is given in
444 445
the local time zone!

446 447
Optional argument DURATION-CORRECTION shortens result by one day.

448 449
FIXME: TZID-attributes are ignored....!
FIXME: multiple comma-separated values should be allowed!"
450 451 452 453 454 455 456 457
  (if isodurationstring
      (save-match-data
        (string-match
         (concat
          "^P[+-]?\\("
          "\\(\\([0-9]+\\)D\\)"         ; days only
          "\\|"
          "\\(\\(\\([0-9]+\\)D\\)?T\\(\\([0-9]+\\)H\\)?" ; opt days
458
          "\\(\\([0-9]+\\)M\\)?\\(\\([0-9]+\\)S\\)?\\)"  ; mand. time
459 460 461 462 463 464 465 466 467
          "\\|"
          "\\(\\([0-9]+\\)W\\)"         ; weeks only
          "\\)$") isodurationstring)
        (let ((seconds 0)
              (minutes 0)
              (hours 0)
              (days 0)
              (months 0)
              (years 0))
468 469 470 471 472
          (cond
           ((match-beginning 2)         ;days only
            (setq days (read (substring isodurationstring
                                        (match-beginning 3)
                                        (match-end 3))))
473
            (when duration-correction
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
              (setq days (1- days))))
           ((match-beginning 4)         ;days and time
            (if (match-beginning 5)
                (setq days (* 7 (read (substring isodurationstring
                                                 (match-beginning 6)
                                                 (match-end 6))))))
            (if (match-beginning 7)
                (setq hours (read (substring isodurationstring
                                             (match-beginning 8)
                                             (match-end 8)))))
            (if (match-beginning 9)
                (setq minutes (read (substring isodurationstring
                                               (match-beginning 10)
                                               (match-end 10)))))
            (if (match-beginning 11)
                (setq seconds (read (substring isodurationstring
                                               (match-beginning 12)
491
                                               (match-end 12))))))
492 493 494
           ((match-beginning 13)        ;weeks only
            (setq days (* 7 (read (substring isodurationstring
                                             (match-beginning 14)
495
                                             (match-end 14)))))))
496
          (list seconds minutes hours days months years)))
497 498 499
    ;; isodatetimestring == nil
    nil))

500
(defun icalendar--add-decoded-times (time1 time2)
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
  "Add TIME1 to TIME2.
Both times must be given in decoded form.  One of these times must be
valid (year > 1900 or something)."
  ;; FIXME: does this function exist already?
  (decode-time (encode-time
                (+ (nth 0 time1) (nth 0 time2))
                (+ (nth 1 time1) (nth 1 time2))
                (+ (nth 2 time1) (nth 2 time2))
                (+ (nth 3 time1) (nth 3 time2))
                (+ (nth 4 time1) (nth 4 time2))
                (+ (nth 5 time1) (nth 5 time2))
                nil
                nil
                ;;(or (nth 6 time1) (nth 6 time2)) ;; FIXME?
                )))

517
(defun icalendar--datetime-to-noneuropean-date (datetime &optional separator)
518
  "Convert the decoded DATETIME to non-european-style format.
519 520 521
Optional argument SEPARATOR gives the separator between month,
day, and year.  If nil a blank character is used as separator.
Non-European format: \"month day year\"."
522
  (if datetime
523 524 525 526 527
      (format "%d%s%d%s%d" (nth 4 datetime) ;month
              (or separator " ")
              (nth 3 datetime)          ;day
              (or separator " ")
              (nth 5 datetime))         ;year
528 529 530
    ;; datetime == nil
    nil))

531
(defun icalendar--datetime-to-european-date (datetime &optional separator)
532
  "Convert the decoded DATETIME to European format.
533 534
Optional argument SEPARATOR gives the separator between month,
day, and year.  If nil a blank character is used as separator.
535 536 537
European format: (day month year).
FIXME"
  (if datetime
538 539
      (format "%d%s%d%s%d" (nth 3 datetime) ;day
              (or separator " ")
540
              (nth 4 datetime)            ;month
541
              (or separator " ")
542
              (nth 5 datetime))           ;year
543 544 545
    ;; datetime == nil
    nil))

546 547 548 549 550 551 552 553 554 555
(defun icalendar--datetime-to-diary-date (datetime &optional separator)
  "Convert the decoded DATETIME to diary format.
Optional argument SEPARATOR gives the separator between month,
day, and year.  If nil a blank character is used as separator.
Call icalendar--datetime-to-(non)-european-date according to
value of `european-calendar-style'."
  (if european-calendar-style
      (icalendar--datetime-to-european-date datetime separator)
    (icalendar--datetime-to-noneuropean-date datetime separator)))

556
(defun icalendar--datetime-to-colontime (datetime)
557 558 559 560
  "Extract the time part of a decoded DATETIME into 24-hour format.
Note that this silently ignores seconds."
  (format "%02d:%02d" (nth 2 datetime) (nth 1 datetime)))

561
(defun icalendar--get-month-number (monthname)
562
  "Return the month number for the given MONTHNAME."
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
  (catch 'found
    (let ((num 1)
          (m (downcase monthname)))
      (mapc (lambda (month)
              (let ((mm (downcase month)))
                (if (or (string-equal mm m)
                        (string-equal (substring mm 0 3) m))
                    (throw 'found num))
                (setq num (1+ num))))
            calendar-month-name-array))
    ;; Error:
    -1))

(defun icalendar--get-weekday-number (abbrevweekday)
  "Return the number for the ABBREVWEEKDAY."
578 579 580 581 582 583 584 585 586 587
  (if abbrevweekday
      (catch 'found
        (let ((num 0)
              (aw (downcase abbrevweekday)))
          (mapc (lambda (day)
                  (let ((d (downcase day)))
                    (if (string-equal d aw)
                        (throw 'found num))
                    (setq num (1+ num))))
                icalendar--weekday-array)))
588 589
    ;; Error:
    -1))
590

591
(defun icalendar--get-weekday-abbrev (weekday)
592
  "Return the abbreviated WEEKDAY."
593 594 595 596 597 598 599 600 601 602 603
  (catch 'found
    (let ((num 0)
          (w (downcase weekday)))
      (mapc (lambda (day)
              (let ((d (downcase day)))
                (if (or (string-equal d w)
                        (string-equal (substring d 0 3) w))
                    (throw 'found (aref icalendar--weekday-array num)))
                (setq num (1+ num))))
            calendar-day-name-array))
    ;; Error:
604 605 606 607 608 609 610 611 612 613 614
    nil))

(defun icalendar--date-to-isodate (date &optional day-shift)
  "Convert DATE to iso-style date.
DATE must be a list of the form (month day year).
If DAY-SHIFT is non-nil, the result is shifted by DAY-SHIFT days."
  (let ((mdy (calendar-gregorian-from-absolute
              (+ (calendar-absolute-from-gregorian date)
                 (or day-shift 0)))))
    (format "%04d%02d%02d" (nth 2 mdy) (nth 0 mdy) (nth 1 mdy))))

615

616
(defun icalendar--datestring-to-isodate (datestring &optional day-shift)
617 618 619 620 621 622
  "Convert diary-style DATESTRING to iso-style date.
If DAY-SHIFT is non-nil, the result is shifted by DAY-SHIFT days
-- DAY-SHIFT must be either nil or an integer.  This function
takes care of european-style."
  (let ((day -1) month year)
    (save-match-data
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
      (cond ( ;; numeric date
             (string-match (concat "\\s-*"
                                   "0?\\([1-9][0-9]?\\)[ \t/]\\s-*"
                                   "0?\\([1-9][0-9]?\\),?[ \t/]\\s-*"
                                   "\\([0-9]\\{4\\}\\)")
                           datestring)
             (setq day (read (substring datestring (match-beginning 1)
                                        (match-end 1))))
             (setq month (read (substring datestring (match-beginning 2)
                                          (match-end 2))))
             (setq year (read (substring datestring (match-beginning 3)
                                         (match-end 3))))
             (unless european-calendar-style
               (let ((x month))
                 (setq month day)
                 (setq day x))))
            ( ;; date contains month names -- european-style
640 641 642 643 644
             (string-match (concat "\\s-*"
                                   "0?\\([123]?[0-9]\\)[ \t/]\\s-*"
                                   "\\([A-Za-z][^ ]+\\)[ \t/]\\s-*"
                                   "\\([0-9]\\{4\\}\\)")
                           datestring)
645 646 647 648 649 650 651 652
             (setq day (read (substring datestring (match-beginning 1)
                                        (match-end 1))))
             (setq month (icalendar--get-month-number
                          (substring datestring (match-beginning 2)
                                     (match-end 2))))
             (setq year (read (substring datestring (match-beginning 3)
                                         (match-end 3)))))
            ( ;; date contains month names -- non-european-style
653 654 655 656 657
             (string-match (concat "\\s-*"
                                   "\\([A-Za-z][^ ]+\\)[ \t/]\\s-*"
                                   "0?\\([123]?[0-9]\\),?[ \t/]\\s-*"
                                   "\\([0-9]\\{4\\}\\)")
                           datestring)
658 659 660 661 662 663 664 665 666
             (setq day (read (substring datestring (match-beginning 2)
                                        (match-end 2))))
             (setq month (icalendar--get-month-number
                          (substring datestring (match-beginning 1)
                                     (match-end 1))))
             (setq year (read (substring datestring (match-beginning 3)
                                         (match-end 3)))))
            (t
             nil)))
667
    (if (> day 0)
668 669
        (let ((mdy (calendar-gregorian-from-absolute
                    (+ (calendar-absolute-from-gregorian (list month day
670
                                                               year))
671 672
                       (or day-shift 0)))))
          (format "%04d%02d%02d" (nth 2 mdy) (nth 0 mdy) (nth 1 mdy)))
673 674
      nil)))

675
(defun icalendar--diarytime-to-isotime (timestring ampmstring)
676 677 678 679
  "Convert a a time like 9:30pm to an iso-conform string like T213000.
In this example the TIMESTRING would be \"9:30\" and the AMPMSTRING
would be \"pm\"."
  (if timestring
680
      (let ((starttimenum (read (icalendar--rris ":" "" timestring))))
681 682 683 684 685 686
        ;; take care of am/pm style
        (if (and ampmstring (string= "pm" ampmstring))
            (setq starttimenum (+ starttimenum 1200)))
        (format "T%04d00" starttimenum))
    nil))

687 688 689
(defun icalendar--convert-string-for-export (string)
  "Escape comma and other critical characters in STRING."
  (icalendar--rris "," "\\\\," string))
690

691
(defun icalendar--convert-string-for-import (string)
692
  "Remove escape chars for comma, semicolon etc. from STRING."
693 694 695 696 697
  (icalendar--rris
   "\\\\n" "\n " (icalendar--rris
                  "\\\\\"" "\"" (icalendar--rris
                                 "\\\\;" ";" (icalendar--rris
                                              "\\\\," "," string)))))
698 699

;; ======================================================================
700
;; Export -- convert emacs-diary to icalendar
701 702
;; ======================================================================

703
;;;###autoload
704 705 706 707
(defun icalendar-export-file (diary-filename ical-filename)
  "Export diary file to iCalendar format.
All diary entries in the file DIARY-FILENAME are converted to iCalendar
format.  The result is appended to the file ICAL-FILENAME."
708
  (interactive "FExport diary data from file: 
709
Finto iCalendar file: ")
710 711 712 713 714
  (save-current-buffer
    (set-buffer (find-file diary-filename))
    (icalendar-export-region (point-min) (point-max) ical-filename)))

(defalias 'icalendar-convert-diary-to-ical 'icalendar-export-file)
715
(make-obsolete 'icalendar-convert-diary-to-ical 'icalendar-export-file)
716

717
;;;###autoload
718 719 720 721
(defun icalendar-export-region (min max ical-filename)
  "Export region in diary file to iCalendar format.
All diary entries in the region from MIN to MAX in the current buffer are
converted to iCalendar format.  The result is appended to the file
722
ICAL-FILENAME.
723 724 725
This function attempts to return t if something goes wrong.  In this
case an error string which describes all the errors and problems is
written into the buffer `*icalendar-errors*'."
726 727
  (interactive "r
FExport diary data into iCalendar file: ")
728 729 730 731 732
  (let ((result "")
        (start 0)
        (entry-main "")
        (entry-rest "")
        (header "")
733
        (contents-n-summary)
734
        (contents)
735
        (found-error nil)
736
        (nonmarker (concat "^" (regexp-quote diary-nonmarking-symbol)
737 738
                           "?"))
        (other-elements nil))
739 740
    ;; prepare buffer with error messages
    (save-current-buffer
741
      (set-buffer (get-buffer-create "*icalendar-errors*"))
742
      (erase-buffer))
743

744
    ;; here we go
745 746
    (save-excursion
      (goto-char min)
747
      (while (re-search-forward
748
              "^\\([^ \t\n].+\\)\\(\\(\n[ \t].*\\)*\\)" max t)
749 750 751 752 753 754 755 756
        (setq entry-main (match-string 1))
        (if (match-beginning 2)
            (setq entry-rest (match-string 2))
          (setq entry-rest ""))
        (setq header (format "\nBEGIN:VEVENT\nUID:emacs%d%d%d"
                             (car (current-time))
                             (cadr (current-time))
                             (car (cddr (current-time)))))
757 758
        (condition-case error-val
            (progn
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
              (setq contents-n-summary
                    (icalendar--convert-to-ical nonmarker entry-main))
              (setq other-elements (icalendar--parse-summary-and-rest
                                    (concat entry-main entry-rest)))
              (setq contents (concat (car contents-n-summary)
                                     "\nSUMMARY:" (cadr contents-n-summary)))
              (let ((cla (cdr (assoc 'cla other-elements)))
                    (des (cdr (assoc 'des other-elements)))
                    (loc (cdr (assoc 'loc other-elements)))
                    (org (cdr (assoc 'org other-elements)))
                    (sta (cdr (assoc 'sta other-elements)))
                    (sum (cdr (assoc 'sum other-elements)))
                    (url (cdr (assoc 'url other-elements))))
                (if cla
                    (setq contents (concat contents "\nCLASS:" cla)))
                (if des
                    (setq contents (concat contents "\nDESCRIPTION:" des)))
                (if loc
                    (setq contents (concat contents "\nLOCATION:" loc)))
                (if org
                    (setq contents (concat contents "\nORGANIZER:" org)))
                (if sta
                    (setq contents (concat contents "\nSTATUS:" sta)))
                ;;(if sum
                ;;    (setq contents (concat contents "\nSUMMARY:" sum)))
                (if url
                    (setq contents (concat contents "\nURL:" url))))
786 787 788 789 790
              (setq result (concat result header contents "\nEND:VEVENT")))
          ;; handle errors
          (error
           (setq found-error t)
           (save-current-buffer
791
             (set-buffer (get-buffer-create "*icalendar-errors*"))
792 793 794 795 796
             (insert (format "Error in line %d -- %s: `%s'\n"
                             (count-lines (point-min) (point))
                             (cadr error-val)
                             entry-main))))))

797
      ;; we're done, insert everything into the file
798
      (save-current-buffer
799
        (let ((coding-system-for-write 'utf-8))
800 801 802 803 804 805 806 807
          (set-buffer (find-file ical-filename))
          (goto-char (point-max))
          (insert "BEGIN:VCALENDAR")
          (insert "\nPRODID:-//Emacs//NONSGML icalendar.el//EN")
          (insert "\nVERSION:2.0")
          (insert result)
          (insert "\nEND:VCALENDAR\n")
          ;; save the diary file
808 809 810
          (save-buffer)
          (unless found-error
            (bury-buffer)))))
811
    found-error))
812

813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
(defun icalendar--convert-to-ical (nonmarker entry-main)
  "Convert a diary entry to icalendar format.
NONMARKER is a regular expression matching the start of non-marking
entries.  ENTRY-MAIN is the first line of the diary entry."
  (or
   ;; anniversaries -- %%(diary-anniversary ...)
   (icalendar--convert-anniversary-to-ical nonmarker entry-main)
   ;; cyclic events -- %%(diary-cyclic ...)
   (icalendar--convert-cyclic-to-ical nonmarker entry-main)
   ;; diary-date -- %%(diary-date ...)
   (icalendar--convert-date-to-ical nonmarker entry-main)
   ;; float events -- %%(diary-float ...)
   (icalendar--convert-float-to-ical nonmarker entry-main)
   ;; block events -- %%(diary-block ...)
   (icalendar--convert-block-to-ical nonmarker entry-main)
   ;; other sexp diary entries
   (icalendar--convert-sexp-to-ical nonmarker entry-main)
   ;; weekly by day -- Monday 8:30 Team meeting
   (icalendar--convert-weekly-to-ical nonmarker entry-main)
   ;; yearly by day -- 1 May Tag der Arbeit
   (icalendar--convert-yearly-to-ical nonmarker entry-main)
   ;; "ordinary" events, start and end time given
   ;; 1 Feb 2003 blah
   (icalendar--convert-ordinary-to-ical nonmarker entry-main)
   ;; everything else
   ;; Oops! what's that?
   (error "Could not parse entry")))

(defun icalendar--parse-summary-and-rest (summary-and-rest)
  "Parse SUMMARY-AND-REST from a diary to fill iCalendar properties."
  (save-match-data
    (let* ((s icalendar-import-format)
           (p-cla (or (string-match "%c" icalendar-import-format) -1))
           (p-des (or (string-match "%d" icalendar-import-format) -1))
           (p-loc (or (string-match "%l" icalendar-import-format) -1))
           (p-org (or (string-match "%o" icalendar-import-format) -1))
           (p-sum (or (string-match "%s" icalendar-import-format) -1))
           (p-sta (or (string-match "%t" icalendar-import-format) -1))
           (p-url (or (string-match "%u" icalendar-import-format) -1))
           (p-list (sort (list p-cla p-des p-loc p-org p-sta p-sum p-url) '<))
           pos-cla pos-des pos-loc pos-org pos-sta pos-sum pos-url)
      (dotimes (i (length p-list))
        (cond ((and (>= p-cla 0) (= (nth i p-list) p-cla))
               (setq pos-cla (+ 2 (* 2 i))))
              ((and (>= p-des 0) (= (nth i p-list) p-des))
               (setq pos-des (+ 2 (* 2 i))))
              ((and (>= p-loc 0) (= (nth i p-list) p-loc))
               (setq pos-loc (+ 2 (* 2 i))))
              ((and (>= p-org 0) (= (nth i p-list) p-org))
               (setq pos-org (+ 2 (* 2 i))))
              ((and (>= p-sta 0) (= (nth i p-list) p-sta))
               (setq pos-sta (+ 2 (* 2 i))))
              ((and (>= p-sum 0) (= (nth i p-list) p-sum))
               (setq pos-sum (+ 2 (* 2 i))))
              ((and (>= p-url 0) (= (nth i p-list) p-url))
               (setq pos-url (+ 2 (* 2 i))))))
      (mapc (lambda (ij)
              (setq s (icalendar--rris (car ij) (cadr ij) s t t)))
            (list
             ;; summary must be first! because of %s
             (list "%s"
                   (concat "\\(" icalendar-import-format-summary "\\)?"))
             (list "%c"
                   (concat "\\(" icalendar-import-format-class "\\)?"))
             (list "%d"
                   (concat "\\(" icalendar-import-format-description "\\)?"))
             (list "%l"
                   (concat "\\(" icalendar-import-format-location "\\)?"))
             (list "%o"
                   (concat "\\(" icalendar-import-format-organizer "\\)?"))
             (list "%t"
                   (concat "\\(" icalendar-import-format-status "\\)?"))
             (list "%u"
                   (concat "\\(" icalendar-import-format-url "\\)?"))))
      (setq s (concat (icalendar--rris "%s" "\\(.*\\)" s nil t) " "))
      (if (string-match s summary-and-rest)
          (let (cla des loc org sta sum url)
            (if (and pos-sum (match-beginning pos-sum))
                (setq sum (substring summary-and-rest
                                     (match-beginning pos-sum)
                                     (match-end pos-sum))))
            (if (and pos-cla (match-beginning pos-cla))
                (setq cla (substring summary-and-rest
                                     (match-beginning pos-cla)
                                     (match-end pos-cla))))
            (if (and pos-des (match-beginning pos-des))
                (setq des (substring summary-and-rest
                                     (match-beginning pos-des)
                                     (match-end pos-des))))
            (if (and pos-loc (match-beginning pos-loc))
                (setq loc (substring summary-and-rest
                                     (match-beginning pos-loc)
                                     (match-end pos-loc))))
            (if (and pos-org (match-beginning pos-org))
                (setq org (substring summary-and-rest
                                     (match-beginning pos-org)
                                     (match-end pos-org))))
            (if (and pos-sta (match-beginning pos-sta))
                (setq sta (substring summary-and-rest
                                     (match-beginning pos-sta)
                                     (match-end pos-sta))))
            (if (and pos-url (match-beginning pos-url))
                (setq url (substring summary-and-rest
                                     (match-beginning pos-url)
                                     (match-end pos-url))))
            (list (if cla (cons 'cla cla) nil)
                  (if des (cons 'des des) nil)
                  (if loc (cons 'loc loc) nil)
                  (if org (cons 'org org) nil)
                  (if sta (cons 'sta sta) nil)
                  ;;(if sum (cons 'sum sum) nil)
                  (if url (cons 'url url) nil)))))))

;; subroutines for icalendar-export-region
927 928 929 930 931 932 933 934 935 936
(defun icalendar--convert-ordinary-to-ical (nonmarker entry-main)
  "Convert \"ordinary\" diary entry to icalendar format.
NONMARKER is a regular expression matching the start of non-marking
entries.  ENTRY-MAIN is the first line of the diary entry."
  (if (string-match (concat nonmarker
                            "\\([^ /]+[ /]+[^ /]+[ /]+[^ ]+\\)\\s-*"
                            "\\(0?\\([1-9][0-9]?:[0-9][0-9]\\)\\([ap]m\\)?"
                            "\\("
                            "-0?\\([1-9][0-9]?:[0-9][0-9]\\)\\([ap]m\\)?\\)?"
                            "\\)?"
937
                            "\\s-*\\(.*?\\) ?$")
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
                    entry-main)
      (let* ((datetime (substring entry-main (match-beginning 1)
                                  (match-end 1)))
             (startisostring (icalendar--datestring-to-isodate
                              datetime))
             (endisostring (icalendar--datestring-to-isodate
                            datetime 1))
             (starttimestring (icalendar--diarytime-to-isotime
                               (if (match-beginning 3)
                                   (substring entry-main
                                              (match-beginning 3)
                                              (match-end 3))
                                 nil)
                               (if (match-beginning 4)
                                   (substring entry-main
                                              (match-beginning 4)
                                              (match-end 4))
                                 nil)))
             (endtimestring (icalendar--diarytime-to-isotime
                             (if (match-beginning 6)
                                 (substring entry-main
                                            (match-beginning 6)
                                            (match-end 6))
                               nil)
                             (if (match-beginning 7)
                                 (substring entry-main
                                            (match-beginning 7)
                                            (match-end 7))
                               nil)))
             (summary (icalendar--convert-string-for-export
                       (substring entry-main (match-beginning 8)
                                  (match-end 8)))))
        (icalendar--dmsg "ordinary %s" entry-main)

        (unless startisostring
          (error "Could not parse date"))
        (when starttimestring
          (unless endtimestring
            (let ((time
                   (read (icalendar--rris "^T0?" ""
                                          starttimestring))))
              (setq endtimestring (format "T%06d"
                                          (+ 10000 time))))))
981 982 983 984 985 986 987 988 989 990 991 992 993
        (list (concat "\nDTSTART;"
                      (if starttimestring "VALUE=DATE-TIME:"
                        "VALUE=DATE:")
                      startisostring
                      (or starttimestring "")
                      "\nDTEND;"
                      (if endtimestring "VALUE=DATE-TIME:"
                        "VALUE=DATE:")
                      (if starttimestring
                          startisostring
                        endisostring)
                      (or endtimestring ""))
              summary))
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
    ;; no match
    nil))

(defun icalendar--convert-weekly-to-ical (nonmarker entry-main)
  "Convert weekly diary entry to icalendar format.
NONMARKER is a regular expression matching the start of non-marking
entries.  ENTRY-MAIN is the first line of the diary entry."
  (if (and (string-match (concat nonmarker
                                 "\\([a-z]+\\)\\s-+"
                                 "\\(0?\\([1-9][0-9]?:[0-9][0-9]\\)"
                                 "\\([ap]m\\)?"
                                 "\\(-0?"
                                 "\\([1-9][0-9]?:[0-9][0-9]\\)"
                                 "\\([ap]m\\)?\\)?"
                                 "\\)?"
1009
                                 "\\s-*\\(.*?\\) ?$")
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
                         entry-main)
           (icalendar--get-weekday-abbrev
            (substring entry-main (match-beginning 1)
                       (match-end 1))))
      (let* ((day (icalendar--get-weekday-abbrev
                   (substring entry-main (match-beginning 1)
                              (match-end 1))))
             (starttimestring (icalendar--diarytime-to-isotime
                               (if (match-beginning 3)
                                   (substring entry-main
                                              (match-beginning 3)
                                              (match-end 3))
                                 nil)
                               (if (match-beginning 4)
                                   (substring entry-main
                                              (match-beginning 4)
                                              (match-end 4))
                                 nil)))
             (endtimestring (icalendar--diarytime-to-isotime
                             (if (match-beginning 6)
                                 (substring entry-main
                                            (match-beginning 6)
                                            (match-end 6))
                               nil)
                             (if (match-beginning 7)
                                 (substring entry-main
                                            (match-beginning 7)
                                            (match-end 7))
                               nil)))
             (summary (icalendar--convert-string-for-export
                       (substring entry-main (match-beginning 8)
                                  (match-end 8)))))
        (icalendar--dmsg "weekly %s" entry-main)

        (when starttimestring
          (unless endtimestring
            (let ((time (read
                         (icalendar--rris "^T0?" ""
                                          starttimestring))))
              (setq endtimestring (format "T%06d"
                                          (+ 10000 time))))))
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
        (list (concat "\nDTSTART;"
                      (if starttimestring
                          "VALUE=DATE-TIME:"
                        "VALUE=DATE:")
                      ;; find the correct week day,
                      ;; 1st january 2000 was a saturday
                      (format
                       "200001%02d"
                       (+ (icalendar--get-weekday-number day) 2))
                      (or starttimestring "")
                      "\nDTEND;"
                      (if endtimestring
                          "VALUE=DATE-TIME:"
                        "VALUE=DATE:")
                      (format
                       "200001%02d"
                       ;; end is non-inclusive!
                       (+ (icalendar--get-weekday-number day)
                          (if endtimestring 2 3)))
                      (or endtimestring "")
                      "\nRRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY="
                      day)
              summary))
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
    ;; no match
    nil))

(defun icalendar--convert-yearly-to-ical (nonmarker entry-main)
  "Convert yearly diary entry to icalendar format.
NONMARKER is a regular expression matching the start of non-marking
entries.  ENTRY-MAIN is the first line of the diary entry."
  (if (string-match (concat nonmarker
                            (if european-calendar-style
                                "0?\\([1-9]+[0-9]?\\)\\s-+\\([a-z]+\\)\\s-+"
                              "\\([a-z]+\\)\\s-+0?\\([1-9]+[0-9]?\\)\\s-+")
                            "\\*?\\s-*"
                            "\\(0?\\([1-9][0-9]?:[0-9][0-9]\\)\\([ap]m\\)?"
                            "\\("
                            "-0?\\([1-9][0-9]?:[0-9][0-9]\\)\\([ap]m\\)?\\)?"
                            "\\)?"
1090
                            "\\s-*\\([^0-9]+.*?\\) ?$" ; must not match years
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
                            )
                    entry-main)
      (let* ((daypos (if european-calendar-style 1 2))
             (monpos (if european-calendar-style 2 1))
             (day (read (substring entry-main
                                   (match-beginning daypos)
                                   (match-end daypos))))
             (month (icalendar--get-month-number
                     (substring entry-main
                                (match-beginning monpos)
                                (match-end monpos))))
             (starttimestring (icalendar--diarytime-to-isotime
                               (if (match-beginning 4)
                                   (substring entry-main
                                              (match-beginning 4)
                                              (match-end 4))
                                 nil)
                               (if (match-beginning 5)
                                   (substring entry-main
                                              (match-beginning 5)
                                              (match-end 5))
                                 nil)))
             (endtimestring (icalendar--diarytime-to-isotime
                             (if (match-beginning 7)
                                 (substring entry-main
                                            (match-beginning 7)
                                            (match-end 7))
                               nil)
                             (if (match-beginning 8)
                                 (substring entry-main
                                            (match-beginning 8)
                                            (match-end 8))
                               nil)))
             (summary (icalendar--convert-string-for-export
                       (substring entry-main (match-beginning 9)
                                  (match-end 9)))))
        (icalendar--dmsg "yearly %s" entry-main)

        (when starttimestring
          (unless endtimestring
            (let ((time (read
                         (icalendar--rris "^T0?" ""
                                          starttimestring))))
              (setq endtimestring (format "T%06d"
                                          (+ 10000 time))))))
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
        (list (concat "\nDTSTART;"
                      (if starttimestring "VALUE=DATE-TIME:"
                        "VALUE=DATE:")
                      (format "1900%02d%02d" month day)
                      (or starttimestring "")
                      "\nDTEND;"
                      (if endtimestring "VALUE=DATE-TIME:"
                        "VALUE=DATE:")
                      ;; end is not included! shift by one day
                      (icalendar--date-to-isodate
                       (list month day 1900)
                       (if endtimestring 0 1))
                      (or endtimestring "")
                      "\nRRULE:FREQ=YEARLY;INTERVAL=1;BYMONTH="
                      (format "%2d" month)
                      ";BYMONTHDAY="
                      (format "%2d" day))
              summary))
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
    ;; no match
    nil))

(defun icalendar--convert-sexp-to-ical (nonmarker entry-main)
  "Convert complex sexp diary entry to icalendar format -- unsupported!

FIXME!

NONMARKER is a regular expression matching the start of non-marking
entries.  ENTRY-MAIN is the first line of the diary entry."
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
  (cond ((string-match (concat nonmarker
                               "%%(and \\(([^)]+)\\))\\(\\s-*.*?\\) ?$")
                       entry-main)
         ;; simple sexp entry as generated by icalendar.el: strip off the
         ;; unnecessary (and)
         (icalendar--dmsg "diary-sexp from icalendar.el %s" entry-main)
         (icalendar--convert-to-ical
          nonmarker
          (concat "%%"
                  (substring entry-main (match-beginning 1) (match-end 1))
                  (substring entry-main (match-beginning 2) (match-end 2)))))
        ((string-match (concat nonmarker
                               "%%([^)]+)\\s-*.*")
                       entry-main)
         (icalendar--dmsg "diary-sexp %s" entry-main)
         (error "Sexp-entries are not supported yet"))
        (t
         ;; no match
         nil)))
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194

(defun icalendar--convert-block-to-ical (nonmarker entry-main)
  "Convert block diary entry to icalendar format.
NONMARKER is a regular expression matching the start of non-marking
entries.  ENTRY-MAIN is the first line of the diary entry."
  (if (string-match (concat nonmarker
                            "%%(diary-block \\([^ /]+[ /]+[^ /]+[ /]+[^ ]+\\)"
                            " +\\([^ /]+[ /]+[^ /]+[ /]+[^ ]+\\))\\s-*"
                            "\\(0?\\([1-9][0-9]?:[0-9][0-9]\\)\\([ap]m\\)?"
                            "\\("
                            "-0?\\([1-9][0-9]?:[0-9][0-9]\\)\\([ap]m\\)?\\)?"
                            "\\)?"
1195
                            "\\s-*\\(.*?\\) ?$")
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
                    entry-main)
      (let* ((startstring (substring entry-main
                                     (match-beginning 1)
                                     (match-end 1)))
             (endstring (substring entry-main
                                   (match-beginning 2)
                                   (match-end 2)))
             (startisostring (icalendar--datestring-to-isodate
                              startstring))
             (endisostring (icalendar--datestring-to-isodate
                            endstring))
             (endisostring+1 (icalendar--datestring-to-isodate
                              endstring 1))
             (starttimestring (icalendar--diarytime-to-isotime
                               (if (match-beginning 4)
                                   (substring entry-main
                                              (match-beginning 4)
                                              (match-end 4))
                                 nil)
                               (if (match-beginning 5)
                                   (substring entry-main
                                              (match-beginning 5)
                                              (match-end 5))
                                 nil)))
             (endtimestring (icalendar--diarytime-to-isotime
                             (if (match-beginning 7)
                                 (substring entry-main
                                            (match-beginning 7)
                                            (match-end 7))
                               nil)
                             (if (match-beginning 8)
                                 (substring entry-main
                                            (match-beginning 8)
                                            (match-end 8))
                               nil)))
             (summary (icalendar--convert-string-for-export
                       (substring entry-main (match-beginning 9)
                                  (match-end 9)))))
        (icalendar--dmsg "diary-block %s" entry-main)
        (when starttimestring
          (unless endtimestring
            (let ((time
                   (read (icalendar--rris "^T0?" ""
                                          starttimestring))))
              (setq endtimestring (format "T%06d"
                                          (+ 10000 time))))))
        (if starttimestring
            ;; with time -> write rrule
1244 1245 1246 1247 1248 1249 1250 1251 1252
            (list (concat "\nDTSTART;VALUE=DATE-TIME:"
                          startisostring
                          starttimestring
                          "\nDTEND;VALUE=DATE-TIME:"
                          startisostring
                          endtimestring
                          "\nRRULE:FREQ=DAILY;INTERVAL=1;UNTIL="
                          endisostring)
                  summary)
1253
          ;; no time -> write long event
1254 1255 1256
          (list (concat "\nDTSTART;VALUE=DATE:" startisostring
                        "\nDTEND;VALUE=DATE:" endisostring+1)
                summary)))
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
    ;; no match
    nil))

(defun icalendar--convert-float-to-ical (nonmarker entry-main)
  "Convert float diary entry to icalendar format -- unsupported!

FIXME!

NONMARKER is a regular expression matching the start of non-marking
entries.  ENTRY-MAIN is the first line of the diary entry."
  (if (string-match (concat nonmarker
1268
                            "%%(diary-float \\([^)]+\\))\\s-*\\(.*?\\) ?$")
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
                    entry-main)
      (progn
        (icalendar--dmsg "diary-float %s" entry-main)
        (error "`diary-float' is not supported yet"))
    ;; no match
    nil))

(defun icalendar--convert-date-to-ical (nonmarker entry-main)
  "Convert `diary-date' diary entry to icalendar format -- unsupported!

FIXME!

NONMARKER is a regular expression matching the start of non-marking
entries.  ENTRY-MAIN is the first line of the diary entry."
  (if (string-match (concat nonmarker
1284
                            "%%(diary-date \\([^)]+\\))\\s-*\\(.*?\\) ?$")
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
                    entry-main)
      (progn
        (icalendar--dmsg "diary-date %s" entry-main)
        (error "`diary-date' is not supported yet"))
    ;; no match
    nil))

(defun icalendar--convert-cyclic-to-ical (nonmarker entry-main)
  "Convert `diary-cyclic' diary entry to icalendar format.
NONMARKER is a regular expression matching the start of non-marking
entries.  ENTRY-MAIN is the first line of the diary entry."
  (if (string-match (concat nonmarker
                            "%%(diary-cyclic \\([^ ]+\\) +"
                            "\\([^ /]+[ /]+[^ /]+[ /]+[^ ]+\\))\\s-*"
                            "\\(0?\\([1-9][0-9]?:[0-9][0-9]\\)\\([ap]m\\)?"
                            "\\("
                            "-0?\\([1-9][0-9]?:[0-9][0-9]\\)\\([ap]m\\)?\\)?"
                            "\\)?"
1303
                            "\\s-*\\(.*?\\) ?$")
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
                    entry-main)
      (let* ((frequency (substring entry-main (match-beginning 1)
                                   (match-end 1)))
             (datetime (substring entry-main (match-beginning 2)
                                  (match-end 2)))
             (startisostring (icalendar--datestring-to-isodate
                              datetime))
             (endisostring (icalendar--datestring-to-isodate
                            datetime))
             (endisostring+1 (icalendar--datestring-to-isodate
                              datetime 1))
             (starttimestring (icalendar--diarytime-to-isotime
                               (if (match-beginning 4)
                                   (substring entry-main
                                              (match-beginning 4)
                                              (match-end 4))
                                 nil)
                               (if (match-beginning 5)
                                   (substring entry-main
                                              (match-beginning 5)
                                              (match-end 5))
                                 nil)))
             (endtimestring (icalendar--diarytime-to-isotime
                             (if (match-beginning 7)
                                 (substring entry-main
                                            (match-beginning 7)
                                            (match-end 7))
                               nil)
                             (if (match-beginning 8)
                                 (substring entry-main
                                            (match-beginning 8)
                                            (match-end 8))
                               nil)))
             (summary (icalendar--convert-string-for-export
                       (substring entry-main (match-beginning 9)
                                  (match-end 9)))))
        (icalendar--dmsg "diary-cyclic %s" entry-main)
        (when starttimestring
          (unless endtimestring
            (let ((time
                   (read (icalendar--rris "^T0?" ""
                                          starttimestring))))
              (setq endtimestring (format "T%06d"
                                          (+ 10000 time))))))
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
        (list (concat "\nDTSTART;"
                      (if starttimestring "VALUE=DATE-TIME:"
                        "VALUE=DATE:")
                      startisostring
                      (or starttimestring "")
                      "\nDTEND;"
                      (if endtimestring "VALUE=DATE-TIME:"
                        "VALUE=DATE:")
                      (if endtimestring endisostring endisostring+1)
                      (or endtimestring "")
                      "\nRRULE:FREQ=DAILY;INTERVAL=" frequency
                      ;; strange: korganizer does not expect
                      ;; BYSOMETHING here...
                      )
              summary))
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
    ;; no match
    nil))

(defun icalendar--convert-anniversary-to-ical (nonmarker entry-main)
  "Convert `diary-anniversary' diary entry to icalendar format.
NONMARKER is a regular expression matching the start of non-marking
entries.  ENTRY-MAIN is the first line of the diary entry."
  (if (string-match (concat nonmarker
                            "%%(diary-anniversary \\([^)]+\\))\\s-*"
                            "\\(0?\\([1-9][0-9]?:[0-9][0-9]\\)\\([ap]m\\)?"
                            "\\("
                            "-0?\\([1-9][0-9]?:[0-9][0-9]\\)\\([ap]m\\)?\\)?"
                            "\\)?"
1376
                            "\\s-*\\(.*?\\) ?$")
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
                    entry-main)
      (let* ((datetime (substring entry-main (match-beginning 1)
                                  (match-end 1)))
             (startisostring (icalendar--datestring-to-isodate
                              datetime))
             (endisostring (icalendar--datestring-to-isodate
                            datetime 1))
             (starttimestring (icalendar--diarytime-to-isotime
                               (if (match-beginning 3)
                                   (substring entry-main
                                              (match-beginning 3)
                                              (match-end 3))
                                 nil)
                               (if (match-beginning 4)
                                   (substring entry-main
                                              (match-beginning 4)
                                              (match-end 4))
                                 nil)))
             (endtimestring (icalendar--diarytime-to-isotime
                             (if (match-beginning 6)
                                 (substring entry-main
                                            (match-beginning 6)
                                            (match-end 6))
                               nil)
                             (if (match-beginning 7)
                                 (substring entry-main
                                            (match-beginning 7)
                                            (match-end 7))
                               nil)))
             (summary (icalendar--convert-string-for-export
                       (substring entry-main (match-beginning 8)
                                  (match-end 8)))))
        (icalendar--dmsg "diary-anniversary %s" entry-main)
        (when starttimestring
          (unless endtimestring
            (let ((time
                   (read (icalendar--rris "^T0?" ""
                                          starttimestring))))
              (setq endtimestring (format "T%06d"
                                          (+ 10000 time))))))
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
        (list (concat "\nDTSTART;"
                      (if starttimestring "VALUE=DATE-TIME:"
                        "VALUE=DATE:")
                      startisostring
                      (or starttimestring "")
                      "\nDTEND;"
                      (if endtimestring "VALUE=DATE-TIME:"
                        "VALUE=DATE:")
                      endisostring
                      (or endtimestring "")
                      "\nRRULE:FREQ=YEARLY;INTERVAL=1"
                      ;; the following is redundant,
                      ;; but korganizer seems to expect this... ;(
                      ;; and evolution doesn't understand it... :(
                      ;; so... who is wrong?!
                      ";BYMONTH="
                      (substring startisostring 4 6)
                      ";BYMONTHDAY="
                      (substring startisostring 6 8))
              summary))
1437 1438 1439
    ;; no match
    nil))

1440
;; ======================================================================
1441
;; Import -- convert icalendar to emacs-diary
1442 1443
;; ======================================================================

1444
;;;###autoload
1445
(defun icalendar-import-file (ical-filename diary-filename
1446
                                            &optional non-marking)
1447
  "Import an iCalendar file and append to a diary file.
1448 1449 1450
Argument ICAL-FILENAME output iCalendar file.
Argument DIARY-FILENAME input `diary-file'.
Optional argument NON-MARKING determines whether events are created as
1451
non-marking or not."
1452
  (interactive "fImport iCalendar data from file: 
1453
Finto diary file: 
1454 1455 1456 1457 1458
p")
  ;; clean up the diary file
  (save-current-buffer
    ;; now load and convert from the ical file
    (set-buffer (find-file ical-filename))
1459
    (icalendar-import-buffer diary-filename t non-marking)))
1460

1461
;;;###autoload
1462 1463
(defun icalendar-import-buffer (&optional diary-file do-not-ask
                                          non-marking)
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
  "Extract iCalendar events from current buffer.

This function searches the current buffer for the first iCalendar
object, reads it and adds all VEVENT elements to the diary
DIARY-FILE.

It will ask for each appointment whether to add it to the diary
when DO-NOT-ASK is non-nil.  When called interactively,
DO-NOT-ASK is set to t, so that you are asked fore each event.

NON-MARKING determines whether diary events are created as
non-marking.

1477 1478 1479
Return code t means that importing worked well, return code nil
means that an error has occured.  Error messages will be in the
buffer `*icalendar-errors*'."
1480 1481 1482 1483
  (interactive)
  (save-current-buffer
    ;; prepare ical
    (message "Preparing icalendar...")
1484
    (set-buffer (icalendar--get-unfolded-buffer (current-buffer)))