64040aebab91e4735f808b52bcb75c4ddc30bd53
[elisp/gnus.git-] / 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 ;; This is the gnus-registry.el package, works with other backends
28 ;; besides nnmail.  The major issue is that it doesn't go across
29 ;; backends, so for instance if an article is in nnml:sys and you see
30 ;; a reference to it in nnimap splitting, the article will end up in
31 ;; nnimap:sys
32
33 ;; gnus-registry.el intercepts article respooling, moving, deleting,
34 ;; and copying for all backends.  If it doesn't work correctly for
35 ;; you, submit a bug report and I'll be glad to fix it.  It needs
36 ;; documentation in the manual (also on my to-do list).
37
38 ;; Put this in your startup file (~/.gnus.el for instance)
39
40 ;; (setq gnus-registry-max-entries 2500
41 ;;       gnus-registry-use-long-group-names t)
42
43 ;; (gnus-registry-initialize)
44
45 ;; Then use this in your fancy-split:
46
47 ;; (: gnus-registry-split-fancy-with-parent)
48
49 ;; TODO:
50
51 ;; - get the correct group on spool actions
52
53 ;; - articles that are spooled to a different backend should be handled
54
55 ;;; Code:
56
57 (eval-when-compile (require 'cl))
58
59 (require 'gnus)
60 (require 'gnus-int)
61 (require 'gnus-sum)
62 (require 'nnmail)
63
64 (defvar gnus-registry-dirty t
65  "Boolean set to t when the registry is modified")
66
67 (defgroup gnus-registry nil
68   "The Gnus registry."
69   :group 'gnus)
70
71 (defvar gnus-registry-hashtb nil
72   "*The article registry by Message ID.")
73
74 (defcustom gnus-registry-unfollowed-groups '("delayed" "drafts" "queue")
75   "List of groups that gnus-registry-split-fancy-with-parent won't follow.
76 The group names are matched, they don't have to be fully qualified."
77   :group 'gnus-registry
78   :type '(repeat string))
79
80 (defcustom gnus-registry-install nil
81   "Whether the registry should be installed."
82   :group 'gnus-registry
83   :type 'boolean)
84
85 (defcustom gnus-registry-clean-empty t
86   "Whether the empty registry entries should be deleted.
87 Registry entries are considered empty when they have no groups."
88   :group 'gnus-registry
89   :type 'boolean)
90
91 (defcustom gnus-registry-use-long-group-names nil
92   "Whether the registry should use long group names (BUGGY)."
93   :group 'gnus-registry
94   :type 'boolean)
95
96 (defcustom gnus-registry-track-extra nil
97   "Whether the registry should track other things about a message.
98 The Subject header is currently the only thing that can be
99 tracked this way."
100   :group 'gnus-registry
101   :type 'boolean)
102
103 (defcustom gnus-registry-entry-caching t
104   "Whether the registry should cache extra information."
105   :group 'gnus-registry
106   :type 'boolean)
107
108 (defcustom gnus-registry-minimum-subject-length 5
109   "The minimum length of a subject before it's considered trackable."
110   :group 'gnus-registry
111   :type 'integer)
112
113 (defcustom gnus-registry-trim-articles-without-groups t
114   "Whether the registry should clean out message IDs without groups."
115   :group 'gnus-registry
116   :type 'boolean)
117
118 (defcustom gnus-registry-cache-file "~/.gnus.registry.eld"
119   "File where the Gnus registry will be stored."
120   :group 'gnus-registry
121   :type 'file)
122
123 (defcustom gnus-registry-max-entries nil
124   "Maximum number of entries in the registry, nil for unlimited."
125   :group 'gnus-registry
126   :type '(radio (const :format "Unlimited " nil)
127                 (integer :format "Maximum number: %v\n" :size 0)))
128
129 ;; Function(s) missing in Emacs 20
130 (when (memq nil (mapcar 'fboundp '(puthash)))
131   (require 'cl)
132   (unless (fboundp 'puthash)
133     ;; alias puthash is missing from Emacs 20 cl-extra.el
134     (defalias 'puthash 'cl-puthash)))
135
136 (defun gnus-registry-cache-read ()
137   "Read the registry cache file."
138   (interactive)
139   (let ((file gnus-registry-cache-file))
140     (when (file-exists-p file)
141       (gnus-message 5 "Reading %s..." file)
142       (gnus-load file)
143       (gnus-message 5 "Reading %s...done" file))))
144
145 (defun gnus-registry-cache-save ()
146   "Save the registry cache file."
147   (interactive)
148   (let ((file gnus-registry-cache-file))
149     (save-excursion
150       (set-buffer (gnus-get-buffer-create " *Gnus-registry-cache*"))
151       (make-local-variable 'version-control)
152     (setq version-control gnus-backup-startup-file)
153     (setq buffer-file-name file)
154     (setq default-directory (file-name-directory buffer-file-name))
155     (buffer-disable-undo)
156     (erase-buffer)
157     (gnus-message 5 "Saving %s..." file)
158     (if gnus-save-startup-file-via-temp-buffer
159         (let ((coding-system-for-write gnus-ding-file-coding-system)
160               (standard-output (current-buffer)))
161           (gnus-gnus-to-quick-newsrc-format t "gnus registry startup file" 'gnus-registry-alist)
162           (gnus-registry-cache-whitespace file)
163           (save-buffer))
164       (let ((coding-system-for-write gnus-ding-file-coding-system)
165             (version-control gnus-backup-startup-file)
166             (startup-file file)
167             (working-dir (file-name-directory file))
168             working-file
169             (i -1))
170         ;; Generate the name of a non-existent file.
171         (while (progn (setq working-file
172                             (format
173                              (if (and (eq system-type 'ms-dos)
174                                       (not (gnus-long-file-names)))
175                                  "%s#%d.tm#" ; MSDOS limits files to 8+3
176                                (if (memq system-type '(vax-vms axp-vms))
177                                    "%s$tmp$%d"
178                                  "%s#tmp#%d"))
179                              working-dir (setq i (1+ i))))
180                       (file-exists-p working-file)))
181         
182         (unwind-protect
183             (progn
184               (gnus-with-output-to-file working-file
185                 (gnus-gnus-to-quick-newsrc-format t "gnus registry startup file" 'gnus-registry-alist))
186               
187               ;; These bindings will mislead the current buffer
188               ;; into thinking that it is visiting the startup
189               ;; file.
190               (let ((buffer-backed-up nil)
191                     (buffer-file-name startup-file)
192                     (file-precious-flag t)
193                     (setmodes (file-modes startup-file)))
194                 ;; Backup the current version of the startup file.
195                 (backup-buffer)
196                 
197                 ;; Replace the existing startup file with the temp file.
198                 (rename-file working-file startup-file t)
199                 (set-file-modes startup-file setmodes)))
200           (condition-case nil
201               (delete-file working-file)
202             (file-error nil)))))
203     
204     (gnus-kill-buffer (current-buffer))
205     (gnus-message 5 "Saving %s...done" file))))
206
207 ;; Idea from Dan Christensen <jdc@chow.mat.jhu.edu>
208 ;; Save the gnus-registry file with extra line breaks.
209 (defun gnus-registry-cache-whitespace (filename)
210   (gnus-message 5 "Adding whitespace to %s" filename)
211   (save-excursion
212     (goto-char (point-min))
213     (while (re-search-forward "^(\\|(\\\"" nil t)
214       (replace-match "\n\\&" t))
215     (goto-char (point-min))
216     (while (re-search-forward " $" nil t)
217       (replace-match "" t t))))
218
219 (defun gnus-registry-save (&optional force)
220   (when (or gnus-registry-dirty force)
221     (let ((caching gnus-registry-entry-caching))
222       ;; turn off entry caching, so mtime doesn't get recorded
223       (setq gnus-registry-entry-caching nil)
224       ;; remove entry caches
225       (maphash
226        (lambda (key value)
227          (if (hash-table-p value)
228              (remhash key gnus-registry-hashtb)))
229        gnus-registry-hashtb)
230       ;; remove empty entries
231       (when gnus-registry-clean-empty 
232         (gnus-registry-clean-empty-function))
233       ;; now trim the registry appropriately
234       (setq gnus-registry-alist (gnus-registry-trim 
235                                  (hashtable-to-alist gnus-registry-hashtb)))
236       ;; really save
237       (gnus-registry-cache-save)
238       (setq gnus-registry-entry-caching caching)
239       (setq gnus-registry-dirty nil))))
240
241 (defun gnus-registry-clean-empty-function ()
242   "Remove all empty entries from the registry.  Returns count thereof."
243   (let ((count 0))
244     (maphash
245      (lambda (key value)
246        (unless (gnus-registry-fetch-group key)
247          (incf count)
248          (remhash key gnus-registry-hashtb)))
249      gnus-registry-hashtb)
250     count))
251
252 (defun gnus-registry-read ()
253   (gnus-registry-cache-read)
254   (setq gnus-registry-hashtb (alist-to-hashtable gnus-registry-alist))
255   (setq gnus-registry-dirty nil))
256
257 (defun gnus-registry-trim (alist)
258   "Trim alist to size, using gnus-registry-max-entries."
259   (if (null gnus-registry-max-entries)
260       alist                             ; just return the alist
261     ;; else, when given max-entries, trim the alist
262     (let ((timehash (make-hash-table                        
263                      :size 4096
264                      :test 'equal)))
265       (maphash
266        (lambda (key value)
267          (puthash key (gnus-registry-fetch-extra key 'mtime) timehash))
268        gnus-registry-hashtb)
269
270       ;; we use the return value of this setq, which is the trimmed alist
271       (setq alist
272             (nthcdr
273              (- (length alist) gnus-registry-max-entries)
274              (sort alist 
275                    (lambda (a b)
276                      (time-less-p 
277                       (cdr (gethash (car a) timehash))
278                       (cdr (gethash (car b) timehash))))))))))
279
280 (defun alist-to-hashtable (alist)
281   "Build a hashtable from the values in ALIST."
282   (let ((ht (make-hash-table                        
283              :size 4096
284              :test 'equal)))
285     (mapc
286      (lambda (kv-pair)
287        (puthash (car kv-pair) (cdr kv-pair) ht))
288      alist)
289      ht))
290
291 (defun hashtable-to-alist (hash)
292   "Build an alist from the values in HASH."
293   (let ((list nil))
294     (maphash
295      (lambda (key value)
296        (setq list (cons (cons key value) list)))
297      hash)
298     list))
299
300 (defun gnus-registry-action (action data-header from &optional to method)
301   (let* ((id (mail-header-id data-header))
302          (subject (gnus-registry-simplify-subject 
303                    (mail-header-subject data-header)))
304         (from (gnus-group-guess-full-name from))
305         (to (if to (gnus-group-guess-full-name to) nil))
306         (to-name (if to to "the Bit Bucket"))
307         (old-entry (gethash id gnus-registry-hashtb)))
308     (gnus-message 5 "Registry: article %s %s from %s to %s"
309                   id
310                   (if method "respooling" "going")
311                   from
312                   to)
313
314     ;; All except copy will need a delete
315     (gnus-registry-delete-group id from)
316
317     (when (equal 'copy action) 
318       (gnus-registry-add-group id from subject)) ; undo the delete
319
320     (gnus-registry-add-group id to subject)))
321
322 (defun gnus-registry-spool-action (id group &optional subject)
323   ;; do not process the draft IDs
324 ;  (unless (string-match "totally-fudged-out-message-id" id)
325 ;    (let ((group (gnus-group-guess-full-name group)))
326   (when (and (stringp id) (string-match "\r$" id))
327     (setq id (substring id 0 -1)))
328   (gnus-message 5 "Registry: article %s spooled to %s"
329                 id
330                 group)
331   (gnus-registry-add-group id group subject))
332 ;)
333
334 ;; Function for nn{mail|imap}-split-fancy: look up all references in
335 ;; the cache and if a match is found, return that group.
336 (defun gnus-registry-split-fancy-with-parent ()
337   "Split this message into the same group as its parent.  The parent
338 is obtained from the registry.  This function can be used as an entry
339 in `nnmail-split-fancy' or `nnimap-split-fancy', for example like
340 this: (: gnus-registry-split-fancy-with-parent) 
341
342 For a message to be split, it looks for the parent message in the
343 References or In-Reply-To header and then looks in the registry to
344 see which group that message was put in.  This group is returned.
345
346 See the Info node `(gnus)Fancy Mail Splitting' for more details."
347   (let ((refstr (or (message-fetch-field "references")
348                     (message-fetch-field "in-reply-to")))
349         (nnmail-split-fancy-with-parent-ignore-groups
350          (if (listp nnmail-split-fancy-with-parent-ignore-groups)
351              nnmail-split-fancy-with-parent-ignore-groups
352            (list nnmail-split-fancy-with-parent-ignore-groups)))
353         references res)
354     (if refstr
355         (progn
356           (setq references (nreverse (gnus-split-references refstr)))
357           (mapcar (lambda (x)
358                     (setq res (or (gnus-registry-fetch-group x) res))
359                     (when (or (gnus-registry-grep-in-list
360                                res
361                                gnus-registry-unfollowed-groups)
362                               (gnus-registry-grep-in-list 
363                                res
364                                nnmail-split-fancy-with-parent-ignore-groups))
365                       (setq res nil)))
366                   references))
367       ;; there were no references, now try the extra tracking
368       (when gnus-registry-track-extra
369         (let ((subject (gnus-registry-simplify-subject 
370                         (message-fetch-field "subject"))))
371           (when (and subject
372                      (< gnus-registry-minimum-subject-length (length subject)))
373             (maphash
374              (lambda (key value)
375                (let ((this-subject (cdr 
376                                     (gnus-registry-fetch-extra key 'subject))))
377                  (when (and this-subject
378                             (equal subject this-subject))
379                    (setq res (gnus-registry-fetch-group key))
380                    (gnus-message
381                     ;; raise level of messaging if gnus-registry-track-extra
382                     (if gnus-registry-track-extra 5 9) 
383                     "%s (extra tracking) traced subject %s to group %s"
384                     "gnus-registry-split-fancy-with-parent"
385                     subject
386                     (if res res "nil")))))
387              gnus-registry-hashtb)))))
388     (gnus-message
389      5 
390      "gnus-registry-split-fancy-with-parent traced %s to group %s"
391      refstr (if res res "nil"))
392     res))
393
394 (defun gnus-registry-register-message-ids ()
395   "Register the Message-ID of every article in the group"
396   (unless (gnus-parameter-registry-ignore gnus-newsgroup-name)
397     (dolist (article gnus-newsgroup-articles)
398       (let ((id (gnus-registry-fetch-message-id-fast article)))
399         (unless (gnus-registry-fetch-group id)
400           (gnus-message 9 "Registry: Registering article %d with group %s" 
401                         article gnus-newsgroup-name)
402           (gnus-registry-add-group 
403            (gnus-registry-fetch-message-id-fast article)
404            gnus-newsgroup-name
405            (gnus-registry-fetch-simplified-message-subject-fast article)))))))
406
407 (defun gnus-registry-fetch-message-id-fast (article)
408   "Fetch the Message-ID quickly, using the internal gnus-data-list function"
409   (if (and (numberp article)
410            (assoc article (gnus-data-list nil)))
411       (mail-header-id (gnus-data-header (assoc article (gnus-data-list nil))))
412     nil))
413
414 (defun gnus-registry-simplify-subject (subject)
415   (if (stringp subject)
416       (gnus-simplify-subject subject)
417     nil))
418
419 (defun gnus-registry-fetch-simplified-message-subject-fast (article)
420   "Fetch the Subject quickly, using the internal gnus-data-list function"
421   (if (and (numberp article)
422            (assoc article (gnus-data-list nil)))
423       (gnus-registry-simplify-subject
424        (mail-header-subject (gnus-data-header
425                              (assoc article (gnus-data-list nil)))))
426     nil))
427
428 (defun gnus-registry-grep-in-list (word list)
429   (when word
430     (memq nil
431           (mapcar 'not
432                   (mapcar 
433                    (lambda (x)
434                      (string-match x word))
435                    list)))))
436
437 (defun gnus-registry-fetch-extra (id &optional entry)
438   "Get the extra data of a message, based on the message ID.
439 Returns the first place where the trail finds a nonstring."
440   (let ((entry-cache (gethash entry gnus-registry-hashtb)))
441     (if (and entry
442              (hash-table-p entry-cache)
443              (gethash id entry-cache))
444         (gethash id entry-cache)
445       ;; else, if there is no caching possible...
446       (let ((trail (gethash id gnus-registry-hashtb)))
447         (when (listp trail)
448           (dolist (crumb trail)
449             (unless (stringp crumb)
450               (return (gnus-registry-fetch-extra-entry crumb entry id)))))))))
451
452 (defun gnus-registry-fetch-extra-entry (alist &optional entry id)
453   "Get the extra data of a message, or a specific entry in it.
454 Update the entry cache if needed."
455   (if (and entry id)
456       (let ((entry-cache (gethash entry gnus-registry-hashtb))
457             entree)
458         (when gnus-registry-entry-caching
459           ;; create the hash table
460           (unless (hash-table-p entry-cache)
461             (setq entry-cache (make-hash-table
462                                :size 4096
463                                :test 'equal))
464             (puthash entry entry-cache gnus-registry-hashtb))
465
466           ;; get the entree from the hash table or from the alist
467           (setq entree (gethash id entry-cache)))
468         
469         (unless entree
470           (setq entree (assq entry alist))
471           (when gnus-registry-entry-caching
472             (puthash id entree entry-cache)))
473         entree)
474     alist))
475
476 (defun gnus-registry-store-extra (id extra)
477   "Store the extra data of a message, based on the message ID.
478 The message must have at least one group name."
479   (when (gnus-registry-group-count id)
480     ;; we now know the trail has at least 1 group name, so it's not empty
481     (let ((trail (gethash id gnus-registry-hashtb))
482           (old-extra (gnus-registry-fetch-extra id))
483           entry-cache)
484       (dolist (crumb trail)
485         (unless (stringp crumb)
486           (dolist (entry crumb)
487             (setq entry-cache (gethash (car entry) gnus-registry-hashtb))
488           (when entry-cache
489             (remhash id entry-cache))))
490       (puthash id (cons extra (delete old-extra trail))
491                gnus-registry-hashtb)
492       (setq gnus-registry-dirty t)))))
493
494 (defun gnus-registry-store-extra-entry (id key value)
495   "Put a specific entry in the extras field of the registry entry for id."
496   (let* ((extra (gnus-registry-fetch-extra id))
497          (alist (cons (cons key value)
498                  (gnus-assq-delete-all key (gnus-registry-fetch-extra id)))))
499     (gnus-registry-store-extra id alist)))
500
501 (defun gnus-registry-fetch-group (id)
502   "Get the group of a message, based on the message ID.
503 Returns the first place where the trail finds a group name."
504   (when (gnus-registry-group-count id)
505     ;; we now know the trail has at least 1 group name
506     (let ((trail (gethash id gnus-registry-hashtb)))
507       (dolist (crumb trail)
508         (when (stringp crumb)
509           (return (gnus-group-short-name crumb)))))))
510
511 (defun gnus-registry-group-count (id)
512   "Get the number of groups of a message, based on the message ID."
513   (let ((trail (gethash id gnus-registry-hashtb)))
514     (if (and trail (listp trail))
515         (apply '+ (mapcar (lambda (x) (if (stringp x) 1 0)) trail))
516       0)))
517
518 (defun gnus-registry-delete-group (id group)
519   "Delete a group for a message, based on the message ID."
520   (when group
521     (when id
522       (let ((trail (gethash id gnus-registry-hashtb))
523             (group (gnus-group-short-name group)))
524         (puthash id (if trail
525                         (delete group trail)
526                       nil)
527                  gnus-registry-hashtb))
528       ;; now, clear the entry if there are no more groups
529       (when gnus-registry-trim-articles-without-groups
530         (unless (gnus-registry-group-count id)
531           (gnus-registry-delete-id id)))
532       (gnus-registry-store-extra-entry id 'mtime (current-time)))))
533
534 (defun gnus-registry-delete-id (id)
535   "Delete a message ID from the registry."
536   (when (stringp id)
537     (remhash id gnus-registry-hashtb)
538     (maphash
539      (lambda (key value)
540        (when (hash-table-p value)
541          (remhash id value)))
542      gnus-registry-hashtb)))
543
544 (defun gnus-registry-add-group (id group &optional subject)
545   "Add a group for a message, based on the message ID."
546   ;; make sure there are no duplicate entries
547   (when group
548     (when (and id
549                (not (string-match "totally-fudged-out-message-id" id)))
550       (let ((full-group group)
551             (group (if gnus-registry-use-long-group-names 
552                        group 
553                      (gnus-group-short-name group))))
554         (gnus-registry-delete-group id group)
555         (unless gnus-registry-use-long-group-names 
556           (gnus-registry-delete-group id full-group))
557         (let ((trail (gethash id gnus-registry-hashtb)))
558           (puthash id (if trail
559                           (cons group trail)
560                         (list group))
561                    gnus-registry-hashtb)
562
563           (when gnus-registry-track-extra 
564             (gnus-registry-store-extra-entry 
565              id 
566              'subject 
567              (gnus-registry-simplify-subject subject)))
568           
569           (gnus-registry-store-extra-entry id 'mtime (current-time)))))))
570
571 (defun gnus-registry-clear ()
572   "Clear the Gnus registry."
573   (interactive)
574   (setq gnus-registry-alist nil)
575   (setq gnus-registry-hashtb (alist-to-hashtable gnus-registry-alist))
576   (setq gnus-registry-dirty t))
577
578 ;;;###autoload
579 (defun gnus-registry-initialize ()
580   (interactive)
581   (setq gnus-registry-install t)
582   (gnus-registry-install-hooks)
583   (gnus-registry-read))
584
585 ;;;###autoload
586 (defun gnus-registry-install-hooks ()
587   "Install the registry hooks."
588   (interactive)
589   (add-hook 'gnus-summary-article-move-hook 'gnus-registry-action) 
590   (add-hook 'gnus-summary-article-delete-hook 'gnus-registry-action)
591   (add-hook 'gnus-summary-article-expire-hook 'gnus-registry-action)
592   (add-hook 'nnmail-spool-hook 'gnus-registry-spool-action)
593   
594   (add-hook 'gnus-save-newsrc-hook 'gnus-registry-save)
595   (add-hook 'gnus-read-newsrc-el-hook 'gnus-registry-read)
596
597   (add-hook 'gnus-summary-prepare-hook 'gnus-registry-register-message-ids))
598
599 (defun gnus-registry-unload-hook ()
600   "Uninstall the registry hooks."
601   (interactive)
602   (remove-hook 'gnus-summary-article-move-hook 'gnus-registry-action) 
603   (remove-hook 'gnus-summary-article-delete-hook 'gnus-registry-action)
604   (remove-hook 'gnus-summary-article-expire-hook 'gnus-registry-action)
605   (remove-hook 'nnmail-spool-hook 'gnus-registry-spool-action)
606   
607   (remove-hook 'gnus-save-newsrc-hook 'gnus-registry-save)
608   (remove-hook 'gnus-read-newsrc-el-hook 'gnus-registry-read)
609
610   (remove-hook 'gnus-summary-prepare-hook 'gnus-registry-register-message-ids))
611
612 (when gnus-registry-install
613   (gnus-registry-install-hooks)
614   (gnus-registry-read))
615
616 ;; TODO: a lot of things
617
618 (provide 'gnus-registry)
619
620 ;;; gnus-registry.el ends here