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