Synch to No Gnus 200506160601, and
[elisp/gnus.git-] / lisp / gnus-diary.el
1 ;;; gnus-diary.el --- Wrapper around the NNDiary Gnus backend
2
3 ;; Copyright (c) 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
4 ;; Copyright (C) 1999, 2000, 2001 Didier Verna.
5
6 ;; Author:        Didier Verna <didier@xemacs.org>
7 ;; Maintainer:    Didier Verna <didier@xemacs.org>
8 ;; Created:       Tue Jul 20 10:42:55 1999
9 ;; Keywords:      calendar mail news
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published
15 ;; by the Free Software Foundation; either version 2 of the License,
16 ;; or (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful, but
19 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21 ;; General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with this program; if not, write to the Free Software
25 ;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26
27
28 ;;; Commentary:
29
30 ;; Contents management by FCM version 0.1.
31
32 ;; Description:
33 ;; ===========
34
35 ;; Gnus-Diary is a wrapper around the NNDiary Gnus backend.  It is here to
36 ;; make your nndiary-user life easier in different ways.  So, you don't have
37 ;; to use it if you don't want to.  But, really, you should.
38
39 ;; Gnus-Diary offers the following features on top of the NNDiary backend:
40
41 ;;  - A nice summary line format:
42 ;;    Displaying diary messages in standard summary line format (usually
43 ;;    something like "<From Joe>: <Subject>") is pretty useless.  Most of the
44 ;;    time, you're the one who wrote the message, and you mostly want to see
45 ;;    the event's date.  Gnus-Diary offers you a nice summary line format
46 ;;    which will do this.  By default, a summary line will appear like this:
47 ;;
48 ;;     <Event Date>: <Subject> <Remaining time>
49 ;;
50 ;;   for example, here's how Joe's birthday is displayed in my
51 ;;   "nndiary:birhdays" summary buffer (the message is expirable, but will
52 ;;   never be deleted, as it specifies a regular event):
53 ;;
54 ;;   E  Sat, Sep 22 01, 12:00: Joe's birthday (in 6 months, 1 week)
55
56 ;;  - More article sorting functions:
57 ;;    Gnus-Diary adds a new sorting function called
58 ;;    `gnus-summary-sort-by-schedule'.  This function lets you organize your
59 ;;    diary summary buffers from the closest event to the farthest one.
60
61 ;;  - Automatic generation of diary group parameters:
62 ;;    When you create a new diary group, or visit one, Gnus-Diary checks your
63 ;;    group parameters, and if needed, sets the summary line format to the
64 ;;    diary-specific value, adds the diary-specific sorting functions, and
65 ;;    also adds the different `X-Diary-*' headers to the group's
66 ;;    posting-style.  It is then easier to send a diary message, because if
67 ;;    you use `C-u a' or `C-u m' on a diary group to prepare a message, these
68 ;;    headers will be inserted automatically (but not filled with proper
69 ;;    values yet).
70
71 ;;  - An interactive mail-to-diary convertion function:
72 ;;    The function `gnus-diary-check-message' ensures that the current message
73 ;;    contains all the required diary headers, and prompts you for values /
74 ;;    correction if needed.  This function is hooked in the nndiary backend so
75 ;;    that moving an article to an nndiary group will trigger it
76 ;;    automatically.  It is also bound to `C-c D c' in message-mode and
77 ;;    article-edit-mode in order to ease the process of converting a usual
78 ;;    mail to a diary one.  This function takes a prefix argument which will
79 ;;    force prompting of all diary headers, regardless of their
80 ;;    presence/validity.  That way, you can very easily reschedule a diary
81 ;;    message for instance.
82
83
84 ;; Usage:
85 ;; =====
86
87 ;; 0/ Don't use any `gnus-user-format-function-[d|D]'.  Gnus-Diary provides
88 ;;    both of these (sorry if you used them before).
89 ;; 1/ Add '(require 'gnus-diary) to your gnusrc file.
90 ;; 2/ Customize your gnus-diary options to suit your needs.
91
92
93
94 ;; Bugs / Todo:
95 ;; ===========
96
97
98 ;;; Code:
99
100 (require 'nndiary)
101 (require 'message)
102 (require 'gnus-art)
103
104 (defgroup gnus-diary nil
105   "Utilities on top of the nndiary backend for Gnus."
106   :version "22.1"
107   :group 'gnus)
108
109 (defcustom gnus-diary-summary-line-format "%U%R%z %uD: %(%s%) (%ud)\n"
110   "*Summary line format for nndiary groups."
111   :type 'string
112   :group 'gnus-diary
113   :group 'gnus-summary-format)
114
115 (defcustom gnus-diary-time-format "%a, %b %e %y, %H:%M"
116   "*Time format to display appointements in nndiary summary buffers.
117 Please refer to `format-time-string' for information on possible values."
118   :type 'string
119   :group 'gnus-diary)
120
121 (defcustom gnus-diary-delay-format-function 'gnus-diary-delay-format-english
122   "*Function called to format a diary delay string.
123 It is passed two arguments.  The first one is non nil if the delay is in
124 the past.  The second one is of the form ((NUM . UNIT) ...) where NUM is
125 an integer and UNIT is one of 'year 'month 'week 'day 'hour or 'minute.
126 It should return strings like \"In 2 months, 3 weeks\", \"3 hours,
127 1 minute ago\" and so on.
128
129 There are currently two built-in format functions:
130 `gnus-diary-delay-format-english' (the default)
131 `gnus-diary-delay-format-french'"
132   :type '(choice (const  :tag "english" gnus-diary-delay-format-english)
133                  (const  :tag "french"  gnus-diary-delay-format-french)
134                  (symbol :tag "other"))
135   :group 'gnus-diary)
136
137 (defconst gnus-diary-version nndiary-version
138   "Current Diary backend version.")
139
140
141 ;; Compatibility functions ==================================================
142
143 (eval-and-compile
144   (if (fboundp 'kill-entire-line)
145       (defalias 'gnus-diary-kill-entire-line 'kill-entire-line)
146     (defun gnus-diary-kill-entire-line ()
147       (beginning-of-line)
148       (let ((kill-whole-line t))
149         (kill-line)))))
150
151
152 ;; Summary line format ======================================================
153
154 (defun gnus-diary-delay-format-french (past delay)
155   (if (null delay)
156       "maintenant!"
157     ;; Keep only a precision of two degrees
158     (and (> (length delay) 1) (setcdr (cdr delay) nil))
159     (concat (if past "il y a " "dans ")
160             (let ((str "")
161                   del)
162               (while (setq del (pop delay))
163                 (setq str (concat str
164                                   (int-to-string (car del)) " "
165                                   (cond ((eq (cdr del) 'year)
166                                          "an")
167                                         ((eq (cdr del) 'month)
168                                          "mois")
169                                         ((eq (cdr del) 'week)
170                                          "semaine")
171                                         ((eq (cdr del) 'day)
172                                          "jour")
173                                         ((eq (cdr del) 'hour)
174                                          "heure")
175                                         ((eq (cdr del) 'minute)
176                                          "minute"))
177                                   (unless (or (eq (cdr del) 'month)
178                                               (= (car del) 1))
179                                     "s")
180                                   (if delay ", "))))
181               str))))
182
183
184 (defun gnus-diary-delay-format-english (past delay)
185   (if (null delay)
186       "now!"
187     ;; Keep only a precision of two degrees
188     (and (> (length delay) 1) (setcdr (cdr delay) nil))
189     (concat (unless past "in ")
190             (let ((str "")
191                   del)
192               (while (setq del (pop delay))
193                 (setq str (concat str
194                                   (int-to-string (car del)) " "
195                                   (symbol-name (cdr del))
196                                   (and (> (car del) 1) "s")
197                                   (if delay ", "))))
198               str)
199             (and past " ago"))))
200
201
202 (defun gnus-diary-header-schedule (headers)
203   ;; Same as `nndiary-schedule', but given a set of headers HEADERS
204   (mapcar
205    (lambda (elt)
206      (let ((head (cdr (assoc (intern (format "X-Diary-%s" (car elt)))
207                              headers))))
208        (when head
209          (nndiary-parse-schedule-value head (cadr elt) (car (cddr elt))))))
210    nndiary-headers))
211
212 ;; #### NOTE: Gnus sometimes gives me a HEADER not corresponding to any
213 ;; message, with all fields set to nil here. I don't know what it is for, and
214 ;; I just ignore it.
215 (defun gnus-user-format-function-d (header)
216   ;; Returns an aproximative delay string for the next occurence of this
217   ;; message. The delay is given only in the first non zero unit.
218   ;; Code partly stolen from article-make-date-line
219   (let* ((extras (mail-header-extra header))
220          (sched (gnus-diary-header-schedule extras))
221          (occur (nndiary-next-occurence sched (current-time)))
222          (now (current-time))
223          (real-time (subtract-time occur now)))
224     (if (null real-time)
225         "?????"
226       (let* ((sec (+ (* (float (car real-time)) 65536) (cadr real-time)))
227              (past (< sec 0))
228              delay)
229         (and past (setq sec (- sec)))
230         (unless (zerop sec)
231           ;; This is a bit convoluted, but basically we go through the time
232           ;; units for years, weeks, etc, and divide things to see whether
233           ;; that results in positive answers.
234           (let ((units `((year . ,(* 365.25 24 3600))
235                          (month . ,(* 31 24 3600))
236                          (week . ,(* 7 24 3600))
237                          (day . ,(* 24 3600))
238                          (hour . 3600)
239                          (minute . 60)))
240                 unit num)
241             (while (setq unit (pop units))
242               (unless (zerop (setq num (ffloor (/ sec (cdr unit)))))
243                 (setq delay (append delay `((,(floor num) . ,(car unit))))))
244               (setq sec (- sec (* num (cdr unit)))))))
245         (funcall gnus-diary-delay-format-function past delay)))
246     ))
247
248 ;; #### NOTE: Gnus sometimes gives me a HEADER not corresponding to any
249 ;; message, with all fields set to nil here. I don't know what it is for, and
250 ;; I just ignore it.
251 (defun gnus-user-format-function-D (header)
252   ;; Returns a formatted time string for the next occurence of this message.
253   (let* ((extras (mail-header-extra header))
254          (sched (gnus-diary-header-schedule extras))
255          (occur (nndiary-next-occurence sched (current-time))))
256     (format-time-string gnus-diary-time-format occur)))
257
258
259 ;; Article sorting functions ================================================
260
261 (defun gnus-article-sort-by-schedule (h1 h2)
262   (let* ((now (current-time))
263          (e1 (mail-header-extra h1))
264          (e2 (mail-header-extra h2))
265          (s1 (gnus-diary-header-schedule e1))
266          (s2 (gnus-diary-header-schedule e2))
267          (o1 (nndiary-next-occurence s1 now))
268          (o2 (nndiary-next-occurence s2 now)))
269     (if (and (= (car o1) (car o2)) (= (cadr o1) (cadr o2)))
270         (< (mail-header-number h1) (mail-header-number h2))
271       (time-less-p o1 o2))))
272
273
274 (defun gnus-thread-sort-by-schedule (h1 h2)
275   (gnus-article-sort-by-schedule (gnus-thread-header h1)
276                                  (gnus-thread-header h2)))
277
278 (defun gnus-summary-sort-by-schedule (&optional reverse)
279   "Sort nndiary summary buffers by schedule of appointements.
280 Optional prefix (or REVERSE argument) means sort in reverse order."
281   (interactive "P")
282   (gnus-summary-sort 'schedule reverse))
283
284 (defvar gnus-summary-misc-menu) ;; Avoid byte compiler warning.
285 ;; The function `easy-menu-add-item' is not available under Emacs
286 ;; versions prior to 20.3.  Could anyone try to emulate it?
287 (if (eval-when-compile
288       (require 'easymenu)
289       (or (fboundp 'easy-menu-add-item)
290           (progn
291             (defalias 'easy-menu-add-item 'ignore)
292             nil)))
293 (add-hook 'gnus-summary-menu-hook
294           (lambda ()
295             (easy-menu-add-item gnus-summary-misc-menu
296                                 '("Sort")
297                                 ["Sort by schedule"
298                                  gnus-summary-sort-by-schedule
299                                  (eq (car (gnus-find-method-for-group
300                                            gnus-newsgroup-name))
301                                      'nndiary)]
302                                 "Sort by number")))
303   )
304
305
306
307 ;; Group parameters autosetting =============================================
308
309 (defun gnus-diary-update-group-parameters (group)
310   ;; Ensure that nndiary groups have convenient group parameters:
311   ;; - a posting style containing X-Diary headers
312   ;; - a nice summary line format
313   ;; - NNDiary specific sorting by schedule functions
314   ;; In general, try not to mess with what the user might have modified.
315   (let ((posting-style (gnus-group-get-parameter group 'posting-style t)))
316     ;; Posting style:
317     (mapcar (lambda (elt)
318               (let ((header (format "X-Diary-%s" (car elt))))
319                 (unless (assoc header posting-style)
320                   (setq posting-style (append posting-style
321                                               `((,header "*")))))
322                 ))
323             nndiary-headers)
324     (gnus-group-set-parameter group 'posting-style posting-style)
325     ;; Summary line format:
326     (unless (gnus-group-get-parameter group 'gnus-summary-line-format t)
327       (gnus-group-set-parameter group 'gnus-summary-line-format
328                                 `(,gnus-diary-summary-line-format)))
329     ;; Sorting by schedule:
330     (unless (gnus-group-get-parameter group 'gnus-article-sort-functions)
331       (gnus-group-set-parameter group 'gnus-article-sort-functions
332                                 '((append gnus-article-sort-functions
333                                           (list
334                                            'gnus-article-sort-by-schedule)))))
335     (unless (gnus-group-get-parameter group 'gnus-thread-sort-functions)
336       (gnus-group-set-parameter group 'gnus-thread-sort-functions
337                                 '((append gnus-thread-sort-functions
338                                           (list
339                                            'gnus-thread-sort-by-schedule)))))
340     ))
341
342 ;; Called when a group is subscribed. This is needed because groups created
343 ;; because of mail splitting are *not* created with the backend function.
344 ;; Thus, `nndiary-request-create-group-hooks' is inoperative.
345 (defun gnus-diary-maybe-update-group-parameters (group)
346   (when (eq (car (gnus-find-method-for-group group)) 'nndiary)
347     (gnus-diary-update-group-parameters group)))
348
349 (add-hook 'nndiary-request-create-group-hooks
350           'gnus-diary-update-group-parameters)
351 ;; Now that we have `gnus-subscribe-newsgroup-hooks', this is not needed
352 ;; anymore. Maybe I should remove this completely.
353 (add-hook 'nndiary-request-update-info-hooks
354           'gnus-diary-update-group-parameters)
355 (add-hook 'gnus-subscribe-newsgroup-hooks
356           'gnus-diary-maybe-update-group-parameters)
357
358
359 ;; Diary Message Checking ===================================================
360
361 (defvar gnus-diary-header-value-history nil
362   ;; History variable for header value prompting
363   )
364
365 (defun gnus-diary-narrow-to-headers ()
366   "Narrow the current buffer to the header part.
367 Point is left at the beginning of the region.
368 The buffer is assumed to contain a message, but the format is unknown."
369   (cond ((eq major-mode 'message-mode)
370          (message-narrow-to-headers))
371         (t
372          (goto-char (point-min))
373          (when (search-forward "\n\n" nil t)
374            (narrow-to-region (point-min) (- (point) 1))
375            (goto-char (point-min))))
376         ))
377
378 (defun gnus-diary-add-header (str)
379   "Add a header to the current buffer.
380 The buffer is assumed to contain a message, but the format is unknown."
381   (cond ((eq major-mode 'message-mode)
382          (message-add-header str))
383         (t
384          (save-restriction
385            (gnus-diary-narrow-to-headers)
386            (goto-char (point-max))
387            (if (string-match "\n$" str)
388                (insert str)
389              (insert str ?\n))))
390         ))
391
392 (defun gnus-diary-check-message (arg)
393   "Ensure that the current message is a valid for NNDiary.
394 This function checks that all NNDiary required headers are present and
395 valid, and prompts for values / correction otherwise.
396
397 If ARG (or prefix) is non-nil, force prompting for all fields."
398   (interactive "P")
399   (save-excursion
400     (mapcar
401      (lambda (head)
402        (let ((header (concat "X-Diary-" (car head)))
403              (ask arg)
404              value invalid)
405          ;; First, try to find the header, and checks for validity:
406          (save-restriction
407            (gnus-diary-narrow-to-headers)
408            (when (re-search-forward (concat "^" header ":") nil t)
409              (unless (eq (char-after) ? )
410                (insert " "))
411              (setq value (buffer-substring (point) (point-at-eol)))
412              (and (string-match "[ \t]*\\([^ \t]+\\)[ \t]*" value)
413                   (setq value (match-string 1 value)))
414              (condition-case ()
415                  (nndiary-parse-schedule-value value
416                                                (nth 1 head) (nth 2 head))
417                (t
418                 (setq invalid t)))
419              ;; #### NOTE: this (along with the `gnus-diary-add-header'
420              ;; function) could be rewritten in a better way, in particular
421              ;; not to blindly remove an already present header and reinsert
422              ;; it somewhere else afterwards.
423              (when (or ask invalid)
424                (gnus-diary-kill-entire-line))
425              ))
426          ;; Now, loop until a valid value is provided:
427          (while (or ask (not value) invalid)
428            (let ((prompt (concat (and invalid
429                                       (prog1 "(current value invalid) "
430                                         (beep)))
431                                  header ": ")))
432              (setq value
433                    (if (listp (nth 1 head))
434                        (completing-read prompt (cons '("*" nil) (nth 1 head))
435                                         nil t value
436                                         gnus-diary-header-value-history)
437                      (read-string prompt value
438                                   gnus-diary-header-value-history))))
439            (setq ask nil)
440            (setq invalid nil)
441            (condition-case ()
442                (nndiary-parse-schedule-value value
443                                              (nth 1 head) (nth 2 head))
444              (t
445               (setq invalid t))))
446          (gnus-diary-add-header (concat header ": " value))
447          ))
448      nndiary-headers)
449     ))
450
451 (add-hook 'nndiary-request-accept-article-hooks
452           (lambda () (gnus-diary-check-message nil)))
453
454 (define-key message-mode-map "\C-cDc" 'gnus-diary-check-message)
455 (define-key gnus-article-edit-mode-map "\C-cDc" 'gnus-diary-check-message)
456
457
458 ;; The end ==================================================================
459
460 (defun gnus-diary-version ()
461   "Current Diary backend version."
462   (interactive)
463   (message "NNDiary version %s" nndiary-version))
464
465 (define-key message-mode-map "\C-cDv" 'gnus-diary-version)
466 (define-key gnus-article-edit-mode-map "\C-cDv" 'gnus-diary-version)
467
468
469 (provide 'gnus-diary)
470
471 ;;; gnus-diary.el ends here