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

3 4
;; Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008
;;   Free Software Foundation, Inc.
5

6 7 8
;; Author:         Ulf Jasper <ulf.jasper@web.de>
;; Created:        August 2002
;; Keywords:       calendar
9 10 11 12 13 14
;; 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
15
;; the Free Software Foundation; either version 3, or (at your option)
16 17 18 19 20 21 22 23 24
;; 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
25 26
;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
27 28 29 30 31

;;; Commentary:

;; This package is documented in the Emacs Manual.

32 33 34 35 36 37 38
;;   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.
39 40 41

;;; History:

42
;;  0.07 onwards: see lisp/ChangeLog
43

44 45 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.06:  (2004-10-06)
;;  - Bugfixes regarding icalendar-import-format-*.
;;  - Fix in icalendar-convert-diary-to-ical -- thanks to Philipp Grau.

;;  0.05: (2003-06-19)
;;  - 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: (2003-05-07)
;;  - 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: (2003-03-21)
;;  - First published version.  Trial version.  Alpha version.
74 75 76 77

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

78
;;  * Import from ical to diary:
79
;;    + Need more properties for icalendar-import-format
80 81 82 83
;;      (added all that Mozilla Calendar uses)
;;      From iCal specifications (RFC2445: 4.8.1), icalendar.el lacks
;;      ATTACH, CATEGORIES, COMMENT, GEO, PERCENT-COMPLETE (VTODO),
;;      PRIORITY, RESOURCES) not considering date/time and time-zone
84 85 86 87 88 89 90 91 92
;;    + 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"
93
;;    + timezones probably still need some improvements.
94

95
;;  * Export from diary to ical
96 97 98 99 100 101 102 103 104 105 106 107
;;    + 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:

108
(defconst icalendar-version "0.18"
109 110 111 112 113 114 115 116 117 118 119 120
  "Version number of icalendar.el.")

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

(defcustom icalendar-import-format
  "%s%d%l%o"
121 122 123 124 125
  "Format for importing events from iCalendar into Emacs diary.
It defines how iCalendar events are inserted into diary file.
This may either be a string or a function.

In case of a formatting STRING the following specifiers can be used:
126
%c Class, see `icalendar-import-format-class'
127 128 129
%d Description, see `icalendar-import-format-description'
%l Location, see `icalendar-import-format-location'
%o Organizer, see `icalendar-import-format-organizer'
130 131
%s Summary, see `icalendar-import-format-summary'
%t Status, see `icalendar-import-format-status'
132 133 134 135 136 137 138 139
%u URL, see `icalendar-import-format-url'

A formatting FUNCTION will be called with a VEVENT as its only
argument.  It must return a string.  See
`icalendar-import-format-sample' for an example."
  :type '(choice
          (string :tag "String")
          (function :tag "Function"))
140 141
  :group 'icalendar)

142
(defcustom icalendar-import-format-summary
143
  "%s"
144 145 146
  "Format string defining how the summary element is formatted.
This applies only if the summary is not empty! `%s' is replaced
by the summary."
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
  :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)

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
(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)

198 199 200 201 202 203 204 205 206
(defcustom icalendar-recurring-start-year
  2005
  "Start year for recurring events.
Some calendar browsers only propagate recurring events for
several years beyond the start time.  Set this string to a year
just before the start of your personal calendar."
  :type 'integer
  :group 'icalendar)

207 208 209 210 211 212 213 214 215

(defcustom icalendar-export-hidden-diary-entries
  t
  "Determines whether hidden diary entries are exported.
If non-nil hidden diary entries (starting with `&') get exported,
if nil they are ignored."
  :type 'boolean
  :group 'icalendar)

216 217
(defvar icalendar-debug nil
  "Enable icalendar debug messages.")
218 219 220 221 222

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

223
(defconst icalendar--weekday-array ["SU" "MO" "TU" "WE" "TH" "FR" "SA"])
224 225 226 227 228 229

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

230 231 232 233 234 235 236 237
;; ======================================================================
;; misc
;; ======================================================================
(defun icalendar--dmsg (&rest args)
  "Print message ARGS if `icalendar-debug' is non-nil."
  (if icalendar-debug
      (apply 'message args)))

238 239 240 241 242
;; ======================================================================
;; Core functionality
;; Functions for parsing icalendars, importing and so on
;; ======================================================================

243
(defun icalendar--get-unfolded-buffer (folded-ical-buffer)
244 245 246 247 248 249 250 251 252
  "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)
253 254
      (insert-buffer-substring folded-ical-buffer)
      (goto-char (point-min))
255
      (while (re-search-forward "\r?\n[ \t]" nil t)
256
        (replace-match "" nil nil)))
257 258
    unfolded-buffer))

259
(defsubst icalendar--rris (regexp rep string &optional fixedcase literal)
260
  "Replace regular expression in string.
261 262 263 264 265 266 267 268 269
Pass arguments REGEXP REP STRING FIXEDCASE LITERAL to
`replace-regexp-in-string' (Emacs) or to `replace-in-string' (XEmacs)."
  (cond ((fboundp 'replace-regexp-in-string)
         ;; Emacs:
         (replace-regexp-in-string regexp rep string fixedcase literal))
        ((fboundp 'replace-in-string)
         ;; XEmacs:
         (save-match-data ;; apparently XEmacs needs save-match-data
           (replace-in-string string regexp rep literal)))))
270

271
(defun icalendar--read-element (invalue inparams)
272 273 274 275
  "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
276
it finds."
277 278
  (let (element children line name params param param-name param-value
                value
279
                (continue t))
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
    (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)
307
      (setq value (icalendar--rris "\r?\n[ \t]" "" (match-string 0)))
308 309 310 311
      (setq line (list name params value))
      (cond ((eq name 'BEGIN)
             (setq children
                   (append children
312 313
                           (list (icalendar--read-element (intern value)
                                                          params)))))
314 315 316 317 318 319 320 321 322 323 324 325
            ((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
;; ======================================================================

326 327 328
;;(defsubst icalendar--get-all-event-properties (event)
;;  "Return the list of properties in this EVENT."
;;  (car (cddr event)))
329

330
(defun icalendar--get-event-property (event prop)
331
  "For the given EVENT return the value of the first occurrence of PROP."
332 333 334 335 336 337 338 339 340
  (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))

341
(defun icalendar--get-event-property-attributes (event prop)
342
  "For the given EVENT return attributes of the first occurrence of PROP."
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
  (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)
358
          (setq result (append (split-string (car (cddr pp)) ",") result)))
359 360 361
      (setq props (cdr props)))
    result))

362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
;; (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)
377 378 379 380 381 382 383 384 385 386 387
  "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
388 389 390
                   (mapcar (lambda (n)
                             (icalendar--get-children n name))
                           children))))
391 392 393 394 395 396
        (if subresult
            (if result
                (setq result (append result subresult))
              (setq result subresult)))))
    result))

397 398
                                        ; private
(defun icalendar--all-events (icalendar)
399
  "Return the list of all existing events in the given ICALENDAR."
400
  (icalendar--get-children (car icalendar) 'VEVENT))
401

402
(defun icalendar--split-value (value-string)
403
  "Split VALUE-STRING at ';='."
404 405 406 407
  (let ((result '())
        param-name param-value)
    (when value-string
      (save-current-buffer
408
        (set-buffer (get-buffer-create " *icalendar-work*"))
409 410 411 412 413
        (set-buffer-modified-p nil)
        (erase-buffer)
        (insert value-string)
        (goto-char (point-min))
        (while
414 415 416
            (re-search-forward
             "\\([A-Za-z0-9-]+\\)=\\(\\([^;,:]+\\)\\|\"\\([^\"]+\\)\"\\);?"
             nil t)
417 418 419
          (setq param-name (intern (match-string 1)))
          (setq param-value (match-string 2))
          (setq result
420
                (append result (list (list param-name param-value)))))))
421 422
    result))

423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
(defun icalendar--convert-tz-offset (alist dst-p)
  "Return a cons of two strings representing a timezone start.
ALIST is an alist entry from a VTIMEZONE, like STANDARD.
DST-P is non-nil if this is for daylight savings time.
The strings are suitable for assembling into a TZ variable."
  (let ((offset (car (cddr (assq 'TZOFFSETTO alist))))
	(rrule-value (car (cddr (assq 'RRULE alist))))
	(dtstart (car (cddr (assq 'DTSTART alist)))))
    ;; FIXME: for now we only handle RRULE and not RDATE here.
    (when (and offset rrule-value dtstart)
      (let* ((rrule (icalendar--split-value rrule-value))
	     (freq (cadr (assq 'FREQ rrule)))
	     (bymonth (cadr (assq 'BYMONTH rrule)))
	     (byday (cadr (assq 'BYDAY rrule))))
	;; FIXME: we don't correctly handle WKST here.
	(if (and (string= freq "YEARLY") bymonth)
	    (cons
	     (concat
	      ;; Fake a name.
	      (if dst-p "(DST?)" "(STD?)")
	      ;; For TZ, OFFSET is added to the local time.  So,
	      ;; invert the values.
	      (if (eq (aref offset 0) ?-) "+" "-")
	      (substring offset 1 3)
	      ":"
	      (substring offset 3 5))
	     ;; The start time.
	     (let* ((day (icalendar--get-weekday-number (substring byday -2)))
		    (week (if (eq day -1)
			      byday
			    (substring byday 0 -2))))
	       (concat "M" bymonth "." week "." (if (eq day -1) "0"
						  (int-to-string day))
		       ;; Start time.
		       "/"
		       (substring dtstart -6 -4)
		       ":"
		       (substring dtstart -4 -2)
		       ":"
		       (substring dtstart -2)))))))))

(defun icalendar--parse-vtimezone (alist)
  "Turn a VTIMEZONE ALIST into a cons (ID . TZ-STRING).
Return nil if timezone cannot be parsed."
  (let* ((tz-id (icalendar--get-event-property alist 'TZID))
	 (daylight (cadr (cdar (icalendar--get-children alist 'DAYLIGHT))))
	 (day (and daylight (icalendar--convert-tz-offset daylight t)))
	 (standard (cadr (cdar (icalendar--get-children alist 'STANDARD))))
	 (std (and standard (icalendar--convert-tz-offset standard nil))))
    (if (and tz-id std)
	(cons tz-id
	      (if day
		  (concat (car std) (car day)
			  "," (cdr day) "," (cdr std))
		(car std))))))

(defun icalendar--convert-all-timezones (icalendar)
  "Convert all timezones in the ICALENDAR into an alist.
Each element of the alist is a cons (ID . TZ-STRING),
like `icalendar--parse-vtimezone'."
  (let (result)
    (dolist (zone (icalendar--get-children (car icalendar) 'VTIMEZONE))
      (setq zone (icalendar--parse-vtimezone zone))
      (if zone
	  (setq result (cons zone result))))
    result))

(defun icalendar--find-time-zone (prop-list zone-map)
  "Return a timezone string for the time zone in PROP-LIST, or nil if none.
ZONE-MAP is a timezone alist as returned by `icalendar--convert-all-timezones'."
  (let ((id (plist-get prop-list 'TZID)))
    (if id
	(cdr (assoc id zone-map)))))

(defun icalendar--decode-isodatetime (isodatetimestring &optional day-shift
                                                        zone)
499
  "Return ISODATETIMESTRING in format like `decode-time'.
500 501 502 503 504
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.
505
ZONE, if provided, is the timezone, in any format understood by `encode-time'.
506 507

FIXME: multiple comma-separated values should be allowed!"
508
  (icalendar--dmsg isodatetimestring)
509 510 511 512 513 514 515 516 517
  (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)
518
          ;; hour/minute present
519 520 521
          (setq hour (read (substring isodatetimestring 9 11)))
          (setq minute (read (substring isodatetimestring 11 13))))
        (when (> (length isodatetimestring) 14)
522
          ;; seconds present
523 524
          (setq second (read (substring isodatetimestring 13 15))))
        (when (and (> (length isodatetimestring) 15)
525
                   ;; UTC specifier present
526 527 528
                   (char-equal ?Z (aref isodatetimestring 15)))
          ;; if not UTC add current-time-zone offset
          (setq second (+ (car (current-time-zone)) second)))
529 530 531 532 533 534 535 536 537
        ;; 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))))
538 539 540
        ;; create the decoded date-time
        ;; FIXME!?!
        (condition-case nil
541
            (decode-time (encode-time second minute hour day month year zone))
542 543 544 545 546 547 548
          (error
           (message "Cannot decode \"%s\"" isodatetimestring)
           ;; hope for the best...
           (list second minute hour day month year 0 nil 0))))
    ;; isodatetimestring == nil
    nil))

549 550 551
(defun icalendar--decode-isoduration (isodurationstring
                                      &optional duration-correction)
  "Convert ISODURATIONSTRING into format provided by `decode-time'.
552 553
Converts from ISO-8601 to Emacs representation.  If ISODURATIONSTRING
specifies UTC time (trailing letter Z) the decoded time is given in
554 555
the local time zone!

556 557
Optional argument DURATION-CORRECTION shortens result by one day.

558 559
FIXME: TZID-attributes are ignored....!
FIXME: multiple comma-separated values should be allowed!"
560 561 562 563 564 565 566 567
  (if isodurationstring
      (save-match-data
        (string-match
         (concat
          "^P[+-]?\\("
          "\\(\\([0-9]+\\)D\\)"         ; days only
          "\\|"
          "\\(\\(\\([0-9]+\\)D\\)?T\\(\\([0-9]+\\)H\\)?" ; opt days
568
          "\\(\\([0-9]+\\)M\\)?\\(\\([0-9]+\\)S\\)?\\)"  ; mand. time
569 570 571 572 573 574 575 576 577
          "\\|"
          "\\(\\([0-9]+\\)W\\)"         ; weeks only
          "\\)$") isodurationstring)
        (let ((seconds 0)
              (minutes 0)
              (hours 0)
              (days 0)
              (months 0)
              (years 0))
578 579 580 581 582
          (cond
           ((match-beginning 2)         ;days only
            (setq days (read (substring isodurationstring
                                        (match-beginning 3)
                                        (match-end 3))))
583
            (when duration-correction
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
              (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)
601
                                               (match-end 12))))))
602 603 604
           ((match-beginning 13)        ;weeks only
            (setq days (* 7 (read (substring isodurationstring
                                             (match-beginning 14)
605
                                             (match-end 14)))))))
606
          (list seconds minutes hours days months years)))
607 608 609
    ;; isodatetimestring == nil
    nil))

610
(defun icalendar--add-decoded-times (time1 time2)
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
  "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?
                )))

627 628
(defun icalendar--datetime-to-american-date (datetime &optional separator)
  "Convert the decoded DATETIME to American-style format.
629 630
Optional argument SEPARATOR gives the separator between month,
day, and year.  If nil a blank character is used as separator.
631
American format: \"month day year\"."
632
  (if datetime
633 634 635 636 637
      (format "%d%s%d%s%d" (nth 4 datetime) ;month
              (or separator " ")
              (nth 3 datetime)          ;day
              (or separator " ")
              (nth 5 datetime))         ;year
638 639 640
    ;; datetime == nil
    nil))

641 642 643
(define-obsolete-function-alias 'icalendar--datetime-to-noneuropean-date
  'icalendar--datetime-to-american-date "icalendar 0.19")

644
(defun icalendar--datetime-to-european-date (datetime &optional separator)
645
  "Convert the decoded DATETIME to European format.
646 647
Optional argument SEPARATOR gives the separator between month,
day, and year.  If nil a blank character is used as separator.
648 649 650
European format: (day month year).
FIXME"
  (if datetime
651 652
      (format "%d%s%d%s%d" (nth 3 datetime) ;day
              (or separator " ")
653
              (nth 4 datetime)            ;month
654
              (or separator " ")
655
              (nth 5 datetime))           ;year
656 657 658
    ;; datetime == nil
    nil))

659 660 661 662 663 664 665 666 667 668 669 670 671 672
(defun icalendar--datetime-to-iso-date (datetime &optional separator)
  "Convert the decoded DATETIME to ISO format.
Optional argument SEPARATOR gives the separator between month,
day, and year.  If nil a blank character is used as separator.
ISO format: (year month day)."
  (if datetime
      (format "%d%s%d%s%d" (nth 5 datetime) ;year
              (or separator " ")
              (nth 4 datetime)            ;month
              (or separator " ")
              (nth 3 datetime))           ;day
    ;; datetime == nil
    nil))

673 674 675 676
(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.
677 678 679 680 681 682 683 684 685
Call icalendar--datetime-to-*-date according to the
value of `calendar-date-style' (or the older `european-calendar-style')."
  (funcall (intern-soft (format "icalendar--datetime-to-%s-date"
                                (if (boundp 'calendar-date-style)
                                    calendar-date-style
                                  (if (with-no-warnings european-calendar-style)
                                      'european
                                    'american))))
           datetime separator))
686

687
(defun icalendar--datetime-to-colontime (datetime)
688 689 690 691
  "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)))

692
(defun icalendar--get-month-number (monthname)
693
  "Return the month number for the given MONTHNAME."
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
  (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."
709 710 711 712 713 714 715 716 717 718
  (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)))
719 720
    ;; Error:
    -1))
721

722
(defun icalendar--get-weekday-abbrev (weekday)
723
  "Return the abbreviated WEEKDAY."
724 725 726 727 728 729 730 731 732 733 734
  (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:
735 736 737 738 739 740 741 742 743 744 745
    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))))

746

747
(defun icalendar--datestring-to-isodate (datestring &optional day-shift)
748 749 750 751 752 753
  "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
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
      (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
771 772 773 774 775
             (string-match (concat "\\s-*"
                                   "0?\\([123]?[0-9]\\)[ \t/]\\s-*"
                                   "\\([A-Za-z][^ ]+\\)[ \t/]\\s-*"
                                   "\\([0-9]\\{4\\}\\)")
                           datestring)
776 777 778 779 780 781 782 783
             (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
784 785 786 787 788
             (string-match (concat "\\s-*"
                                   "\\([A-Za-z][^ ]+\\)[ \t/]\\s-*"
                                   "0?\\([123]?[0-9]\\),?[ \t/]\\s-*"
                                   "\\([0-9]\\{4\\}\\)")
                           datestring)
789 790 791 792 793 794 795 796 797
             (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)))
798
    (if (> day 0)
799 800
        (let ((mdy (calendar-gregorian-from-absolute
                    (+ (calendar-absolute-from-gregorian (list month day
801
                                                               year))
802 803
                       (or day-shift 0)))))
          (format "%04d%02d%02d" (nth 2 mdy) (nth 0 mdy) (nth 1 mdy)))
804 805
      nil)))

806
(defun icalendar--diarytime-to-isotime (timestring ampmstring)
807
  "Convert a time like 9:30pm to an iso-conform string like T213000.
808 809 810
In this example the TIMESTRING would be \"9:30\" and the AMPMSTRING
would be \"pm\"."
  (if timestring
811
      (let ((starttimenum (read (icalendar--rris ":" "" timestring))))
812
        ;; take care of am/pm style
813 814
        ;; Be sure *not* to convert 12:00pm - 12:59pm to 2400-2459
        (if (and ampmstring (string= "pm" ampmstring) (< starttimenum 1200))
815 816 817 818
            (setq starttimenum (+ starttimenum 1200)))
        (format "T%04d00" starttimenum))
    nil))

819 820 821
(defun icalendar--convert-string-for-export (string)
  "Escape comma and other critical characters in STRING."
  (icalendar--rris "," "\\\\," string))
822

823
(defun icalendar--convert-string-for-import (string)
824
  "Remove escape chars for comma, semicolon etc. from STRING."
825 826 827 828 829
  (icalendar--rris
   "\\\\n" "\n " (icalendar--rris
                  "\\\\\"" "\"" (icalendar--rris
                                 "\\\\;" ";" (icalendar--rris
                                              "\\\\," "," string)))))
830 831

;; ======================================================================
832
;; Export -- convert emacs-diary to icalendar
833 834
;; ======================================================================

835
;;;###autoload
836 837 838 839
(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."
840
  (interactive "FExport diary data from file: 
841
Finto iCalendar file: ")
842 843 844 845 846
  (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)
847
(make-obsolete 'icalendar-convert-diary-to-ical 'icalendar-export-file)
848

849
;;;###autoload
850 851 852 853
(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
854
ICAL-FILENAME.
855 856 857
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*'."
858 859
  (interactive "r
FExport diary data into iCalendar file: ")
860 861 862 863 864
  (let ((result "")
        (start 0)
        (entry-main "")
        (entry-rest "")
        (header "")
865
        (contents-n-summary)
866
        (contents)
867
        (found-error nil)
868
        (nonmarker (concat "^" (regexp-quote diary-nonmarking-symbol)
869 870
                           "?"))
        (other-elements nil))
871 872
    ;; prepare buffer with error messages
    (save-current-buffer
873
      (set-buffer (get-buffer-create "*icalendar-errors*"))
874
      (erase-buffer))
875

876
    ;; here we go
877 878
    (save-excursion
      (goto-char min)
879
      (while (re-search-forward
880 881 882 883
              ;; possibly ignore hidden entries beginning with "&"
              (if icalendar-export-hidden-diary-entries
                  "^\\([^ \t\n#].+\\)\\(\\(\n[ \t].*\\)*\\)"
                "^\\([^ \t\n&#].+\\)\\(\\(\n[ \t].*\\)*\\)") max t)
884 885 886 887 888 889 890 891
        (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)))))
892 893
        (condition-case error-val
            (progn
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
              (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))))
921 922 923 924 925
              (setq result (concat result header contents "\nEND:VEVENT")))
          ;; handle errors
          (error
           (setq found-error t)
           (save-current-buffer
926
             (set-buffer (get-buffer-create "*icalendar-errors*"))
927 928
             (insert (format "Error in line %d -- %s: `%s'\n"
                             (count-lines (point-min) (point))
929
                             error-val
930 931
                             entry-main))))))

932
      ;; we're done, insert everything into the file
933
      (save-current-buffer
934
        (let ((coding-system-for-write 'utf-8))
935 936 937 938 939 940 941 942
          (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
943 944 945
          (save-buffer)
          (unless found-error
            (bury-buffer)))))
946
    found-error))
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
(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)
977 978
  "Parse SUMMARY-AND-REST from a diary to fill iCalendar properties.
Returns an alist."
979
  (save-match-data
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 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 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
    (if (functionp icalendar-import-format)
        ;; can't do anything
        nil
      ;; split summary-and-rest
      (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))))))))
1066 1067

;; subroutines for icalendar-export-region
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
(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\\)?\\)?"
                            "\\)?"
1078
                            "\\s-*\\(.*?\\) ?$")
1079 1080 1081 1082 1083 1084 1085
                    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))
1086
             (endisostring1)
1087 1088 1089 1090 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
             (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"))
1116 1117 1118 1119 1120 1121 1122

        ;; If only start-date is specified, then end-date is next day,
        ;; otherwise it is same day.
        (setq endisostring1 (if starttimestring
                                startisostring
                              endisostring))

1123 1124 1125 1126 1127
        (when starttimestring
          (unless endtimestring
            (let ((time
                   (read (icalendar--rris "^T0?" ""
                                          starttimestring))))
1128 1129
              (if (< time 230000)
                  ;; Case: ends on same day
1130
              (setq endtimestring (format "T%06d"
1131 1132 1133 1134 1135 1136
                                              (+ 10000 time)))
                ;; Case: ends on next day
                (setq endtimestring (format "T%06d"
                                              (- time 230000)))
                (setq endisostring1 endisostring)) )))

1137 1138 1139 1140 1141 1142 1143 1144
        (list (concat "\nDTSTART;"
                      (if starttimestring "VALUE=DATE-TIME:"
                        "VALUE=DATE:")
                      startisostring
                      (or starttimestring "")
                      "\nDTEND;"
                      (if endtimestring "VALUE=DATE-TIME:"
                        "VALUE=DATE:")
1145
                      endisostring1
1146 1147
                      (or endtimestring ""))
              summary))
1148 1149 1150
    ;; no match
    nil))

1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
(defun icalendar-first-weekday-of-year (abbrevweekday year)
  "Find the first ABBREVWEEKDAY in a given YEAR.
Returns day number."
  (let* ((day-of-week-jan01 (calendar-day-of-week (list 1 1 year)))
         (result (+ 1
                    (- (icalendar--get-weekday-number abbrevweekday)
                       day-of-week-jan01))))
    (cond ((<= result 0)
           (setq result (+ result 7)))
          ((> result 7)
           (setq result (- result 7))))
    result))
1163

1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
(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\\)?\\)?"
                                 "\\)?"
1176
                                 "\\s-*\\(.*?\\) ?$")
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
                         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))))))
1218 1219 1220 1221
        (list (concat "\nDTSTART;"
                      (if starttimestring
                          "VALUE=DATE-TIME:"
                        "VALUE=DATE:")
1222 1223
                      ;; Find the first requested weekday of the
                      ;; start year
1224 1225 1226 1227
                      (funcall 'format "%04d%02d%02d"
                               icalendar-recurring-start-year 1
                               (icalendar-first-weekday-of-year
                                day icalendar-recurring-start-year))
1228 1229 1230 1231 1232
                      (or starttimestring "")
                      "\nDTEND;"
                      (if endtimestring
                          "VALUE=DATE-TIME:"
                        "VALUE=DATE:")
1233
                      (funcall 'format "%04d%02d%02d"
1234
                       ;; end is non-inclusive!
1235 1236 1237
                               icalendar-recurring-start-year 1
                               (+ (icalendar-first-weekday-of-year
                                   day icalendar-recurring-start-year)
1238
                          (if endtimestring 0 1)))
1239 1240 1241 1242
                      (or endtimestring "")
                      "\nRRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY="
                      day)
              summary))
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
    ;; 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\\)?\\)?"
                            "\\)?"