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