* gnus-registry.el (gnus-registry-save): allow forced saving even
[gnus] / lisp / gnus-registry.el
1 ;;; gnus-registry.el --- article registry for Gnus
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Ted Zlatanov <tzz@lifelogs.com>
6 ;; Keywords: news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;;; Code:
28
29 (eval-when-compile (require 'cl))
30
31 (require 'gnus)
32 (require 'gnus-int)
33 (require 'gnus-sum)
34 (require 'nnmail)
35
36 (defvar gnus-registry-dirty t
37  "Boolean set to t when the registry is modified")
38
39 (defgroup gnus-registry nil
40   "The Gnus registry."
41   :group 'gnus)
42
43 (defvar gnus-registry-hashtb nil
44   "*The article registry by Message ID.")
45
46 (defcustom gnus-registry-unfollowed-groups '("delayed" "drafts" "queue")
47   "List of groups that gnus-registry-split-fancy-with-parent won't follow.
48 The group names are matched, they don't have to be fully qualified."
49   :group 'gnus-registry
50   :type '(repeat string))
51
52 (defcustom gnus-registry-install nil
53   "Whether the registry should be installed."
54   :group 'gnus-registry
55   :type 'boolean)
56
57 (defcustom gnus-registry-cache-file "~/.gnus.registry.eld"
58   "File where the Gnus registry will be stored."
59   :group 'gnus-registry
60   :type 'file)
61
62 (defcustom gnus-registry-max-entries nil
63   "Maximum number of entries in the registry, nil for unlimited."
64   :group 'gnus-registry
65   :type 'integer)
66
67 ;; Function(s) missing in Emacs 20
68 (when (memq nil (mapcar 'fboundp '(puthash)))
69   (require 'cl)
70   (unless (fboundp 'puthash)
71     ;; alias puthash is missing from Emacs 20 cl-extra.el
72     (defalias 'puthash 'cl-puthash)))
73
74 (defun gnus-registry-cache-read ()
75   "Read the registry cache file."
76   (interactive)
77   (let ((file gnus-registry-cache-file))
78     (when (file-exists-p file)
79       (gnus-message 5 "Reading %s..." file)
80       (gnus-load file)
81       (gnus-message 5 "Reading %s...done" file))))
82
83 (defun gnus-registry-cache-save ()
84   "Save the registry cache file."
85   (interactive)
86   (let ((file gnus-registry-cache-file))
87     (save-excursion
88       (set-buffer (gnus-get-buffer-create " *Gnus-registry-cache*"))
89       (make-local-variable 'version-control)
90     (setq version-control gnus-backup-startup-file)
91     (setq buffer-file-name file)
92     (setq default-directory (file-name-directory buffer-file-name))
93     (buffer-disable-undo)
94     (erase-buffer)
95     (gnus-message 5 "Saving %s..." file)
96     (if gnus-save-startup-file-via-temp-buffer
97         (let ((coding-system-for-write gnus-ding-file-coding-system)
98               (standard-output (current-buffer)))
99           (gnus-gnus-to-quick-newsrc-format t "gnus registry startup file" 'gnus-registry-alist)
100           (gnus-registry-cache-whitespace file)
101           (save-buffer))
102       (let ((coding-system-for-write gnus-ding-file-coding-system)
103             (version-control gnus-backup-startup-file)
104             (startup-file file)
105             (working-dir (file-name-directory file))
106             working-file
107             (i -1))
108         ;; Generate the name of a non-existent file.
109         (while (progn (setq working-file
110                             (format
111                              (if (and (eq system-type 'ms-dos)
112                                       (not (gnus-long-file-names)))
113                                  "%s#%d.tm#" ; MSDOS limits files to 8+3
114                                (if (memq system-type '(vax-vms axp-vms))
115                                    "%s$tmp$%d"
116                                  "%s#tmp#%d"))
117                              working-dir (setq i (1+ i))))
118                       (file-exists-p working-file)))
119         
120         (unwind-protect
121             (progn
122               (gnus-with-output-to-file working-file
123                 (gnus-gnus-to-quick-newsrc-format t "gnus registry startup file" 'gnus-registry-alist))
124               
125               ;; These bindings will mislead the current buffer
126               ;; into thinking that it is visiting the startup
127               ;; file.
128               (let ((buffer-backed-up nil)
129                     (buffer-file-name startup-file)
130                     (file-precious-flag t)
131                     (setmodes (file-modes startup-file)))
132                 ;; Backup the current version of the startup file.
133                 (backup-buffer)
134                 
135                 ;; Replace the existing startup file with the temp file.
136                 (rename-file working-file startup-file t)
137                 (set-file-modes startup-file setmodes)))
138           (condition-case nil
139               (delete-file working-file)
140             (file-error nil)))))
141     
142     (gnus-kill-buffer (current-buffer))
143     (gnus-message 5 "Saving %s...done" file))))
144
145 ;; Idea from Dan Christensen <jdc@chow.mat.jhu.edu>
146 ;; Save the gnus-registry file with extra line breaks.
147 (defun gnus-registry-cache-whitespace (filename)
148   (gnus-message 4 "Adding whitespace to %s" filename)
149   (save-excursion
150     (goto-char (point-min))
151     (while (re-search-forward "^(\\|(\\\"" nil t)
152       (replace-match "\n\\&" t))
153     (goto-char (point-min))
154     (while (re-search-forward " $" nil t)
155       (replace-match "" t t))))
156
157 (defun gnus-registry-save (&optional force)
158 ;; TODO: delete entries with 0 groups
159   (when (or gnus-registry-dirty force)
160     (setq gnus-registry-alist (gnus-registry-trim 
161                                (hashtable-to-alist gnus-registry-hashtb)))
162     (gnus-registry-cache-save)
163     (setq gnus-registry-dirty nil)))
164
165 (defun gnus-registry-read ()
166   (gnus-registry-cache-read)
167   (setq gnus-registry-hashtb (alist-to-hashtable gnus-registry-alist))
168   (setq gnus-registry-dirty nil))
169
170 (defun gnus-registry-trim (alist)
171   "Trim alist to size, using gnus-registry-max-entries."
172   (unless (null gnus-registry-max-entries)
173     (let ((timehash (make-hash-table                        
174                      :size 4096
175                      :test 'equal)))
176       (maphash
177        (lambda (key value)
178          (puthash key (gnus-registry-fetch-extra key 'mtime) timehash))
179        gnus-registry-hashtb)
180
181       (setq alist
182             (nthcdr
183              (- (length alist) gnus-registry-max-entries)
184              (sort alist 
185                    (lambda (a b)
186                      (time-less-p 
187                       (cdr (gethash (car a) timehash))
188                       (cdr (gethash (car b) timehash))))))))))
189
190 (defun alist-to-hashtable (alist)
191   "Build a hashtable from the values in ALIST."
192   (let ((ht (make-hash-table                        
193              :size 4096
194              :test 'equal)))
195     (mapc
196      (lambda (kv-pair)
197        (puthash (car kv-pair) (cdr kv-pair) ht))
198      alist)
199      ht))
200
201 (defun hashtable-to-alist (hash)
202   "Build an alist from the values in HASH."
203   (let ((list nil))
204     (maphash
205      (lambda (key value)
206        (setq list (cons (cons key value) list)))
207      hash)
208     list))
209
210 (defun gnus-register-action (action data-header from &optional to method)
211   (let* ((id (mail-header-id data-header))
212         (from (gnus-group-guess-full-name from))
213         (to (if to (gnus-group-guess-full-name to) nil))
214         (to-name (if to to "the Bit Bucket"))
215         (old-entry (gethash id gnus-registry-hashtb)))
216     (gnus-message 5 "Registry: article %s %s from %s to %s"
217                   id
218                   (if method "respooling" "going")
219                   from
220                   to)
221
222     ;; All except copy will need a delete
223     (gnus-registry-delete-group id from)
224
225     (when (equal 'copy action) 
226       (gnus-registry-add-group id from)) ; undo the delete
227
228     (gnus-registry-add-group id to)))
229
230 (defun gnus-register-spool-action (id group)
231   ;; do not process the draft IDs
232 ;  (unless (string-match "totally-fudged-out-message-id" id)
233 ;    (let ((group (gnus-group-guess-full-name group)))
234   (when (string-match "\r$" id)
235     (setq id (substring id 0 -1)))
236   (gnus-message 5 "Registry: article %s spooled to %s"
237                 id
238                 group)
239   (gnus-registry-add-group id group))
240 ;)
241
242 ;; Function for nn{mail|imap}-split-fancy: look up all references in
243 ;; the cache and if a match is found, return that group.
244 (defun gnus-registry-split-fancy-with-parent ()
245   "Split this message into the same group as its parent.  The parent
246 is obtained from the registry.  This function can be used as an entry
247 in `nnmail-split-fancy' or `nnimap-split-fancy', for example like
248 this: (: gnus-registry-split-fancy-with-parent) 
249
250 For a message to be split, it looks for the parent message in the
251 References or In-Reply-To header and then looks in the registry to
252 see which group that message was put in.  This group is returned.
253
254 See the Info node `(gnus)Fancy Mail Splitting' for more details."
255   (let ((refstr (or (message-fetch-field "references")
256                     (message-fetch-field "in-reply-to")))
257         (nnmail-split-fancy-with-parent-ignore-groups
258          (if (listp nnmail-split-fancy-with-parent-ignore-groups)
259              nnmail-split-fancy-with-parent-ignore-groups
260            (list nnmail-split-fancy-with-parent-ignore-groups)))
261         references res)
262     (when refstr
263       (setq references (nreverse (gnus-split-references refstr)))
264       (mapcar (lambda (x)
265                 (setq res (or (gnus-registry-fetch-group x) res))
266                 (when (or (gnus-registry-grep-in-list 
267                            res
268                            gnus-registry-unfollowed-groups)
269                           (gnus-registry-grep-in-list 
270                            res 
271                            nnmail-split-fancy-with-parent-ignore-groups))
272                   (setq res nil)))
273               references)
274       (gnus-message 
275        5 
276        "gnus-registry-split-fancy-with-parent traced %s to group %s"
277        refstr (if res res "nil"))
278       res)))
279
280 (defun gnus-registry-register-message-ids ()
281   "Register the Message-ID of every article in the group"
282   (unless (gnus-parameter-registry-ignore gnus-newsgroup-name)
283     (dolist (article gnus-newsgroup-articles)
284       (let ((id (gnus-registry-fetch-message-id-fast article)))
285         (unless (gnus-registry-fetch-group id)
286           (gnus-message 9 "Registry: Registering article %d with group %s" 
287                         article gnus-newsgroup-name)
288           (gnus-registry-add-group (gnus-registry-fetch-message-id-fast article)
289                                    gnus-newsgroup-name))))))
290
291 (defun gnus-registry-fetch-message-id-fast (article)
292   "Fetch the Message-ID quickly, using the internal gnus-data-list function"
293   (if (and (numberp article)
294            (assoc article (gnus-data-list nil)))
295       (mail-header-id (gnus-data-header (assoc article (gnus-data-list nil))))
296     nil))
297
298 (defun gnus-registry-grep-in-list (word list)
299   (when word
300     (memq nil
301           (mapcar 'not
302                   (mapcar 
303                    (lambda (x)
304                      (string-match x word))
305                    list)))))
306
307 (defun gnus-registry-fetch-extra (id &optional entry)
308   "Get the extra data of a message, based on the message ID.
309 Returns the first place where the trail finds a nonstring."
310   (let ((trail (gethash id gnus-registry-hashtb)))
311     (dolist (crumb trail)
312       (unless (stringp crumb)
313         (return (gnus-registry-fetch-extra-entry crumb entry))))))
314
315 (defun gnus-registry-fetch-extra-entry (alist &optional entry)
316   "Get the extra data of a message, or a specific entry in it."
317   (if entry
318       (assq entry alist)
319     alist))
320
321 (defun gnus-registry-store-extra (id extra)
322   "Store the extra data of a message, based on the message ID.
323 The message must have at least one group name."
324   (when (gnus-registry-group-count id)
325     ;; we now know the trail has at least 1 group name, so it's not empty
326     (let ((trail (gethash id gnus-registry-hashtb))
327           (old-extra (gnus-registry-fetch-extra id)))
328       (puthash id (cons extra (delete old-extra trail))
329                gnus-registry-hashtb)
330       (setq gnus-registry-dirty t))))
331
332 (defun gnus-registry-store-extra-entry (id key value)
333   "Put a specific entry in the extras field of the registry entry for id."
334   (let* ((extra (gnus-registry-fetch-extra id))
335          (alist (cons (cons key value)
336                  (gnus-assq-delete-all key (gnus-registry-fetch-extra id)))))
337     (gnus-registry-store-extra id alist)))
338
339 (defun gnus-registry-fetch-group (id)
340   "Get the group of a message, based on the message ID.
341 Returns the first place where the trail finds a group name."
342   (when (gnus-registry-group-count id)
343     ;; we now know the trail has at least 1 group name
344     (let ((trail (gethash id gnus-registry-hashtb)))
345       (dolist (crumb trail)
346         (when (stringp crumb)
347           (return crumb))))))
348
349 (defun gnus-registry-group-count (id)
350   "Get the number of groups of a message, based on the message ID."
351   (let ((trail (gethash id gnus-registry-hashtb)))
352     (if (and trail (listp trail))
353         (apply '+ (mapcar (lambda (x) (if (stringp x) 1 0)) trail))
354       0)))
355
356 (defun gnus-registry-delete-group (id group)
357   "Delete a group for a message, based on the message ID."
358   (when group
359     (when id
360       (let ((trail (gethash id gnus-registry-hashtb))
361             (group (gnus-group-short-name group)))
362         (puthash id (if trail
363                         (delete group trail)
364                       nil)
365                  gnus-registry-hashtb))
366       ;; now, clear the entry if there are no more groups
367       (unless (gnus-registry-group-count id)
368         (remhash id gnus-registry-hashtb))
369       (gnus-registry-store-extra-entry id 'mtime (current-time)))))
370
371 (defun gnus-registry-add-group (id group &rest extra)
372   "Add a group for a message, based on the message ID."
373   ;; make sure there are no duplicate entries
374   (when group
375     (when (and id
376                (not (string-match "totally-fudged-out-message-id" id)))
377       (let ((group (gnus-group-short-name group)))
378         (gnus-registry-delete-group id group)   
379         (let ((trail (gethash id gnus-registry-hashtb)))
380           (puthash id (if trail
381                           (cons group trail)
382                         (list group))
383                    gnus-registry-hashtb)
384           (when extra (gnus-registry-store-extra id extra))
385           (gnus-registry-store-extra-entry id 'mtime (current-time)))))))
386
387 (defun gnus-registry-clear ()
388   "Clear the Gnus registry."
389   (interactive)
390   (setq gnus-registry-alist nil)
391   (setq gnus-registry-hashtb (alist-to-hashtable gnus-registry-alist))
392   (setq gnus-registry-dirty t))
393
394 (defun gnus-registry-install-hooks ()
395   "Install the registry hooks."
396   (interactive)
397   (add-hook 'gnus-summary-article-move-hook 'gnus-register-action) 
398   (add-hook 'gnus-summary-article-delete-hook 'gnus-register-action)
399   (add-hook 'gnus-summary-article-expire-hook 'gnus-register-action)
400   (add-hook 'nnmail-spool-hook 'gnus-register-spool-action)
401   
402   (add-hook 'gnus-save-newsrc-hook 'gnus-registry-save)
403   (add-hook 'gnus-read-newsrc-el-hook 'gnus-registry-read)
404
405   (add-hook 'gnus-summary-prepare-hook 'gnus-registry-register-message-ids))
406
407 (when gnus-registry-install
408   (gnus-registry-install-hooks))
409
410 ;; TODO: a lot of things
411
412 (provide 'gnus-registry)
413
414 ;;; gnus-registry.el ends here