d6491347395ef8d5ed3a4d9c63827801941e1cd4
[gnus] / lisp / gnus-registry.el
1 ;;; gnus-registry.el --- article registry for Gnus
2
3 ;;; Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008 
4 ;;; Free Software Foundation, Inc.
5
6 ;; Author: Ted Zlatanov <tzz@lifelogs.com>
7 ;; Keywords: news registry
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 3, or (at your option)
14 ;; any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, USA.
25
26 ;;; Commentary:
27
28 ;; This is the gnus-registry.el package, which works with all
29 ;; backends, not just nnmail (e.g. NNTP).  The major issue is that it
30 ;; doesn't go across backends, so for instance if an article is in
31 ;; nnml:sys and you see a reference to it in nnimap splitting, the
32 ;; article will end up in nnimap:sys
33
34 ;; gnus-registry.el intercepts article respooling, moving, deleting,
35 ;; and copying for all backends.  If it doesn't work correctly for
36 ;; you, submit a bug report and I'll be glad to fix it.  It needs
37 ;; documentation in the manual (also on my to-do list).
38
39 ;; Put this in your startup file (~/.gnus.el for instance)
40
41 ;; (setq gnus-registry-max-entries 2500
42 ;;       gnus-registry-use-long-group-names t)
43
44 ;; (gnus-registry-initialize)
45
46 ;; Then use this in your fancy-split:
47
48 ;; (: gnus-registry-split-fancy-with-parent)
49
50 ;; TODO:
51
52 ;; - get the correct group on spool actions
53
54 ;; - articles that are spooled to a different backend should be handled
55
56 ;;; Code:
57
58 (eval-when-compile (require 'cl))
59
60 (require 'gnus)
61 (require 'gnus-int)
62 (require 'gnus-sum)
63 (require 'gnus-util)
64 (require 'nnmail)
65
66 (defvar gnus-adaptive-word-syntax-table)
67
68 (defvar gnus-registry-dirty t
69  "Boolean set to t when the registry is modified")
70
71 (defgroup gnus-registry nil
72   "The Gnus registry."
73   :version "22.1"
74   :group 'gnus)
75
76 (defvar gnus-registry-hashtb (make-hash-table                       
77                               :size 256
78                               :test 'equal)
79   "*The article registry by Message ID.")
80
81 (defcustom gnus-registry-marks
82   '((Important
83      :char ?i
84      :image "summary_important")
85     (Work
86      :char ?w
87      :image "summary_work")
88     (Personal
89      :char ?p
90      :image "summary_personal")
91     (To-Do
92      :char ?t
93      :image "summary_todo")
94     (Later
95      :char ?l
96      :image "summary_later"))
97
98   "List of registry marks and their options.
99
100 `gnus-registry-mark-article' will offer symbols from this list
101 for completion.  
102
103 Each entry must have a character to be useful for summary mode
104 line display and for keyboard shortcuts.
105
106 Each entry must have an image string to be useful for visual
107 display."
108   :group 'gnus-registry
109   :type '(repeat :tag "Registry Marks"
110                  (cons :tag "Mark"
111                        (symbol :tag "Name")
112                        (checklist :tag "Options" :greedy t
113                                   (group :inline t
114                                          (const :format "" :value :char)
115                                          (character :tag "Character code"))
116                                   (group :inline t
117                                          (const :format "" :value :image)
118                                          (string :tag "Image"))))))
119
120 (defcustom gnus-registry-default-mark 'To-Do
121   "The default mark.  Should be a valid key for `gnus-registry-marks'."
122   :group 'gnus-registry
123   :type 'symbol)
124
125 (defcustom gnus-registry-unfollowed-groups 
126   '("delayed$" "drafts$" "queue$" "INBOX$")
127   "List of groups that gnus-registry-split-fancy-with-parent won't return.
128 The group names are matched, they don't have to be fully
129 qualified.  This parameter tells the Registry 'never split a
130 message into a group that matches one of these, regardless of
131 references.'"
132   :group 'gnus-registry
133   :type '(repeat regexp))
134
135 (defcustom gnus-registry-install 'ask
136   "Whether the registry should be installed."
137   :group 'gnus-registry
138   :type '(choice (const :tag "Never Install" nil)
139                  (const :tag "Always Install" t)
140                  (const :tag "Ask Me" ask)))
141
142 (defcustom gnus-registry-clean-empty t
143   "Whether the empty registry entries should be deleted.
144 Registry entries are considered empty when they have no groups
145 and no extra data."
146   :group 'gnus-registry
147   :type 'boolean)
148
149 (defcustom gnus-registry-use-long-group-names nil
150   "Whether the registry should use long group names (BUGGY)."
151   :group 'gnus-registry
152   :type 'boolean)
153
154 (defcustom gnus-registry-track-extra nil
155   "Whether the registry should track extra data about a message.
156 The Subject and Sender (From:) headers are currently tracked this
157 way."
158   :group 'gnus-registry
159   :type
160   '(set :tag "Tracking choices"
161     (const :tag "Track by subject (Subject: header)" subject)
162     (const :tag "Track by sender (From: header)"  sender)))
163
164 (defcustom gnus-registry-split-strategy nil
165   "Whether the registry should track extra data about a message.
166 The Subject and Sender (From:) headers are currently tracked this
167 way."
168   :group 'gnus-registry
169   :type
170   '(choice :tag "Tracking choices"
171            (const :tag "Only use single choices, discard multiple matches" nil)
172            (const :tag "Majority of matches wins" majority)
173            (const :tag "First found wins"  first)))
174
175 (defcustom gnus-registry-entry-caching t
176   "Whether the registry should cache extra information."
177   :group 'gnus-registry
178   :type 'boolean)
179
180 (defcustom gnus-registry-minimum-subject-length 5
181   "The minimum length of a subject before it's considered trackable."
182   :group 'gnus-registry
183   :type 'integer)
184
185 (defcustom gnus-registry-trim-articles-without-groups t
186   "Whether the registry should clean out message IDs without groups."
187   :group 'gnus-registry
188   :type 'boolean)
189
190 (defcustom gnus-registry-extra-entries-precious '(marks)
191   "What extra entries are precious, meaning they won't get trimmed.
192 When you save the Gnus registry, it's trimmed to be no longer
193 than `gnus-registry-max-entries' (which is nil by default, so no
194 trimming happens).  Any entries with extra data in this list (by
195 default, marks are included, so articles with marks are
196 considered precious) will not be trimmed."
197   :group 'gnus-registry
198   :type '(repeat symbol))
199
200 (defcustom gnus-registry-cache-file 
201   (nnheader-concat 
202    (or gnus-dribble-directory gnus-home-directory "~/") 
203    ".gnus.registry.eld")
204   "File where the Gnus registry will be stored."
205   :group 'gnus-registry
206   :type 'file)
207
208 (defcustom gnus-registry-max-entries nil
209   "Maximum number of entries in the registry, nil for unlimited."
210   :group 'gnus-registry
211   :type '(radio (const :format "Unlimited " nil)
212                 (integer :format "Maximum number: %v")))
213
214 (defun gnus-registry-track-subject-p ()
215   (memq 'subject gnus-registry-track-extra))
216
217 (defun gnus-registry-track-sender-p ()
218   (memq 'sender gnus-registry-track-extra))
219
220 (defun gnus-registry-cache-read ()
221   "Read the registry cache file."
222   (interactive)
223   (let ((file gnus-registry-cache-file))
224     (when (file-exists-p file)
225       (gnus-message 5 "Reading %s..." file)
226       (gnus-load file)
227       (gnus-message 5 "Reading %s...done" file))))
228
229 ;; FIXME: Get rid of duplicated code, cf. `gnus-save-newsrc-file' in
230 ;; `gnus-start.el'.  --rsteib
231 (defun gnus-registry-cache-save ()
232   "Save the registry cache file."
233   (interactive)
234   (let ((file gnus-registry-cache-file))
235     (save-excursion
236       (set-buffer (gnus-get-buffer-create " *Gnus-registry-cache*"))
237       (make-local-variable 'version-control)
238     (setq version-control gnus-backup-startup-file)
239     (setq buffer-file-name file)
240     (setq default-directory (file-name-directory buffer-file-name))
241     (buffer-disable-undo)
242     (erase-buffer)
243     (gnus-message 5 "Saving %s..." file)
244     (if gnus-save-startup-file-via-temp-buffer
245         (let ((coding-system-for-write gnus-ding-file-coding-system)
246               (standard-output (current-buffer)))
247           (gnus-gnus-to-quick-newsrc-format 
248            t "gnus registry startup file" 'gnus-registry-alist)
249           (gnus-registry-cache-whitespace file)
250           (save-buffer))
251       (let ((coding-system-for-write gnus-ding-file-coding-system)
252             (version-control gnus-backup-startup-file)
253             (startup-file file)
254             (working-dir (file-name-directory file))
255             working-file
256             (i -1))
257         ;; Generate the name of a non-existent file.
258         (while (progn (setq working-file
259                             (format
260                              (if (and (eq system-type 'ms-dos)
261                                       (not (gnus-long-file-names)))
262                                  "%s#%d.tm#" ; MSDOS limits files to 8+3
263                                (if (memq system-type '(vax-vms axp-vms))
264                                    "%s$tmp$%d"
265                                  "%s#tmp#%d"))
266                              working-dir (setq i (1+ i))))
267                       (file-exists-p working-file)))
268
269         (unwind-protect
270             (progn
271               (gnus-with-output-to-file working-file
272                 (gnus-gnus-to-quick-newsrc-format 
273                  t "gnus registry startup file" 'gnus-registry-alist))
274
275               ;; These bindings will mislead the current buffer
276               ;; into thinking that it is visiting the startup
277               ;; file.
278               (let ((buffer-backed-up nil)
279                     (buffer-file-name startup-file)
280                     (file-precious-flag t)
281                     (setmodes (file-modes startup-file)))
282                 ;; Backup the current version of the startup file.
283                 (backup-buffer)
284
285                 ;; Replace the existing startup file with the temp file.
286                 (rename-file working-file startup-file t)
287                 (gnus-set-file-modes startup-file setmodes)))
288           (condition-case nil
289               (delete-file working-file)
290             (file-error nil)))))
291
292     (gnus-kill-buffer (current-buffer))
293     (gnus-message 5 "Saving %s...done" file))))
294
295 ;; Idea from Dan Christensen <jdc@chow.mat.jhu.edu>
296 ;; Save the gnus-registry file with extra line breaks.
297 (defun gnus-registry-cache-whitespace (filename)
298   (gnus-message 7 "Adding whitespace to %s" filename)
299   (save-excursion
300     (goto-char (point-min))
301     (while (re-search-forward "^(\\|(\\\"" nil t)
302       (replace-match "\n\\&" t))
303     (goto-char (point-min))
304     (while (re-search-forward " $" nil t)
305       (replace-match "" t t))))
306
307 (defun gnus-registry-save (&optional force)
308   (when (or gnus-registry-dirty force)
309     (let ((caching gnus-registry-entry-caching))
310       ;; turn off entry caching, so mtime doesn't get recorded
311       (setq gnus-registry-entry-caching nil)
312       ;; remove entry caches
313       (maphash
314        (lambda (key value)
315          (if (hash-table-p value)
316              (remhash key gnus-registry-hashtb)))
317        gnus-registry-hashtb)
318       ;; remove empty entries
319       (when gnus-registry-clean-empty
320         (gnus-registry-clean-empty-function))
321       ;; now trim and clean text properties from the registry appropriately
322       (setq gnus-registry-alist 
323             (gnus-registry-remove-alist-text-properties
324              (gnus-registry-trim
325               (gnus-hashtable-to-alist
326                gnus-registry-hashtb))))
327       ;; really save
328       (gnus-registry-cache-save)
329       (setq gnus-registry-entry-caching caching)
330       (setq gnus-registry-dirty nil))))
331
332 (defun gnus-registry-clean-empty-function ()
333   "Remove all empty entries from the registry.  Returns count thereof."
334   (let ((count 0))
335
336     (maphash
337      (lambda (key value)
338        (when (stringp key)
339          (dolist (group (gnus-registry-fetch-groups key))
340            (when (gnus-parameter-registry-ignore group)
341              (gnus-message
342               10 
343               "gnus-registry: deleted ignored group %s from key %s"
344               group key)
345              (gnus-registry-delete-group key group)))
346
347          (unless (gnus-registry-group-count key)
348            (gnus-registry-delete-id key))
349
350          (unless (or
351                   (gnus-registry-fetch-group key)
352                   ;; TODO: look for specific extra data here!
353                   ;; in this example, we look for 'label
354                   (gnus-registry-fetch-extra key 'label))
355            (incf count)
356            (gnus-registry-delete-id key))
357          
358          (unless (stringp key)
359            (gnus-message 
360             10 
361             "gnus-registry key %s was not a string, removing" 
362             key)
363            (gnus-registry-delete-id key))))
364        
365      gnus-registry-hashtb)
366     count))
367
368 (defun gnus-registry-read ()
369   (gnus-registry-cache-read)
370   (setq gnus-registry-hashtb (gnus-alist-to-hashtable gnus-registry-alist))
371   (setq gnus-registry-dirty nil))
372
373 (defun gnus-registry-remove-alist-text-properties (v)
374   "Remove text properties from all strings in alist."
375   (if (stringp v)
376       (gnus-string-remove-all-properties v)
377     (if (and (listp v) (listp (cdr v)))
378         (mapcar 'gnus-registry-remove-alist-text-properties v)
379       (if (and (listp v) (stringp (cdr v)))
380           (cons (gnus-registry-remove-alist-text-properties (car v))
381                 (gnus-registry-remove-alist-text-properties (cdr v)))
382       v))))
383
384 (defun gnus-registry-trim (alist)
385   "Trim alist to size, using gnus-registry-max-entries.
386 Any entries with extra data (marks, currently) are left alone."
387   (if (null gnus-registry-max-entries)      
388       alist                             ; just return the alist
389     ;; else, when given max-entries, trim the alist
390     (let* ((timehash (make-hash-table
391                       :size 20000
392                       :test 'equal))
393            (precious (make-hash-table
394                       :size 20000
395                       :test 'equal))
396            (trim-length (- (length alist) gnus-registry-max-entries))
397            (trim-length (if (natnump trim-length) trim-length 0))
398            precious-list junk-list)
399       (maphash
400        (lambda (key value)
401          (let ((extra (gnus-registry-fetch-extra key)))
402            (dolist (item gnus-registry-extra-entries-precious)
403              (dolist (e extra)
404                (when (equal (nth 0 e) item)
405                  (puthash key t precious)
406                  (return))))
407            (puthash key (gnus-registry-fetch-extra key 'mtime) timehash)))
408        gnus-registry-hashtb)
409
410       (dolist (item alist)
411         (let ((key (nth 0 item)))
412           (if (gethash key precious)
413               (push item precious-list)
414             (push item junk-list))))
415
416       (sort 
417        junk-list
418        (lambda (a b)
419          (let ((t1 (or (cdr (gethash (car a) timehash)) 
420                        '(0 0 0)))
421                (t2 (or (cdr (gethash (car b) timehash)) 
422                        '(0 0 0))))
423            (time-less-p t1 t2))))
424
425       ;; we use the return value of this setq, which is the trimmed alist
426       (setq alist (append precious-list
427                           (nthcdr trim-length junk-list))))))
428   
429 (defun gnus-registry-action (action data-header from &optional to method)
430   (let* ((id (mail-header-id data-header))
431          (subject (gnus-string-remove-all-properties
432                    (gnus-registry-simplify-subject
433                     (mail-header-subject data-header))))
434          (sender (gnus-string-remove-all-properties 
435                   (mail-header-from data-header)))
436          (from (gnus-group-guess-full-name-from-command-method from))
437          (to (if to (gnus-group-guess-full-name-from-command-method to) nil))
438          (to-name (if to to "the Bit Bucket"))
439          (old-entry (gethash id gnus-registry-hashtb)))
440     (gnus-message 7 "Registry: article %s %s from %s to %s"
441                   id
442                   (if method "respooling" "going")
443                   from
444                   to)
445
446     ;; All except copy will need a delete
447     (gnus-registry-delete-group id from)
448
449     (when (equal 'copy action)
450       (gnus-registry-add-group id from subject sender)) ; undo the delete
451
452     (gnus-registry-add-group id to subject sender)))
453
454 (defun gnus-registry-spool-action (id group &optional subject sender)
455   (let ((group (gnus-group-guess-full-name-from-command-method group)))
456     (when (and (stringp id) (string-match "\r$" id))
457       (setq id (substring id 0 -1)))
458     (gnus-message 7 "Registry: article %s spooled to %s"
459                   id
460                   group)
461     (gnus-registry-add-group id group subject sender)))
462
463 ;; Function for nn{mail|imap}-split-fancy: look up all references in
464 ;; the cache and if a match is found, return that group.
465 (defun gnus-registry-split-fancy-with-parent ()
466   "Split this message into the same group as its parent.  The parent
467 is obtained from the registry.  This function can be used as an entry
468 in `nnmail-split-fancy' or `nnimap-split-fancy', for example like
469 this: (: gnus-registry-split-fancy-with-parent)
470
471 This function tracks ALL backends, unlike
472 `nnmail-split-fancy-with-parent' which tracks only nnmail
473 messages.
474
475 For a message to be split, it looks for the parent message in the
476 References or In-Reply-To header and then looks in the registry
477 to see which group that message was put in.  This group is
478 returned, unless `gnus-registry-follow-group-p' return nil for
479 that group.
480
481 See the Info node `(gnus)Fancy Mail Splitting' for more details."
482   (let* ((refstr (or (message-fetch-field "references") "")) ; guaranteed
483          (reply-to (message-fetch-field "in-reply-to"))      ; may be nil
484          ;; now, if reply-to is valid, append it to the References
485          (refstr (if reply-to 
486                      (concat refstr " " reply-to)
487                    refstr))
488          ;; these may not be used, but the code is cleaner having them up here
489          (sender (gnus-string-remove-all-properties
490                   (message-fetch-field "from")))
491          (subject (gnus-string-remove-all-properties
492                    (gnus-registry-simplify-subject
493                     (message-fetch-field "subject"))))
494
495          (nnmail-split-fancy-with-parent-ignore-groups
496           (if (listp nnmail-split-fancy-with-parent-ignore-groups)
497               nnmail-split-fancy-with-parent-ignore-groups
498             (list nnmail-split-fancy-with-parent-ignore-groups)))
499          (log-agent "gnus-registry-split-fancy-with-parent")
500          found found-full)
501
502     ;; this is a big if-else statement.  it uses
503     ;; gnus-registry-post-process-groups to filter the results after
504     ;; every step.
505     (cond
506      ;; the references string must be valid and parse to valid references
507      ((and refstr (gnus-extract-references refstr))
508       (dolist (reference (nreverse (gnus-extract-references refstr)))
509         (gnus-message
510          9
511          "%s is looking for matches for reference %s from [%s]"
512          log-agent reference refstr)
513         (dolist (group (gnus-registry-fetch-groups reference))
514           (when (and group (gnus-registry-follow-group-p group))
515             (gnus-message
516              7
517              "%s traced the reference %s from [%s] to group %s"
518              log-agent reference refstr group)
519             (push group found))))
520       ;; filter the found groups and return them
521       ;; the found groups are the full groups
522       (setq found (gnus-registry-post-process-groups 
523                    "references" refstr found found)))
524      
525      ;; else: there were no matches, now try the extra tracking by sender
526      ((and (gnus-registry-track-sender-p)
527            sender
528            (not (equal (gnus-extract-address-component-email sender)
529                        user-mail-address)))
530       (maphash
531        (lambda (key value)
532          (let ((this-sender (cdr
533                              (gnus-registry-fetch-extra key 'sender)))
534                matches)
535            (when (and this-sender
536                       (equal sender this-sender))
537              (let ((groups (gnus-registry-fetch-groups key)))
538                (dolist (group groups)
539                  (push group found-full)
540                  (setq found (append (list group) (delete group found)))))
541              (push key matches)
542              (gnus-message
543               ;; raise level of messaging if gnus-registry-track-extra
544               (if gnus-registry-track-extra 7 9)
545               "%s (extra tracking) traced sender %s to groups %s (keys %s)"
546               log-agent sender found matches))))
547        gnus-registry-hashtb)
548       ;; filter the found groups and return them
549       ;; the found groups are NOT the full groups
550       (setq found (gnus-registry-post-process-groups 
551                    "sender" sender found found-full)))
552       
553      ;; else: there were no matches, now try the extra tracking by subject
554      ((and (gnus-registry-track-subject-p)
555            subject
556            (< gnus-registry-minimum-subject-length (length subject)))
557       (maphash
558        (lambda (key value)
559          (let ((this-subject (cdr
560                               (gnus-registry-fetch-extra key 'subject)))
561                matches)
562            (when (and this-subject
563                       (equal subject this-subject))
564              (let ((groups (gnus-registry-fetch-groups key)))
565                (dolist (group groups)
566                  (push group found-full)
567                  (setq found (append (list group) (delete group found)))))
568              (push key matches)
569              (gnus-message
570               ;; raise level of messaging if gnus-registry-track-extra
571               (if gnus-registry-track-extra 7 9)
572               "%s (extra tracking) traced subject %s to groups %s (keys %s)"
573               log-agent subject found matches))))
574        gnus-registry-hashtb)
575       ;; filter the found groups and return them
576       ;; the found groups are NOT the full groups
577       (setq found (gnus-registry-post-process-groups 
578                    "subject" subject found found-full))))
579     ;; after the (cond) we extract the actual value safely
580     (car-safe found)))
581
582 (defun gnus-registry-post-process-groups (mode key groups groups-full)
583   "Modifies GROUPS found by MODE for KEY to determine which ones to follow.
584
585 MODE can be 'subject' or 'sender' for example.  The KEY is the
586 value by which MODE was searched.
587
588 Transforms each group name to the equivalent short name.
589
590 Checks if the current Gnus method (from `gnus-command-method' or
591 from `gnus-newsgroup-name') is the same as the group's method.
592 This is not possible if gnus-registry-use-long-group-names is
593 false.  Foreign methods are not supported so they are rejected.
594
595 Reduces the list to a single group, or complains if that's not
596 possible.  Uses `gnus-registry-split-strategy' and GROUPS-FULL if
597 necessary."
598   (let ((log-agent "gnus-registry-post-process-group")
599         out)
600
601     ;; the strategy can be 'first, 'majority, or nil
602     (when (eq gnus-registry-split-strategy 'first)
603       (when groups
604         (setq groups (list (car-safe groups)))))
605
606     (when (eq gnus-registry-split-strategy 'majority)
607       (let ((freq (make-hash-table
608                    :size 256
609                    :test 'equal)))
610         (mapc (lambda(x) (puthash x (1+ (gethash x freq 0)) freq)) groups-full)
611         (setq groups (list (car-safe
612                             (sort
613                              groups
614                              (lambda (a b)
615                                (> (gethash a freq 0)
616                                   (gethash b freq 0)))))))))
617     
618     (if gnus-registry-use-long-group-names
619         (dolist (group groups)
620           (let ((m1 (gnus-find-method-for-group group))
621                 (m2 (or gnus-command-method
622                         (gnus-find-method-for-group gnus-newsgroup-name)))
623                 (short-name (gnus-group-short-name group)))
624             (if (gnus-methods-equal-p m1 m2)
625                 (progn
626                   ;; this is REALLY just for debugging
627                   (gnus-message
628                    10
629                    "%s stripped group %s to %s"
630                    log-agent group short-name)
631                   (unless (member short-name out)
632                     (push short-name out)))
633               ;; else...
634               (gnus-message
635                7
636                "%s ignored foreign group %s"
637                log-agent group))))
638       (setq out groups))
639     (when (cdr-safe out)
640         (gnus-message
641          5
642          "%s: too many extra matches (%s) for %s %s.  Returning none."
643          log-agent out mode key)
644         (setq out nil))
645     out))
646
647 (defun gnus-registry-follow-group-p (group)
648   "Determines if a group name should be followed.
649 Consults `gnus-registry-unfollowed-groups' and
650 `nnmail-split-fancy-with-parent-ignore-groups'."
651   (not (or (gnus-registry-grep-in-list
652             group
653             gnus-registry-unfollowed-groups)
654            (gnus-registry-grep-in-list
655             group
656             nnmail-split-fancy-with-parent-ignore-groups))))
657
658 (defun gnus-registry-wash-for-keywords (&optional force)
659   (interactive)
660   (let ((id (gnus-registry-fetch-message-id-fast gnus-current-article))
661         word words)
662     (if (or (not (gnus-registry-fetch-extra id 'keywords))
663             force)
664         (save-excursion
665           (set-buffer gnus-article-buffer)
666           (article-goto-body)
667           (save-window-excursion
668             (save-restriction
669               (narrow-to-region (point) (point-max))
670               (with-syntax-table gnus-adaptive-word-syntax-table
671                 (while (re-search-forward "\\b\\w+\\b" nil t)
672                   (setq word (gnus-registry-remove-alist-text-properties
673                               (downcase (buffer-substring
674                                          (match-beginning 0) (match-end 0)))))
675                   (if (> (length word) 3)
676                       (push word words))))))
677           (gnus-registry-store-extra-entry id 'keywords words)))))
678
679 (defun gnus-registry-find-keywords (keyword)
680   (interactive "skeyword: ")
681   (let (articles)
682     (maphash
683      (lambda (key value)
684        (when (member keyword
685                    (cdr-safe (gnus-registry-fetch-extra key 'keywords)))
686          (push key articles)))
687      gnus-registry-hashtb)
688     articles))
689
690 (defun gnus-registry-register-message-ids ()
691   "Register the Message-ID of every article in the group"
692   (unless (gnus-parameter-registry-ignore gnus-newsgroup-name)
693     (dolist (article gnus-newsgroup-articles)
694       (let ((id (gnus-registry-fetch-message-id-fast article)))
695         (unless (member gnus-newsgroup-name (gnus-registry-fetch-groups id))
696           (gnus-message 9 "Registry: Registering article %d with group %s"
697                         article gnus-newsgroup-name)
698           (gnus-registry-add-group 
699            id 
700            gnus-newsgroup-name
701            (gnus-registry-fetch-simplified-message-subject-fast article)
702            (gnus-registry-fetch-sender-fast article)))))))
703
704 (defun gnus-registry-fetch-message-id-fast (article)
705   "Fetch the Message-ID quickly, using the internal gnus-data-list function"
706   (if (and (numberp article)
707            (assoc article (gnus-data-list nil)))
708       (mail-header-id (gnus-data-header (assoc article (gnus-data-list nil))))
709     nil))
710
711 (defun gnus-registry-simplify-subject (subject)
712   (if (stringp subject)
713       (gnus-simplify-subject subject)
714     nil))
715
716 (defun gnus-registry-fetch-simplified-message-subject-fast (article)
717   "Fetch the Subject quickly, using the internal gnus-data-list function"
718   (if (and (numberp article)
719            (assoc article (gnus-data-list nil)))
720       (gnus-string-remove-all-properties
721        (gnus-registry-simplify-subject
722         (mail-header-subject (gnus-data-header
723                               (assoc article (gnus-data-list nil))))))
724     nil))
725
726 (defun gnus-registry-fetch-sender-fast (article)
727   "Fetch the Sender quickly, using the internal gnus-data-list function"
728   (if (and (numberp article)
729            (assoc article (gnus-data-list nil)))
730       (gnus-string-remove-all-properties
731        (mail-header-from (gnus-data-header
732                           (assoc article (gnus-data-list nil)))))
733     nil))
734
735 (defun gnus-registry-grep-in-list (word list)
736 "Find if a WORD matches any regular expression in the given LIST."
737   (when (and word list)
738     (catch 'found
739       (dolist (r list)
740         (when (string-match r word)
741           (throw 'found r))))))
742
743 (defun gnus-registry-do-marks (type function)
744   "For each known mark, call FUNCTION for each cell of type TYPE.
745
746 FUNCTION should take two parameters, a mark symbol and the cell value."
747   (dolist (mark-info gnus-registry-marks)
748     (let* ((mark (car-safe mark-info))
749            (data (cdr-safe mark-info))
750            (cell-data (plist-get data type)))
751       (when cell-data
752         (funcall function mark cell-data)))))
753
754 ;;; this is ugly code, but I don't know how to do it better
755 (defun gnus-registry-install-shortcuts ()
756   "Install the keyboard shortcuts and menus for the registry.
757 Uses `gnus-registry-marks' to find what shortcuts to install."
758   (let (keys-plist)
759     (gnus-registry-do-marks 
760      :char
761      (lambda (mark data)
762        (let ((function-format
763               (format "gnus-registry-%%s-article-%s-mark" mark)))
764
765 ;;; The following generates these functions:
766 ;;; (defun gnus-registry-set-article-Important-mark (&rest articles)
767 ;;;   "Apply the Important mark to process-marked ARTICLES."
768 ;;;   (interactive (gnus-summary-work-articles current-prefix-arg))
769 ;;;   (gnus-registry-set-article-mark-internal 'Important articles nil t))
770 ;;; (defun gnus-registry-remove-article-Important-mark (&rest articles)
771 ;;;   "Apply the Important mark to process-marked ARTICLES."
772 ;;;   (interactive (gnus-summary-work-articles current-prefix-arg))
773 ;;;   (gnus-registry-set-article-mark-internal 'Important articles t t))
774
775          (dolist (remove '(t nil))
776            (let* ((variant-name (if remove "remove" "set"))
777                   (function-name (format function-format variant-name))
778                   (shortcut (format "%c" data))
779                   (shortcut (if remove (upcase shortcut) shortcut)))
780              (unintern function-name)
781              (eval
782               `(defun 
783                  ;; function name
784                  ,(intern function-name) 
785                  ;; parameter definition
786                  (&rest articles)
787                  ;; documentation
788                  ,(format 
789                    "%s the %s mark over process-marked ARTICLES."
790                    (upcase-initials variant-name)
791                    mark)
792                  ;; interactive definition
793                  (interactive 
794                   (gnus-summary-work-articles current-prefix-arg))
795                  ;; actual code
796
797                  ;; if this is called and the user doesn't want the
798                  ;; registry enabled, we'll ask anyhow
799                  (when (eq gnus-registry-install nil)
800                    (setq gnus-registry-install 'ask))
801
802                  ;; now the user is asked if gnus-registry-install is 'ask
803                  (when (gnus-registry-install-p)
804                    (gnus-registry-set-article-mark-internal 
805                     ;; all this just to get the mark, I must be doing it wrong
806                     (intern ,(symbol-name mark))
807                     articles ,remove t)
808                    (dolist (article articles)
809                      (gnus-summary-update-article 
810                       article 
811                       (assoc article (gnus-data-list nil)))))))
812              (push (intern function-name) keys-plist)
813              (push shortcut keys-plist)
814              (gnus-message 
815               9 
816               "Defined mark handling function %s" 
817               function-name))))))
818     (gnus-define-keys-1
819      '(gnus-registry-mark-map "M" gnus-summary-mark-map) 
820      keys-plist)))
821
822 ;;; use like this:
823 ;;; (defalias 'gnus-user-format-function-M 
824 ;;;           'gnus-registry-user-format-function-M)
825 (defun gnus-registry-user-format-function-M (headers)
826   (let* ((id (mail-header-message-id headers))
827          (marks (when id (gnus-registry-fetch-extra-marks id))))
828     (apply 'concat (mapcar (lambda(mark)
829                              (let ((c 
830                                     (plist-get
831                                      (cdr-safe 
832                                       (assoc mark gnus-registry-marks))
833                                      :char)))
834                                (if c
835                                    (list c)
836                                  nil)))
837                            marks))))
838
839 (defun gnus-registry-read-mark ()
840   "Read a mark name from the user with completion."
841   (let ((mark (gnus-completing-read-with-default 
842                (symbol-name gnus-registry-default-mark)
843                "Label" 
844                (mapcar (lambda (x)      ; completion list
845                          (cons (symbol-name (car-safe x)) (car-safe x)))
846                        gnus-registry-marks))))
847     (when (stringp mark)
848       (intern mark))))
849
850 (defun gnus-registry-set-article-mark (&rest articles)
851   "Apply a mark to process-marked ARTICLES."
852   (interactive (gnus-summary-work-articles current-prefix-arg))
853   (gnus-registry-set-article-mark-internal (gnus-registry-read-mark) articles nil t))
854
855 (defun gnus-registry-remove-article-mark (&rest articles)
856   "Remove a mark from process-marked ARTICLES."
857   (interactive (gnus-summary-work-articles current-prefix-arg))
858   (gnus-registry-set-article-mark-internal (gnus-registry-read-mark) articles t t))
859
860 (defun gnus-registry-set-article-mark-internal (mark articles &optional remove show-message)
861   "Apply a mark to a list of ARTICLES."
862   (let ((article-id-list
863          (mapcar 'gnus-registry-fetch-message-id-fast articles)))
864     (dolist (id article-id-list)
865       (let* (
866              ;; all the marks for this article without the mark of
867              ;; interest
868              (marks
869               (delq mark (gnus-registry-fetch-extra-marks id)))
870              ;; the new marks we want to use
871              (new-marks (if remove
872                             marks
873                           (cons mark marks))))
874         (when show-message
875           (gnus-message 1 "%s mark %s with message ID %s, resulting in %S"
876                         (if remove "Removing" "Adding")
877                         mark id new-marks))
878         
879         (apply 'gnus-registry-store-extra-marks ; set the extra marks
880                id                               ; for the message ID
881                new-marks)))))
882
883 (defun gnus-registry-get-article-marks (&rest articles)
884   "Get the Gnus registry marks for ARTICLES and show them if interactive.
885 Uses process/prefix conventions.  For multiple articles,
886 only the last one's marks are returned."
887   (interactive (gnus-summary-work-articles 1))
888   (let (marks)
889     (dolist (article articles)
890       (let ((article-id
891              (gnus-registry-fetch-message-id-fast article)))
892         (setq marks (gnus-registry-fetch-extra-marks article-id))))
893     (when (interactive-p)
894         (gnus-message 1 "Marks are %S" marks))
895     marks))
896
897 ;;; if this extends to more than 'marks, it should be improved to be more generic.
898 (defun gnus-registry-fetch-extra-marks (id)
899   "Get the marks of a message, based on the message ID.
900 Returns a list of symbol marks or nil."
901   (car-safe (cdr (gnus-registry-fetch-extra id 'marks))))
902
903 (defun gnus-registry-has-extra-mark (id mark)
904   "Checks if a message has `mark', based on the message ID `id'."
905   (memq mark (gnus-registry-fetch-extra-marks id)))
906
907 (defun gnus-registry-store-extra-marks (id &rest mark-list)
908   "Set the marks of a message, based on the message ID.
909 The `mark-list' can be nil, in which case no marks are left."
910   (gnus-registry-store-extra-entry id 'marks (list mark-list)))
911
912 (defun gnus-registry-delete-extra-marks (id &rest mark-delete-list)
913   "Delete the message marks in `mark-delete-list', based on the message ID."
914   (let ((marks (gnus-registry-fetch-extra-marks id)))
915     (when marks
916       (dolist (mark mark-delete-list)
917         (setq marks (delq mark marks))))
918     (gnus-registry-store-extra-marks id (car marks))))
919
920 (defun gnus-registry-delete-all-extra-marks (id)
921   "Delete all the marks for a message ID."
922   (gnus-registry-store-extra-marks id nil))
923
924 (defun gnus-registry-fetch-extra (id &optional entry)
925   "Get the extra data of a message, based on the message ID.
926 Returns the first place where the trail finds a nonstring."
927   (let ((entry-cache (gethash entry gnus-registry-hashtb)))
928     (if (and entry
929              (hash-table-p entry-cache)
930              (gethash id entry-cache))
931         (gethash id entry-cache)
932       ;; else, if there is no caching possible...
933       (let ((trail (gethash id gnus-registry-hashtb)))
934         (when (listp trail)
935           (dolist (crumb trail)
936             (unless (stringp crumb)
937               (return (gnus-registry-fetch-extra-entry crumb entry id)))))))))
938
939 (defun gnus-registry-fetch-extra-entry (alist &optional entry id)
940   "Get the extra data of a message, or a specific entry in it.
941 Update the entry cache if needed."
942   (if (and entry id)
943       (let ((entry-cache (gethash entry gnus-registry-hashtb))
944             entree)
945         (when gnus-registry-entry-caching
946           ;; create the hash table
947           (unless (hash-table-p entry-cache)
948             (setq entry-cache (make-hash-table
949                                :size 4096
950                                :test 'equal))
951             (puthash entry entry-cache gnus-registry-hashtb))
952
953           ;; get the entree from the hash table or from the alist
954           (setq entree (gethash id entry-cache)))
955
956         (unless entree
957           (setq entree (assq entry alist))
958           (when gnus-registry-entry-caching
959             (puthash id entree entry-cache)))
960         entree)
961     alist))
962
963 (defun gnus-registry-store-extra (id extra)
964   "Store the extra data of a message, based on the message ID.
965 The message must have at least one group name."
966   (when (gnus-registry-group-count id)
967     ;; we now know the trail has at least 1 group name, so it's not empty
968     (let ((trail (gethash id gnus-registry-hashtb))
969           (old-extra (gnus-registry-fetch-extra id))
970           entry-cache)
971       (dolist (crumb trail)
972         (unless (stringp crumb)
973           (dolist (entry crumb)
974             (setq entry-cache (gethash (car entry) gnus-registry-hashtb))
975           (when entry-cache
976             (remhash id entry-cache))))
977       (puthash id (cons extra (delete old-extra trail))
978                gnus-registry-hashtb)
979       (setq gnus-registry-dirty t)))))
980
981 (defun gnus-registry-delete-extra-entry (id key)
982   "Delete a specific entry in the extras field of the registry entry for id."
983   (gnus-registry-store-extra-entry id key nil))
984
985 (defun gnus-registry-store-extra-entry (id key value)
986   "Put a specific entry in the extras field of the registry entry for id."
987   (let* ((extra (gnus-registry-fetch-extra id))
988          ;; all the entries except the one for `key'
989          (the-rest (gnus-assq-delete-all key (gnus-registry-fetch-extra id))) 
990          (alist (if value
991                     (gnus-registry-remove-alist-text-properties
992                      (cons (cons key value)
993                            the-rest))
994                   the-rest)))
995     (gnus-registry-store-extra id alist)))
996
997 (defun gnus-registry-fetch-group (id)
998   "Get the group of a message, based on the message ID.
999 Returns the first place where the trail finds a group name."
1000   (when (gnus-registry-group-count id)
1001     ;; we now know the trail has at least 1 group name
1002     (let ((trail (gethash id gnus-registry-hashtb)))
1003       (dolist (crumb trail)
1004         (when (stringp crumb)
1005           (return (if gnus-registry-use-long-group-names
1006                        crumb
1007                      (gnus-group-short-name crumb))))))))
1008
1009 (defun gnus-registry-fetch-groups (id)
1010   "Get the groups of a message, based on the message ID."
1011   (let ((trail (gethash id gnus-registry-hashtb))
1012         groups)
1013     (dolist (crumb trail)
1014       (when (stringp crumb)
1015         ;; push the group name into the list
1016         (setq 
1017          groups
1018          (cons
1019           (if (or (not (stringp crumb)) gnus-registry-use-long-group-names)
1020               crumb
1021             (gnus-group-short-name crumb))
1022          groups))))
1023     ;; return the list of groups
1024     groups))
1025
1026 (defun gnus-registry-group-count (id)
1027   "Get the number of groups of a message, based on the message ID."
1028   (let ((trail (gethash id gnus-registry-hashtb)))
1029     (if (and trail (listp trail))
1030         (apply '+ (mapcar (lambda (x) (if (stringp x) 1 0)) trail))
1031       0)))
1032
1033 (defun gnus-registry-delete-group (id group)
1034   "Delete a group for a message, based on the message ID."
1035   (when (and group id)
1036       (let ((trail (gethash id gnus-registry-hashtb))
1037             (short-group (gnus-group-short-name group)))
1038         (puthash id (if trail
1039                         (delete short-group (delete group trail))
1040                       nil)
1041                  gnus-registry-hashtb))
1042       ;; now, clear the entry if there are no more groups
1043       (when gnus-registry-trim-articles-without-groups
1044         (unless (gnus-registry-group-count id)
1045           (gnus-registry-delete-id id)))
1046       ;; is this ID still in the registry?
1047       (when (gethash id gnus-registry-hashtb)
1048         (gnus-registry-store-extra-entry id 'mtime (current-time)))))
1049
1050 (defun gnus-registry-delete-id (id)
1051   "Delete a message ID from the registry."
1052   (when (stringp id)
1053     (remhash id gnus-registry-hashtb)
1054     (maphash
1055      (lambda (key value)
1056        (when (hash-table-p value)
1057          (remhash id value)))
1058      gnus-registry-hashtb)))
1059
1060 (defun gnus-registry-add-group (id group &optional subject sender)
1061   "Add a group for a message, based on the message ID."
1062   (when group
1063     (when (and id
1064                (not (string-match "totally-fudged-out-message-id" id)))
1065       (let ((full-group group)
1066             (group (if gnus-registry-use-long-group-names
1067                        group
1068                      (gnus-group-short-name group))))
1069         (gnus-registry-delete-group id group)
1070
1071         (unless gnus-registry-use-long-group-names ;; unnecessary in this case
1072           (gnus-registry-delete-group id full-group))
1073
1074         (let ((trail (gethash id gnus-registry-hashtb)))
1075           (puthash id (if trail
1076                           (cons group trail)
1077                         (list group))
1078                    gnus-registry-hashtb)
1079
1080           (when (and (gnus-registry-track-subject-p)
1081                      subject)
1082             (gnus-registry-store-extra-entry
1083              id
1084              'subject
1085              (gnus-registry-simplify-subject subject)))
1086           (when (and (gnus-registry-track-sender-p)
1087                      sender)
1088             (gnus-registry-store-extra-entry
1089              id
1090              'sender
1091              sender))
1092
1093           (gnus-registry-store-extra-entry id 'mtime (current-time)))))))
1094
1095 (defun gnus-registry-clear ()
1096   "Clear the Gnus registry."
1097   (interactive)
1098   (setq gnus-registry-alist nil)
1099   (setq gnus-registry-hashtb (gnus-alist-to-hashtable gnus-registry-alist))
1100   (setq gnus-registry-dirty t))
1101
1102 ;;;###autoload
1103 (defun gnus-registry-initialize ()
1104 "Initialize the Gnus registry."
1105   (interactive)
1106   (gnus-message 5 "Initializing the registry")
1107   (setq gnus-registry-install t)        ; in case it was 'ask or nil
1108   (gnus-registry-install-hooks)
1109   (gnus-registry-install-shortcuts)
1110   (gnus-registry-read))
1111
1112 ;;;###autoload
1113 (defun gnus-registry-install-hooks ()
1114   "Install the registry hooks."
1115   (interactive)
1116   (add-hook 'gnus-summary-article-move-hook 'gnus-registry-action)
1117   (add-hook 'gnus-summary-article-delete-hook 'gnus-registry-action)
1118   (add-hook 'gnus-summary-article-expire-hook 'gnus-registry-action)
1119   (add-hook 'nnmail-spool-hook 'gnus-registry-spool-action)
1120
1121   (add-hook 'gnus-save-newsrc-hook 'gnus-registry-save)
1122   (add-hook 'gnus-read-newsrc-el-hook 'gnus-registry-read)
1123
1124   (add-hook 'gnus-summary-prepare-hook 'gnus-registry-register-message-ids))
1125
1126 (defun gnus-registry-unload-hook ()
1127   "Uninstall the registry hooks."
1128   (interactive)
1129   (remove-hook 'gnus-summary-article-move-hook 'gnus-registry-action)
1130   (remove-hook 'gnus-summary-article-delete-hook 'gnus-registry-action)
1131   (remove-hook 'gnus-summary-article-expire-hook 'gnus-registry-action)
1132   (remove-hook 'nnmail-spool-hook 'gnus-registry-spool-action)
1133
1134   (remove-hook 'gnus-save-newsrc-hook 'gnus-registry-save)
1135   (remove-hook 'gnus-read-newsrc-el-hook 'gnus-registry-read)
1136
1137   (remove-hook 'gnus-summary-prepare-hook 'gnus-registry-register-message-ids))
1138
1139 (add-hook 'gnus-registry-unload-hook 'gnus-registry-unload-hook)
1140
1141 (defun gnus-registry-install-p ()
1142   (interactive)
1143   (when (eq gnus-registry-install 'ask)
1144     (setq gnus-registry-install
1145           (gnus-y-or-n-p
1146            (concat "Enable the Gnus registry?  "
1147                    "See the variable `gnus-registry-install' "
1148                    "to get rid of this query permanently. ")))
1149     (when gnus-registry-install
1150       ;; we just set gnus-registry-install to t, so initialize the registry!
1151       (gnus-registry-initialize)))
1152 ;;; we could call it here: (customize-variable 'gnus-registry-install)
1153   gnus-registry-install)
1154
1155 (when (or (eq gnus-registry-install t)
1156           (gnus-registry-install-p))
1157   (gnus-registry-initialize))
1158
1159 ;; TODO: a few things
1160
1161 (provide 'gnus-registry)
1162
1163 ;; arch-tag: 5cba0a32-718a-4a97-8c91-0a15af21da94
1164 ;;; gnus-registry.el ends here