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