(gnus-registry-grep-in-list): Fix logic, use
[gnus] / lisp / gnus-registry.el
1 ;;; gnus-registry.el --- article registry for Gnus
2
3 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;;   2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5
6 ;; Author: Ted Zlatanov <tzz@lifelogs.com>
7 ;; Keywords: news
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 sender user-mail-address)))
529       (maphash
530        (lambda (key value)
531          (let ((this-sender (cdr
532                              (gnus-registry-fetch-extra key 'sender)))
533                matches)
534            (when (and this-sender
535                       (equal sender this-sender))
536              (let ((groups (gnus-registry-fetch-groups key)))
537                (dolist (group groups)
538                  (push group found-full)
539                  (setq found (append (list group) (delete group found)))))
540              (push key matches)
541              (gnus-message
542               ;; raise level of messaging if gnus-registry-track-extra
543               (if gnus-registry-track-extra 7 9)
544               "%s (extra tracking) traced sender %s to groups %s (keys %s)"
545               log-agent sender found matches))))
546        gnus-registry-hashtb)
547       ;; filter the found groups and return them
548       ;; the found groups are NOT the full groups
549       (setq found (gnus-registry-post-process-groups 
550                    "sender" sender found found-full)))
551       
552      ;; else: there were no matches, now try the extra tracking by subject
553      ((and (gnus-registry-track-subject-p)
554            subject
555            (< gnus-registry-minimum-subject-length (length subject)))
556       (maphash
557        (lambda (key value)
558          (let ((this-subject (cdr
559                               (gnus-registry-fetch-extra key 'subject)))
560                matches)
561            (when (and this-subject
562                       (equal subject this-subject))
563              (let ((groups (gnus-registry-fetch-groups key)))
564                (dolist (group groups)
565                  (push group found-full)
566                  (setq found (append (list group) (delete group found)))))
567              (push key matches)
568              (gnus-message
569               ;; raise level of messaging if gnus-registry-track-extra
570               (if gnus-registry-track-extra 7 9)
571               "%s (extra tracking) traced subject %s to groups %s (keys %s)"
572               log-agent subject found matches))))
573        gnus-registry-hashtb)
574       ;; filter the found groups and return them
575       ;; the found groups are NOT the full groups
576       (setq found (gnus-registry-post-process-groups 
577                    "subject" subject found found-full))))
578     ;; after the (cond) we extract the actual value safely
579     (car-safe found)))
580
581 (defun gnus-registry-post-process-groups (mode key groups groups-full)
582   "Modifies GROUPS found by MODE for KEY to determine which ones to follow.
583
584 MODE can be 'subject' or 'sender' for example.  The KEY is the
585 value by which MODE was searched.
586
587 Transforms each group name to the equivalent short name.
588
589 Checks if the current Gnus method (from `gnus-command-method' or
590 from `gnus-newsgroup-name') is the same as the group's method.
591 This is not possible if gnus-registry-use-long-group-names is
592 false.  Foreign methods are not supported so they are rejected.
593
594 Reduces the list to a single group, or complains if that's not
595 possible.  Uses `gnus-registry-split-strategy' and GROUPS-FULL if
596 necessary."
597   (let ((log-agent "gnus-registry-post-process-group")
598         out)
599
600     ;; the strategy can be 'first, 'majority, or nil
601     (when (eq gnus-registry-split-strategy 'first)
602       (when groups
603         (setq groups (list (car-safe groups)))))
604
605     (when (eq gnus-registry-split-strategy 'majority)
606       (let ((freq (make-hash-table
607                    :size 256
608                    :test 'equal)))
609         (mapc (lambda(x) (puthash x (1+ (gethash x freq 0)) freq)) groups-full)
610         (setq groups (list (car-safe
611                             (sort
612                              groups
613                              (lambda (a b)
614                                (> (gethash a freq 0)
615                                   (gethash b freq 0)))))))))
616     
617     (if gnus-registry-use-long-group-names
618         (dolist (group groups)
619           (let ((m1 (gnus-find-method-for-group group))
620                 (m2 (or gnus-command-method
621                         (gnus-find-method-for-group gnus-newsgroup-name)))
622                 (short-name (gnus-group-short-name group)))
623             (if (gnus-methods-equal-p m1 m2)
624                 (progn
625                   ;; this is REALLY just for debugging
626                   (gnus-message
627                    10
628                    "%s stripped group %s to %s"
629                    log-agent group short-name)
630                   (unless (member short-name out)
631                     (push short-name out)))
632               ;; else...
633               (gnus-message
634                7
635                "%s ignored foreign group %s"
636                log-agent group))))
637       (setq out groups))
638     (when (cdr-safe out)
639         (gnus-message
640          5
641          "%s: too many extra matches (%s) for %s %s.  Returning none."
642          log-agent out mode key)
643         (setq out nil))
644     out))
645
646 (defun gnus-registry-follow-group-p (group)
647   "Determines if a group name should be followed.
648 Consults `gnus-registry-unfollowed-groups' and
649 `nnmail-split-fancy-with-parent-ignore-groups'."
650   (not (or (gnus-registry-grep-in-list
651             group
652             gnus-registry-unfollowed-groups)
653            (gnus-registry-grep-in-list
654             group
655             nnmail-split-fancy-with-parent-ignore-groups))))
656
657 (defun gnus-registry-wash-for-keywords (&optional force)
658   (interactive)
659   (let ((id (gnus-registry-fetch-message-id-fast gnus-current-article))
660         word words)
661     (if (or (not (gnus-registry-fetch-extra id 'keywords))
662             force)
663         (save-excursion
664           (set-buffer gnus-article-buffer)
665           (article-goto-body)
666           (save-window-excursion
667             (save-restriction
668               (narrow-to-region (point) (point-max))
669               (with-syntax-table gnus-adaptive-word-syntax-table
670                 (while (re-search-forward "\\b\\w+\\b" nil t)
671                   (setq word (gnus-registry-remove-alist-text-properties
672                               (downcase (buffer-substring
673                                          (match-beginning 0) (match-end 0)))))
674                   (if (> (length word) 3)
675                       (push word words))))))
676           (gnus-registry-store-extra-entry id 'keywords words)))))
677
678 (defun gnus-registry-find-keywords (keyword)
679   (interactive "skeyword: ")
680   (let (articles)
681     (maphash
682      (lambda (key value)
683        (when (member keyword
684                    (cdr-safe (gnus-registry-fetch-extra key 'keywords)))
685          (push key articles)))
686      gnus-registry-hashtb)
687     articles))
688
689 (defun gnus-registry-register-message-ids ()
690   "Register the Message-ID of every article in the group"
691   (unless (gnus-parameter-registry-ignore gnus-newsgroup-name)
692     (dolist (article gnus-newsgroup-articles)
693       (let ((id (gnus-registry-fetch-message-id-fast article)))
694         (unless (member gnus-newsgroup-name (gnus-registry-fetch-groups id))
695           (gnus-message 9 "Registry: Registering article %d with group %s"
696                         article gnus-newsgroup-name)
697           (gnus-registry-add-group 
698            id 
699            gnus-newsgroup-name
700            (gnus-registry-fetch-simplified-message-subject-fast article)
701            (gnus-registry-fetch-sender-fast article)))))))
702
703 (defun gnus-registry-fetch-message-id-fast (article)
704   "Fetch the Message-ID quickly, using the internal gnus-data-list function"
705   (if (and (numberp article)
706            (assoc article (gnus-data-list nil)))
707       (mail-header-id (gnus-data-header (assoc article (gnus-data-list nil))))
708     nil))
709
710 (defun gnus-registry-simplify-subject (subject)
711   (if (stringp subject)
712       (gnus-simplify-subject subject)
713     nil))
714
715 (defun gnus-registry-fetch-simplified-message-subject-fast (article)
716   "Fetch the Subject quickly, using the internal gnus-data-list function"
717   (if (and (numberp article)
718            (assoc article (gnus-data-list nil)))
719       (gnus-string-remove-all-properties
720        (gnus-registry-simplify-subject
721         (mail-header-subject (gnus-data-header
722                               (assoc article (gnus-data-list nil))))))
723     nil))
724
725 (defun gnus-registry-fetch-sender-fast (article)
726   "Fetch the Sender quickly, using the internal gnus-data-list function"
727   (if (and (numberp article)
728            (assoc article (gnus-data-list nil)))
729       (gnus-string-remove-all-properties
730        (mail-header-from (gnus-data-header
731                           (assoc article (gnus-data-list nil)))))
732     nil))
733
734 (defun gnus-registry-grep-in-list (word list)
735 "Find if a WORD matches any regular expression in the given LIST."
736   (when (and word list)
737     (catch 'found
738       (dolist (r list)
739         (when (string-match r word)
740           (throw 'found r))))))
741
742 (defun gnus-registry-do-marks (type function)
743   "For each known mark, call FUNCTION for each cell of type TYPE.
744
745 FUNCTION should take two parameters, a mark symbol and the cell value."
746   (dolist (mark-info gnus-registry-marks)
747     (let* ((mark (car-safe mark-info))
748            (data (cdr-safe mark-info))
749            (cell-data (plist-get data type)))
750       (when cell-data
751         (funcall function mark cell-data)))))
752
753 ;;; this is ugly code, but I don't know how to do it better
754 (defun gnus-registry-install-shortcuts ()
755   "Install the keyboard shortcuts and menus for the registry.
756 Uses `gnus-registry-marks' to find what shortcuts to install."
757   (let (keys-plist)
758     (gnus-registry-do-marks 
759      :char
760      (lambda (mark data)
761        (let ((function-format
762               (format "gnus-registry-%%s-article-%s-mark" mark)))
763
764 ;;; The following generates these functions:
765 ;;; (defun gnus-registry-set-article-Important-mark (&rest articles)
766 ;;;   "Apply the Important mark to process-marked ARTICLES."
767 ;;;   (interactive (gnus-summary-work-articles current-prefix-arg))
768 ;;;   (gnus-registry-set-article-mark-internal 'Important articles nil t))
769 ;;; (defun gnus-registry-remove-article-Important-mark (&rest articles)
770 ;;;   "Apply the Important mark to process-marked ARTICLES."
771 ;;;   (interactive (gnus-summary-work-articles current-prefix-arg))
772 ;;;   (gnus-registry-set-article-mark-internal 'Important articles t t))
773
774          (dolist (remove '(t nil))
775            (let* ((variant-name (if remove "remove" "set"))
776                   (function-name (format function-format variant-name))
777                   (shortcut (format "%c" data))
778                   (shortcut (if remove (upcase shortcut) shortcut)))
779              (unintern function-name)
780              (eval
781               `(defun 
782                  ;; function name
783                  ,(intern function-name) 
784                  ;; parameter definition
785                  (&rest articles)
786                  ;; documentation
787                  ,(format 
788                    "%s the %s mark over process-marked ARTICLES."
789                    (upcase-initials variant-name)
790                    mark)
791                  ;; interactive definition
792                  (interactive 
793                   (gnus-summary-work-articles current-prefix-arg))
794                  ;; actual code
795
796                  ;; if this is called and the user doesn't want the
797                  ;; registry enabled, we'll ask anyhow
798                  (when (eq gnus-registry-install nil)
799                    (setq gnus-registry-install 'ask))
800
801                  ;; now the user is asked if gnus-registry-install is 'ask
802                  (when (gnus-registry-install-p)
803                    (gnus-registry-set-article-mark-internal 
804                     ;; all this just to get the mark, I must be doing it wrong
805                     (intern ,(symbol-name mark))
806                     articles ,remove t)
807                    (dolist (article articles)
808                      (gnus-summary-update-article 
809                       article 
810                       (assoc article (gnus-data-list nil)))))))
811              (push (intern function-name) keys-plist)
812              (push shortcut keys-plist)
813              (gnus-message 
814               9 
815               "Defined mark handling function %s" 
816               function-name))))))
817     (gnus-define-keys-1
818      '(gnus-registry-mark-map "M" gnus-summary-mark-map) 
819      keys-plist)))
820
821 ;;; use like this:
822 ;;; (defalias 'gnus-user-format-function-M 
823 ;;;           'gnus-registry-user-format-function-M)
824 (defun gnus-registry-user-format-function-M (headers)
825   (let* ((id (mail-header-message-id headers))
826          (marks (when id (gnus-registry-fetch-extra-marks id))))
827     (apply 'concat (mapcar (lambda(mark)
828                              (let ((c 
829                                     (plist-get
830                                      (cdr-safe 
831                                       (assoc mark gnus-registry-marks))
832                                      :char)))
833                                (if c
834                                    (list c)
835                                  nil)))
836                            marks))))
837
838 (defun gnus-registry-read-mark ()
839   "Read a mark name from the user with completion."
840   (let ((mark (gnus-completing-read-with-default 
841                (symbol-name gnus-registry-default-mark)
842                "Label" 
843                (mapcar (lambda (x)      ; completion list
844                          (cons (symbol-name (car-safe x)) (car-safe x)))
845                        gnus-registry-marks))))
846     (when (stringp mark)
847       (intern mark))))
848
849 (defun gnus-registry-set-article-mark (&rest articles)
850   "Apply a mark to process-marked ARTICLES."
851   (interactive (gnus-summary-work-articles current-prefix-arg))
852   (gnus-registry-set-article-mark-internal (gnus-registry-read-mark) articles nil t))
853
854 (defun gnus-registry-remove-article-mark (&rest articles)
855   "Remove a mark from process-marked ARTICLES."
856   (interactive (gnus-summary-work-articles current-prefix-arg))
857   (gnus-registry-set-article-mark-internal (gnus-registry-read-mark) articles t t))
858
859 (defun gnus-registry-set-article-mark-internal (mark articles &optional remove show-message)
860   "Apply a mark to a list of ARTICLES."
861   (let ((article-id-list
862          (mapcar 'gnus-registry-fetch-message-id-fast articles)))
863     (dolist (id article-id-list)
864       (let* (
865              ;; all the marks for this article without the mark of
866              ;; interest
867              (marks
868               (delq mark (gnus-registry-fetch-extra-marks id)))
869              ;; the new marks we want to use
870              (new-marks (if remove
871                             marks
872                           (cons mark marks))))
873         (when show-message
874           (gnus-message 1 "%s mark %s with message ID %s, resulting in %S"
875                         (if remove "Removing" "Adding")
876                         mark id new-marks))
877         
878         (apply 'gnus-registry-store-extra-marks ; set the extra marks
879                id                               ; for the message ID
880                new-marks)))))
881
882 (defun gnus-registry-get-article-marks (&rest articles)
883   "Get the Gnus registry marks for ARTICLES and show them if interactive.
884 Uses process/prefix conventions.  For multiple articles,
885 only the last one's marks are returned."
886   (interactive (gnus-summary-work-articles 1))
887   (let (marks)
888     (dolist (article articles)
889       (let ((article-id
890              (gnus-registry-fetch-message-id-fast article)))
891         (setq marks (gnus-registry-fetch-extra-marks article-id))))
892     (when (interactive-p)
893         (gnus-message 1 "Marks are %S" marks))
894     marks))
895
896 ;;; if this extends to more than 'marks, it should be improved to be more generic.
897 (defun gnus-registry-fetch-extra-marks (id)
898   "Get the marks of a message, based on the message ID.
899 Returns a list of symbol marks or nil."
900   (car-safe (cdr (gnus-registry-fetch-extra id 'marks))))
901
902 (defun gnus-registry-has-extra-mark (id mark)
903   "Checks if a message has `mark', based on the message ID `id'."
904   (memq mark (gnus-registry-fetch-extra-marks id)))
905
906 (defun gnus-registry-store-extra-marks (id &rest mark-list)
907   "Set the marks of a message, based on the message ID.
908 The `mark-list' can be nil, in which case no marks are left."
909   (gnus-registry-store-extra-entry id 'marks (list mark-list)))
910
911 (defun gnus-registry-delete-extra-marks (id &rest mark-delete-list)
912   "Delete the message marks in `mark-delete-list', based on the message ID."
913   (let ((marks (gnus-registry-fetch-extra-marks id)))
914     (when marks
915       (dolist (mark mark-delete-list)
916         (setq marks (delq mark marks))))
917     (gnus-registry-store-extra-marks id (car marks))))
918
919 (defun gnus-registry-delete-all-extra-marks (id)
920   "Delete all the marks for a message ID."
921   (gnus-registry-store-extra-marks id nil))
922
923 (defun gnus-registry-fetch-extra (id &optional entry)
924   "Get the extra data of a message, based on the message ID.
925 Returns the first place where the trail finds a nonstring."
926   (let ((entry-cache (gethash entry gnus-registry-hashtb)))
927     (if (and entry
928              (hash-table-p entry-cache)
929              (gethash id entry-cache))
930         (gethash id entry-cache)
931       ;; else, if there is no caching possible...
932       (let ((trail (gethash id gnus-registry-hashtb)))
933         (when (listp trail)
934           (dolist (crumb trail)
935             (unless (stringp crumb)
936               (return (gnus-registry-fetch-extra-entry crumb entry id)))))))))
937
938 (defun gnus-registry-fetch-extra-entry (alist &optional entry id)
939   "Get the extra data of a message, or a specific entry in it.
940 Update the entry cache if needed."
941   (if (and entry id)
942       (let ((entry-cache (gethash entry gnus-registry-hashtb))
943             entree)
944         (when gnus-registry-entry-caching
945           ;; create the hash table
946           (unless (hash-table-p entry-cache)
947             (setq entry-cache (make-hash-table
948                                :size 4096
949                                :test 'equal))
950             (puthash entry entry-cache gnus-registry-hashtb))
951
952           ;; get the entree from the hash table or from the alist
953           (setq entree (gethash id entry-cache)))
954
955         (unless entree
956           (setq entree (assq entry alist))
957           (when gnus-registry-entry-caching
958             (puthash id entree entry-cache)))
959         entree)
960     alist))
961
962 (defun gnus-registry-store-extra (id extra)
963   "Store the extra data of a message, based on the message ID.
964 The message must have at least one group name."
965   (when (gnus-registry-group-count id)
966     ;; we now know the trail has at least 1 group name, so it's not empty
967     (let ((trail (gethash id gnus-registry-hashtb))
968           (old-extra (gnus-registry-fetch-extra id))
969           entry-cache)
970       (dolist (crumb trail)
971         (unless (stringp crumb)
972           (dolist (entry crumb)
973             (setq entry-cache (gethash (car entry) gnus-registry-hashtb))
974           (when entry-cache
975             (remhash id entry-cache))))
976       (puthash id (cons extra (delete old-extra trail))
977                gnus-registry-hashtb)
978       (setq gnus-registry-dirty t)))))
979
980 (defun gnus-registry-delete-extra-entry (id key)
981   "Delete a specific entry in the extras field of the registry entry for id."
982   (gnus-registry-store-extra-entry id key nil))
983
984 (defun gnus-registry-store-extra-entry (id key value)
985   "Put a specific entry in the extras field of the registry entry for id."
986   (let* ((extra (gnus-registry-fetch-extra id))
987          ;; all the entries except the one for `key'
988          (the-rest (gnus-assq-delete-all key (gnus-registry-fetch-extra id))) 
989          (alist (if value
990                     (gnus-registry-remove-alist-text-properties
991                      (cons (cons key value)
992                            the-rest))
993                   the-rest)))
994     (gnus-registry-store-extra id alist)))
995
996 (defun gnus-registry-fetch-group (id)
997   "Get the group of a message, based on the message ID.
998 Returns the first place where the trail finds a group name."
999   (when (gnus-registry-group-count id)
1000     ;; we now know the trail has at least 1 group name
1001     (let ((trail (gethash id gnus-registry-hashtb)))
1002       (dolist (crumb trail)
1003         (when (stringp crumb)
1004           (return (if gnus-registry-use-long-group-names
1005                        crumb
1006                      (gnus-group-short-name crumb))))))))
1007
1008 (defun gnus-registry-fetch-groups (id)
1009   "Get the groups of a message, based on the message ID."
1010   (let ((trail (gethash id gnus-registry-hashtb))
1011         groups)
1012     (dolist (crumb trail)
1013       (when (stringp crumb)
1014         ;; push the group name into the list
1015         (setq 
1016          groups
1017          (cons
1018           (if (or (not (stringp crumb)) gnus-registry-use-long-group-names)
1019               crumb
1020             (gnus-group-short-name crumb))
1021          groups))))
1022     ;; return the list of groups
1023     groups))
1024
1025 (defun gnus-registry-group-count (id)
1026   "Get the number of groups of a message, based on the message ID."
1027   (let ((trail (gethash id gnus-registry-hashtb)))
1028     (if (and trail (listp trail))
1029         (apply '+ (mapcar (lambda (x) (if (stringp x) 1 0)) trail))
1030       0)))
1031
1032 (defun gnus-registry-delete-group (id group)
1033   "Delete a group for a message, based on the message ID."
1034   (when (and group id)
1035       (let ((trail (gethash id gnus-registry-hashtb))
1036             (short-group (gnus-group-short-name group)))
1037         (puthash id (if trail
1038                         (delete short-group (delete group trail))
1039                       nil)
1040                  gnus-registry-hashtb))
1041       ;; now, clear the entry if there are no more groups
1042       (when gnus-registry-trim-articles-without-groups
1043         (unless (gnus-registry-group-count id)
1044           (gnus-registry-delete-id id)))
1045       ;; is this ID still in the registry?
1046       (when (gethash id gnus-registry-hashtb)
1047         (gnus-registry-store-extra-entry id 'mtime (current-time)))))
1048
1049 (defun gnus-registry-delete-id (id)
1050   "Delete a message ID from the registry."
1051   (when (stringp id)
1052     (remhash id gnus-registry-hashtb)
1053     (maphash
1054      (lambda (key value)
1055        (when (hash-table-p value)
1056          (remhash id value)))
1057      gnus-registry-hashtb)))
1058
1059 (defun gnus-registry-add-group (id group &optional subject sender)
1060   "Add a group for a message, based on the message ID."
1061   (when group
1062     (when (and id
1063                (not (string-match "totally-fudged-out-message-id" id)))
1064       (let ((full-group group)
1065             (group (if gnus-registry-use-long-group-names
1066                        group
1067                      (gnus-group-short-name group))))
1068         (gnus-registry-delete-group id group)
1069
1070         (unless gnus-registry-use-long-group-names ;; unnecessary in this case
1071           (gnus-registry-delete-group id full-group))
1072
1073         (let ((trail (gethash id gnus-registry-hashtb)))
1074           (puthash id (if trail
1075                           (cons group trail)
1076                         (list group))
1077                    gnus-registry-hashtb)
1078
1079           (when (and (gnus-registry-track-subject-p)
1080                      subject)
1081             (gnus-registry-store-extra-entry
1082              id
1083              'subject
1084              (gnus-registry-simplify-subject subject)))
1085           (when (and (gnus-registry-track-sender-p)
1086                      sender)
1087             (gnus-registry-store-extra-entry
1088              id
1089              'sender
1090              sender))
1091
1092           (gnus-registry-store-extra-entry id 'mtime (current-time)))))))
1093
1094 (defun gnus-registry-clear ()
1095   "Clear the Gnus registry."
1096   (interactive)
1097   (setq gnus-registry-alist nil)
1098   (setq gnus-registry-hashtb (gnus-alist-to-hashtable gnus-registry-alist))
1099   (setq gnus-registry-dirty t))
1100
1101 ;;;###autoload
1102 (defun gnus-registry-initialize ()
1103 "Initialize the Gnus registry."
1104   (interactive)
1105   (gnus-message 5 "Initializing the registry")
1106   (setq gnus-registry-install t)        ; in case it was 'ask or nil
1107   (gnus-registry-install-hooks)
1108   (gnus-registry-install-shortcuts)
1109   (gnus-registry-read))
1110
1111 ;;;###autoload
1112 (defun gnus-registry-install-hooks ()
1113   "Install the registry hooks."
1114   (interactive)
1115   (add-hook 'gnus-summary-article-move-hook 'gnus-registry-action)
1116   (add-hook 'gnus-summary-article-delete-hook 'gnus-registry-action)
1117   (add-hook 'gnus-summary-article-expire-hook 'gnus-registry-action)
1118   (add-hook 'nnmail-spool-hook 'gnus-registry-spool-action)
1119
1120   (add-hook 'gnus-save-newsrc-hook 'gnus-registry-save)
1121   (add-hook 'gnus-read-newsrc-el-hook 'gnus-registry-read)
1122
1123   (add-hook 'gnus-summary-prepare-hook 'gnus-registry-register-message-ids))
1124
1125 (defun gnus-registry-unload-hook ()
1126   "Uninstall the registry hooks."
1127   (interactive)
1128   (remove-hook 'gnus-summary-article-move-hook 'gnus-registry-action)
1129   (remove-hook 'gnus-summary-article-delete-hook 'gnus-registry-action)
1130   (remove-hook 'gnus-summary-article-expire-hook 'gnus-registry-action)
1131   (remove-hook 'nnmail-spool-hook 'gnus-registry-spool-action)
1132
1133   (remove-hook 'gnus-save-newsrc-hook 'gnus-registry-save)
1134   (remove-hook 'gnus-read-newsrc-el-hook 'gnus-registry-read)
1135
1136   (remove-hook 'gnus-summary-prepare-hook 'gnus-registry-register-message-ids))
1137
1138 (add-hook 'gnus-registry-unload-hook 'gnus-registry-unload-hook)
1139
1140 (defun gnus-registry-install-p ()
1141   (interactive)
1142   (when (eq gnus-registry-install 'ask)
1143     (setq gnus-registry-install
1144           (gnus-y-or-n-p
1145            (concat "Enable the Gnus registry?  "
1146                    "See the variable `gnus-registry-install' "
1147                    "to get rid of this query permanently. ")))
1148     (when gnus-registry-install
1149       ;; we just set gnus-registry-install to t, so initialize the registry!
1150       (gnus-registry-initialize)))
1151 ;;; we could call it here: (customize-variable 'gnus-registry-install)
1152   gnus-registry-install)
1153
1154 (when (or (eq gnus-registry-install t)
1155           (gnus-registry-install-p))
1156   (gnus-registry-initialize))
1157
1158 ;; TODO: a few things
1159
1160 (provide 'gnus-registry)
1161
1162 ;; arch-tag: 5cba0a32-718a-4a97-8c91-0a15af21da94
1163 ;;; gnus-registry.el ends here