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