file new.xpm was added on branch t-gnus-6_17 on 2006-04-11 22:59:16 +0000
[elisp/gnus.git-] / lisp / gnus-diary.el
1 ;;; gnus-diary.el --- Wrapper around the NNDiary Gnus backend
2
3 ;; Copyright (c) 2001, 2002, 2003 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
108 (defcustom gnus-diary-summary-line-format "%U%R%z %uD: %(%s%) (%ud)\n"
109   "*Summary line format for nndiary groups."
110   :type 'string
111   :group 'gnus-diary
112   :group 'gnus-summary-format)
113
114 (defcustom gnus-diary-time-format "%a, %b %e %y, %H:%M"
115   "*Time format to display appointements in nndiary summary buffers.
116 Please refer to `format-time-string' for information on possible values."
117   :type 'string
118   :group 'gnus-diary)
119
120 (defcustom gnus-diary-delay-format-function 'gnus-diary-delay-format-english
121   "*Function called to format a diary delay string.
122 It is passed two arguments.  The first one is non nil if the delay is in
123 the past.  The second one is of the form ((NUM . UNIT) ...) where NUM is
124 an integer and UNIT is one of 'year 'month 'week 'day 'hour or 'minute.
125 It should return strings like \"In 2 months, 3 weeks\", \"3 hours,
126 1 minute ago\" and so on.
127
128 There are currently two built-in format functions:
129 `gnus-diary-delay-format-english' (the default)
130 `gnus-diary-delay-format-french'"
131   :type '(choice (const  :tag "english" gnus-diary-delay-format-english)
132                  (const  :tag "french"  gnus-diary-delay-format-french)
133                  (symbol :tag "other"))
134   :group 'gnus-diary)
135
136 (defconst gnus-diary-version nndiary-version
137   "Current Diary backend version.")
138
139
140 ;; Compatibility functions ==================================================
141
142 (eval-and-compile
143   (if (fboundp 'kill-entire-line)
144       (defalias 'gnus-diary-kill-entire-line 'kill-entire-line)
145     (defun gnus-diary-kill-entire-line ()
146       (beginning-of-line)
147       (let ((kill-whole-line t))
148         (kill-line)))))
149
150
151 ;; Summary line format ======================================================
152
153 (defun gnus-diary-delay-format-french (past delay)
154   (if (null delay)
155       "maintenant!"
156     ;; Keep only a precision of two degrees
157     (and (> (length delay) 1) (setcdr (cdr delay) nil))
158     (concat (if past "il y a " "dans ")
159             (let ((str "")
160                   del)
161               (while (setq del (pop delay))
162                 (setq str (concat str
163                                   (int-to-string (car del)) " "
164                                   (cond ((eq (cdr del) 'year)
165                                          "an")
166                                         ((eq (cdr del) 'month)
167                                          "mois")
168                                         ((eq (cdr del) 'week)
169                                          "semaine")
170                                         ((eq (cdr del) 'day)
171                                          "jour")
172                                         ((eq (cdr del) 'hour)
173                                          "heure")
174                                         ((eq (cdr del) 'minute)
175                                          "minute"))
176                                   (unless (or (eq (cdr del) 'month)
177                                               (= (car del) 1))
178                                     "s")
179                                   (if delay ", "))))
180               str))))
181
182
183 (defun gnus-diary-delay-format-english (past delay)
184   (if (null delay)
185       "now!"
186     ;; Keep only a precision of two degrees
187     (and (> (length delay) 1) (setcdr (cdr delay) nil))
188     (concat (unless past "in ")
189             (let ((str "")
190                   del)
191               (while (setq del (pop delay))
192                 (setq str (concat str
193                                   (int-to-string (car del)) " "
194                                   (symbol-name (cdr del))
195                                   (and (> (car del) 1) "s")
196                                   (if delay ", "))))
197               str)
198             (and past " ago"))))
199
200
201 (defun gnus-diary-header-schedule (headers)
202   ;; Same as `nndiary-schedule', but given a set of headers HEADERS
203   (mapcar
204    (lambda (elt)
205      (let ((head (cdr (assoc (intern (format "X-Diary-%s" (car elt)))
206                              headers))))
207        (when head
208          (nndiary-parse-schedule-value head (cadr elt) (car (cddr elt))))))
209    nndiary-headers))
210
211 ;; #### NOTE: Gnus sometimes gives me a HEADER not corresponding to any
212 ;; message, with all fields set to nil here. I don't know what it is for, and
213 ;; I just ignore it.
214 (defun gnus-user-format-function-d (header)
215   ;; Returns an aproximative delay string for the next occurence of this
216   ;; message. The delay is given only in the first non zero unit.
217   ;; Code partly stolen from article-make-date-line
218   (let* ((extras (mail-header-extra header))
219          (sched (gnus-diary-header-schedule extras))
220          (occur (nndiary-next-occurence sched (current-time)))
221          (now (current-time))
222          (real-time (subtract-time occur now)))
223     (if (null real-time)
224         "?????"
225       (let* ((sec (+ (* (float (car real-time)) 65536) (cadr real-time)))
226              (past (< sec 0))
227              delay)
228         (and past (setq sec (- sec)))
229         (unless (zerop sec)
230           ;; This is a bit convoluted, but basically we go through the time
231           ;; units for years, weeks, etc, and divide things to see whether
232           ;; that results in positive answers.
233           (let ((units `((year . ,(* 365.25 24 3600))
234                          (month . ,(* 31 24 3600))
235                          (week . ,(* 7 24 3600))
236                          (day . ,(* 24 3600))
237                          (hour . 3600)
238                          (minute . 60)))
239                 unit num)
240             (while (setq unit (pop units))
241               (unless (zerop (setq num (ffloor (/ sec (cdr unit)))))
242                 (setq delay (append delay `((,(floor num) . ,(car unit))))))
243               (setq sec (- sec (* num (cdr unit)))))))
244         (funcall gnus-diary-delay-format-function past delay)))
245     ))
246
247 ;; #### NOTE: Gnus sometimes gives me a HEADER not corresponding to any
248 ;; message, with all fields set to nil here. I don't know what it is for, and
249 ;; I just ignore it.
250 (defun gnus-user-format-function-D (header)
251   ;; Returns a formatted time string for the next occurence of this message.
252   (let* ((extras (mail-header-extra header))
253          (sched (gnus-diary-header-schedule extras))
254          (occur (nndiary-next-occurence sched (current-time))))
255     (format-time-string gnus-diary-time-format occur)))
256
257
258 ;; Article sorting functions ================================================
259
260 (defun gnus-article-sort-by-schedule (h1 h2)
261   (let* ((now (current-time))
262          (e1 (mail-header-extra h1))
263          (e2 (mail-header-extra h2))
264          (s1 (gnus-diary-header-schedule e1))
265          (s2 (gnus-diary-header-schedule e2))
266          (o1 (nndiary-next-occurence s1 now))
267          (o2 (nndiary-next-occurence s2 now)))
268     (if (and (= (car o1) (car o2)) (= (cadr o1) (cadr o2)))
269         (< (mail-header-number h1) (mail-header-number h2))
270       (time-less-p o1 o2))))
271
272
273 (defun gnus-thread-sort-by-schedule (h1 h2)
274   (gnus-article-sort-by-schedule (gnus-thread-header h1)
275                                  (gnus-thread-header h2)))
276
277 (defun gnus-summary-sort-by-schedule (&optional reverse)
278   "Sort nndiary summary buffers by schedule of appointements.
279 Optional prefix (or REVERSE argument) means sort in reverse order."
280   (interactive "P")
281   (gnus-summary-sort 'schedule reverse))
282
283 (defvar gnus-summary-misc-menu) ;; Avoid byte compiler warning.
284 ;; The function `easy-menu-add-item' is not available under Emacs
285 ;; versions prior to 20.3.  Could anyone try to emulate it?
286 (if (eval-when-compile
287       (require 'easymenu)
288       (or (fboundp 'easy-menu-add-item)
289           (progn
290             (defalias 'easy-menu-add-item 'ignore)
291             nil)))
292 (add-hook 'gnus-summary-menu-hook
293           (lambda ()
294             (easy-menu-add-item gnus-summary-misc-menu
295                                 '("Sort")
296                                 ["Sort by schedule"
297                                  gnus-summary-sort-by-schedule
298                                  (eq (car (gnus-find-method-for-group
299                                            gnus-newsgroup-name))
300                                      'nndiary)]
301                                 "Sort by number")))
302   )
303
304
305
306 ;; Group parameters autosetting =============================================
307
308 (defun gnus-diary-update-group-parameters (group)
309   ;; Ensure that nndiary groups have convenient group parameters:
310   ;; - a posting style containing X-Diary headers
311   ;; - a nice summary line format
312   ;; - NNDiary specific sorting by schedule functions
313   ;; In general, try not to mess with what the user might have modified.
314   (let ((posting-style (gnus-group-get-parameter group 'posting-style t)))
315     ;; Posting style:
316     (mapcar (lambda (elt)
317               (let ((header (format "X-Diary-%s" (car elt))))
318                 (unless (assoc header posting-style)
319                   (setq posting-style (append posting-style
320                                               `((,header "*")))))
321                 ))
322             nndiary-headers)
323     (gnus-group-set-parameter group 'posting-style posting-style)
324     ;; Summary line format:
325     (unless (gnus-group-get-parameter group 'gnus-summary-line-format t)
326       (gnus-group-set-parameter group 'gnus-summary-line-format
327                                 `(,gnus-diary-summary-line-format)))
328     ;; Sorting by schedule:
329     (unless (gnus-group-get-parameter group 'gnus-article-sort-functions)
330       (gnus-group-set-parameter group 'gnus-article-sort-functions
331                                 '((append gnus-article-sort-functions
332                                           (list
333                                            'gnus-article-sort-by-schedule)))))
334     (unless (gnus-group-get-parameter group 'gnus-thread-sort-functions)
335       (gnus-group-set-parameter group 'gnus-thread-sort-functions
336                                 '((append gnus-thread-sort-functions
337                                           (list
338                                            'gnus-thread-sort-by-schedule)))))
339     ))
340
341 ;; Called when a group is subscribed. This is needed because groups created
342 ;; because of mail splitting are *not* created with the backend function.
343 ;; Thus, `nndiary-request-create-group-hooks' is inoperative.
344 (defun gnus-diary-maybe-update-group-parameters (group)
345   (when (eq (car (gnus-find-method-for-group group)) 'nndiary)
346     (gnus-diary-update-group-parameters group)))
347
348 (add-hook 'nndiary-request-create-group-hooks
349           'gnus-diary-update-group-parameters)
350 ;; Now that we have `gnus-subscribe-newsgroup-hooks', this is not needed
351 ;; anymore. Maybe I should remove this completely.
352 (add-hook 'nndiary-request-update-info-hooks
353           'gnus-diary-update-group-parameters)
354 (add-hook 'gnus-subscribe-newsgroup-hooks
355           'gnus-diary-maybe-update-group-parameters)
356
357
358 ;; Diary Message Checking ===================================================
359
360 (defvar gnus-diary-header-value-history nil
361   ;; History variable for header value prompting
362   )
363
364 (defun gnus-diary-narrow-to-headers ()
365   "Narrow the current buffer to the header part.
366 Point is left at the beginning of the region.
367 The buffer is assumed to contain a message, but the format is unknown."
368   (cond ((eq major-mode 'message-mode)
369          (message-narrow-to-headers))
370         (t
371          (goto-char (point-min))
372          (when (search-forward "\n\n" nil t)
373            (narrow-to-region (point-min) (- (point) 1))
374            (goto-char (point-min))))
375         ))
376
377 (defun gnus-diary-add-header (str)
378   "Add a header to the current buffer.
379 The buffer is assumed to contain a message, but the format is unknown."
380   (cond ((eq major-mode 'message-mode)
381          (message-add-header str))
382         (t
383          (save-restriction
384            (gnus-diary-narrow-to-headers)
385            (goto-char (point-max))
386            (if (string-match "\n$" str)
387                (insert str)
388              (insert str ?\n))))
389         ))
390
391 (defun gnus-diary-check-message (arg)
392   "Ensure that the current message is a valid for NNDiary.
393 This function checks that all NNDiary required headers are present and
394 valid, and prompts for values / correction otherwise.
395
396 If ARG (or prefix) is non-nil, force prompting for all fields."
397   (interactive "P")
398   (save-excursion
399     (mapcar
400      (lambda (head)
401        (let ((header (concat "X-Diary-" (car head)))
402              (ask arg)
403              value invalid)
404          ;; First, try to find the header, and checks for validity:
405          (save-restriction
406            (gnus-diary-narrow-to-headers)
407            (when (re-search-forward (concat "^" header ":") nil t)
408              (unless (eq (char-after) ? )
409                (insert " "))
410              (setq value (buffer-substring (point) (point-at-eol)))
411              (and (string-match "[ \t]*\\([^ \t]+\\)[ \t]*" value)
412                   (setq value (match-string 1 value)))
413              (condition-case ()
414                  (nndiary-parse-schedule-value value
415                                                (nth 1 head) (nth 2 head))
416                (t
417                 (setq invalid t)))
418              ;; #### NOTE: this (along with the `gnus-diary-add-header'
419              ;; function) could be rewritten in a better way, in particular
420              ;; not to blindly remove an already present header and reinsert
421              ;; it somewhere else afterwards.
422              (when (or ask invalid)
423                (gnus-diary-kill-entire-line))
424              ))
425          ;; Now, loop until a valid value is provided:
426          (while (or ask (not value) invalid)
427            (let ((prompt (concat (and invalid
428                                       (prog1 "(current value invalid) "
429                                         (beep)))
430                                  header ": ")))
431              (setq value
432                    (if (listp (nth 1 head))
433                        (completing-read prompt (cons '("*" nil) (nth 1 head))
434                                         nil t value
435                                         gnus-diary-header-value-history)
436                      (read-string prompt value
437                                   gnus-diary-header-value-history))))
438            (setq ask nil)
439            (setq invalid nil)
440            (condition-case ()
441                (nndiary-parse-schedule-value value
442                                              (nth 1 head) (nth 2 head))
443              (t
444               (setq invalid t))))
445          (gnus-diary-add-header (concat header ": " value))
446          ))
447      nndiary-headers)
448     ))
449
450 (add-hook 'nndiary-request-accept-article-hooks
451           (lambda () (gnus-diary-check-message nil)))
452
453 (define-key message-mode-map "\C-cDc" 'gnus-diary-check-message)
454 (define-key gnus-article-edit-mode-map "\C-cDc" 'gnus-diary-check-message)
455
456
457 ;; The end ==================================================================
458
459 (defun gnus-diary-version ()
460   "Current Diary backend version."
461   (interactive)
462   (message "NNDiary version %s" nndiary-version))
463
464 (define-key message-mode-map "\C-cDv" 'gnus-diary-version)
465 (define-key gnus-article-edit-mode-map "\C-cDv" 'gnus-diary-version)
466
467
468 (provide 'gnus-diary)
469
470 ;;; gnus-diary.el ends here