* gnus-sum.el (gnus-summary-make-menu-bar): Let
[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-registry-grep-in-list
665             group
666             gnus-registry-unfollowed-groups)
667            (gnus-registry-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-grep-in-list (word list)
749 "Find if a WORD matches any regular expression in the given LIST."
750   (when (and word list)
751     (catch 'found
752       (dolist (r list)
753         (when (string-match r word)
754           (throw 'found r))))))
755
756 (defun gnus-registry-do-marks (type function)
757   "For each known mark, call FUNCTION for each cell of type TYPE.
758
759 FUNCTION should take two parameters, a mark symbol and the cell value."
760   (dolist (mark-info gnus-registry-marks)
761     (let* ((mark (car-safe mark-info))
762            (data (cdr-safe mark-info))
763            (cell-data (plist-get data type)))
764       (when cell-data
765         (funcall function mark cell-data)))))
766
767 ;;; this is ugly code, but I don't know how to do it better
768 (defun gnus-registry-install-shortcuts ()
769   "Install the keyboard shortcuts and menus for the registry.
770 Uses `gnus-registry-marks' to find what shortcuts to install."
771   (let (keys-plist)
772     (setq gnus-registry-misc-menus nil)
773     (gnus-registry-do-marks
774      :char
775      (lambda (mark data)
776        (let ((function-format
777               (format "gnus-registry-%%s-article-%s-mark" mark)))
778
779 ;;; The following generates these functions:
780 ;;; (defun gnus-registry-set-article-Important-mark (&rest articles)
781 ;;;   "Apply the Important mark to process-marked ARTICLES."
782 ;;;   (interactive (gnus-summary-work-articles current-prefix-arg))
783 ;;;   (gnus-registry-set-article-mark-internal 'Important articles nil t))
784 ;;; (defun gnus-registry-remove-article-Important-mark (&rest articles)
785 ;;;   "Apply the Important mark to process-marked ARTICLES."
786 ;;;   (interactive (gnus-summary-work-articles current-prefix-arg))
787 ;;;   (gnus-registry-set-article-mark-internal 'Important articles t t))
788
789          (dolist (remove '(t nil))
790            (let* ((variant-name (if remove "remove" "set"))
791                   (function-name (format function-format variant-name))
792                   (shortcut (format "%c" data))
793                   (shortcut (if remove (upcase shortcut) shortcut)))
794              (unintern function-name)
795              (eval
796               `(defun 
797                  ;; function name
798                  ,(intern function-name) 
799                  ;; parameter definition
800                  (&rest articles)
801                  ;; documentation
802                  ,(format 
803                    "%s the %s mark over process-marked ARTICLES."
804                    (upcase-initials variant-name)
805                    mark)
806                  ;; interactive definition
807                  (interactive 
808                   (gnus-summary-work-articles current-prefix-arg))
809                  ;; actual code
810
811                  ;; if this is called and the user doesn't want the
812                  ;; registry enabled, we'll ask anyhow
813                  (when (eq gnus-registry-install nil)
814                    (setq gnus-registry-install 'ask))
815
816                  ;; now the user is asked if gnus-registry-install is 'ask
817                  (when (gnus-registry-install-p)
818                    (gnus-registry-set-article-mark-internal 
819                     ;; all this just to get the mark, I must be doing it wrong
820                     (intern ,(symbol-name mark))
821                     articles ,remove t)
822                    (gnus-message
823                     9 
824                     "Applying mark %s to %d articles"
825                     ,(symbol-name mark) (length articles))
826                    (dolist (article articles)
827                      (gnus-summary-update-article 
828                       article
829                       (assoc article (gnus-data-list nil)))))))
830              (push (intern function-name) keys-plist)
831              (push shortcut keys-plist)      
832              (push (vector (format "%s %s"
833                                    (upcase-initials variant-name)
834                                    (symbol-name mark))
835                            (intern function-name) t)
836                    gnus-registry-misc-menus)
837              (gnus-message
838               9 
839               "Defined mark handling function %s" 
840               function-name))))))
841     (gnus-define-keys-1
842      '(gnus-registry-mark-map "M" gnus-summary-mark-map)
843      keys-plist)
844     (add-hook 'gnus-summary-menu-hook
845               (lambda ()
846                 (easy-menu-add-item 
847                  gnus-summary-misc-menu
848                  nil 
849                  (cons "Registry Marks" gnus-registry-misc-menus))))))
850
851 ;;; use like this:
852 ;;; (defalias 'gnus-user-format-function-M 
853 ;;;           'gnus-registry-user-format-function-M)
854 (defun gnus-registry-user-format-function-M (headers)
855   (let* ((id (mail-header-message-id headers))
856          (marks (when id (gnus-registry-fetch-extra-marks id))))
857     (apply 'concat (mapcar (lambda(mark)
858                              (let ((c 
859                                     (plist-get
860                                      (cdr-safe 
861                                       (assoc mark gnus-registry-marks))
862                                      :char)))
863                                (if c
864                                    (list c)
865                                  nil)))
866                            marks))))
867
868 (defun gnus-registry-read-mark ()
869   "Read a mark name from the user with completion."
870   (let ((mark (gnus-completing-read-with-default 
871                (symbol-name gnus-registry-default-mark)
872                "Label" 
873                (mapcar (lambda (x)      ; completion list
874                          (cons (symbol-name (car-safe x)) (car-safe x)))
875                        gnus-registry-marks))))
876     (when (stringp mark)
877       (intern mark))))
878
879 (defun gnus-registry-set-article-mark (&rest articles)
880   "Apply a mark to process-marked ARTICLES."
881   (interactive (gnus-summary-work-articles current-prefix-arg))
882   (gnus-registry-set-article-mark-internal (gnus-registry-read-mark) articles nil t))
883
884 (defun gnus-registry-remove-article-mark (&rest articles)
885   "Remove a mark from process-marked ARTICLES."
886   (interactive (gnus-summary-work-articles current-prefix-arg))
887   (gnus-registry-set-article-mark-internal (gnus-registry-read-mark) articles t t))
888
889 (defun gnus-registry-set-article-mark-internal (mark articles &optional remove show-message)
890   "Apply a mark to a list of ARTICLES."
891   (let ((article-id-list
892          (mapcar 'gnus-registry-fetch-message-id-fast articles)))
893     (dolist (id article-id-list)
894       (let* (
895              ;; all the marks for this article without the mark of
896              ;; interest
897              (marks
898               (delq mark (gnus-registry-fetch-extra-marks id)))
899              ;; the new marks we want to use
900              (new-marks (if remove
901                             marks
902                           (cons mark marks))))
903         (when show-message
904           (gnus-message 1 "%s mark %s with message ID %s, resulting in %S"
905                         (if remove "Removing" "Adding")
906                         mark id new-marks))
907         
908         (apply 'gnus-registry-store-extra-marks ; set the extra marks
909                id                               ; for the message ID
910                new-marks)))))
911
912 (defun gnus-registry-get-article-marks (&rest articles)
913   "Get the Gnus registry marks for ARTICLES and show them if interactive.
914 Uses process/prefix conventions.  For multiple articles,
915 only the last one's marks are returned."
916   (interactive (gnus-summary-work-articles 1))
917   (let (marks)
918     (dolist (article articles)
919       (let ((article-id
920              (gnus-registry-fetch-message-id-fast article)))
921         (setq marks (gnus-registry-fetch-extra-marks article-id))))
922     (when (interactive-p)
923         (gnus-message 1 "Marks are %S" marks))
924     marks))
925
926 ;;; if this extends to more than 'marks, it should be improved to be more generic.
927 (defun gnus-registry-fetch-extra-marks (id)
928   "Get the marks of a message, based on the message ID.
929 Returns a list of symbol marks or nil."
930   (car-safe (cdr (gnus-registry-fetch-extra id 'marks))))
931
932 (defun gnus-registry-has-extra-mark (id mark)
933   "Checks if a message has `mark', based on the message ID `id'."
934   (memq mark (gnus-registry-fetch-extra-marks id)))
935
936 (defun gnus-registry-store-extra-marks (id &rest mark-list)
937   "Set the marks of a message, based on the message ID.
938 The `mark-list' can be nil, in which case no marks are left."
939   (gnus-registry-store-extra-entry id 'marks (list mark-list)))
940
941 (defun gnus-registry-delete-extra-marks (id &rest mark-delete-list)
942   "Delete the message marks in `mark-delete-list', based on the message ID."
943   (let ((marks (gnus-registry-fetch-extra-marks id)))
944     (when marks
945       (dolist (mark mark-delete-list)
946         (setq marks (delq mark marks))))
947     (gnus-registry-store-extra-marks id (car marks))))
948
949 (defun gnus-registry-delete-all-extra-marks (id)
950   "Delete all the marks for a message ID."
951   (gnus-registry-store-extra-marks id nil))
952
953 (defun gnus-registry-fetch-extra (id &optional entry)
954   "Get the extra data of a message, based on the message ID.
955 Returns the first place where the trail finds a nonstring."
956   (let ((entry-cache (gethash entry gnus-registry-hashtb)))
957     (if (and entry
958              (hash-table-p entry-cache)
959              (gethash id entry-cache))
960         (gethash id entry-cache)
961       ;; else, if there is no caching possible...
962       (let ((trail (gethash id gnus-registry-hashtb)))
963         (when (listp trail)
964           (dolist (crumb trail)
965             (unless (stringp crumb)
966               (return (gnus-registry-fetch-extra-entry crumb entry id)))))))))
967
968 (defun gnus-registry-fetch-extra-entry (alist &optional entry id)
969   "Get the extra data of a message, or a specific entry in it.
970 Update the entry cache if needed."
971   (if (and entry id)
972       (let ((entry-cache (gethash entry gnus-registry-hashtb))
973             entree)
974         (when gnus-registry-entry-caching
975           ;; create the hash table
976           (unless (hash-table-p entry-cache)
977             (setq entry-cache (make-hash-table
978                                :size 4096
979                                :test 'equal))
980             (puthash entry entry-cache gnus-registry-hashtb))
981
982           ;; get the entree from the hash table or from the alist
983           (setq entree (gethash id entry-cache)))
984
985         (unless entree
986           (setq entree (assq entry alist))
987           (when gnus-registry-entry-caching
988             (puthash id entree entry-cache)))
989         entree)
990     alist))
991
992 (defun gnus-registry-store-extra (id extra)
993   "Store the extra data of a message, based on the message ID.
994 The message must have at least one group name."
995   (when (gnus-registry-group-count id)
996     ;; we now know the trail has at least 1 group name, so it's not empty
997     (let ((trail (gethash id gnus-registry-hashtb))
998           (old-extra (gnus-registry-fetch-extra id))
999           entry-cache)
1000       (dolist (crumb trail)
1001         (unless (stringp crumb)
1002           (dolist (entry crumb)
1003             (setq entry-cache (gethash (car entry) gnus-registry-hashtb))
1004           (when entry-cache
1005             (remhash id entry-cache))))
1006       (puthash id (cons extra (delete old-extra trail))
1007                gnus-registry-hashtb)
1008       (setq gnus-registry-dirty t)))))
1009
1010 (defun gnus-registry-delete-extra-entry (id key)
1011   "Delete a specific entry in the extras field of the registry entry for id."
1012   (gnus-registry-store-extra-entry id key nil))
1013
1014 (defun gnus-registry-store-extra-entry (id key value)
1015   "Put a specific entry in the extras field of the registry entry for id."
1016   (let* ((extra (gnus-registry-fetch-extra id))
1017          ;; all the entries except the one for `key'
1018          (the-rest (gnus-assq-delete-all key (gnus-registry-fetch-extra id))) 
1019          (alist (if value
1020                     (gnus-registry-remove-alist-text-properties
1021                      (cons (cons key value)
1022                            the-rest))
1023                   the-rest)))
1024     (gnus-registry-store-extra id alist)))
1025
1026 (defun gnus-registry-fetch-group (id)
1027   "Get the group of a message, based on the message ID.
1028 Returns the first place where the trail finds a group name."
1029   (when (gnus-registry-group-count id)
1030     ;; we now know the trail has at least 1 group name
1031     (let ((trail (gethash id gnus-registry-hashtb)))
1032       (dolist (crumb trail)
1033         (when (stringp crumb)
1034           (return (if gnus-registry-use-long-group-names
1035                        crumb
1036                      (gnus-group-short-name crumb))))))))
1037
1038 (defun gnus-registry-fetch-groups (id &optional max)
1039   "Get the groups (up to MAX, if given) of a message, based on the message ID."
1040   (let ((trail (gethash id gnus-registry-hashtb))
1041         groups)
1042     (dolist (crumb trail)
1043       (when (stringp crumb)
1044         ;; push the group name into the list
1045         (setq 
1046          groups
1047          (cons
1048           (if (or (not (stringp crumb)) gnus-registry-use-long-group-names)
1049               crumb
1050             (gnus-group-short-name crumb))
1051          groups))
1052         (when (and max (> (length groups) max))
1053           (return))))
1054     ;; return the list of groups
1055     groups))
1056
1057 (defun gnus-registry-group-count (id)
1058   "Get the number of groups of a message, based on the message ID."
1059   (let ((trail (gethash id gnus-registry-hashtb)))
1060     (if (and trail (listp trail))
1061         (apply '+ (mapcar (lambda (x) (if (stringp x) 1 0)) trail))
1062       0)))
1063
1064 (defun gnus-registry-delete-group (id group)
1065   "Delete a group for a message, based on the message ID."
1066   (when (and group id)
1067       (let ((trail (gethash id gnus-registry-hashtb))
1068             (short-group (gnus-group-short-name group)))
1069         (puthash id (if trail
1070                         (delete short-group (delete group trail))
1071                       nil)
1072                  gnus-registry-hashtb))
1073       ;; now, clear the entry if there are no more groups
1074       (when gnus-registry-trim-articles-without-groups
1075         (unless (gnus-registry-group-count id)
1076           (gnus-registry-delete-id id)))
1077       ;; is this ID still in the registry?
1078       (when (gethash id gnus-registry-hashtb)
1079         (gnus-registry-store-extra-entry id 'mtime (current-time)))))
1080
1081 (defun gnus-registry-delete-id (id)
1082   "Delete a message ID from the registry."
1083   (when (stringp id)
1084     (remhash id gnus-registry-hashtb)
1085     (maphash
1086      (lambda (key value)
1087        (when (hash-table-p value)
1088          (remhash id value)))
1089      gnus-registry-hashtb)))
1090
1091 (defun gnus-registry-add-group (id group &optional subject sender)
1092   "Add a group for a message, based on the message ID."
1093   (when group
1094     (when (and id
1095                (not (string-match "totally-fudged-out-message-id" id)))
1096       (let ((full-group group)
1097             (group (if gnus-registry-use-long-group-names
1098                        group
1099                      (gnus-group-short-name group))))
1100         (gnus-registry-delete-group id group)
1101
1102         (unless gnus-registry-use-long-group-names ;; unnecessary in this case
1103           (gnus-registry-delete-group id full-group))
1104
1105         (let ((trail (gethash id gnus-registry-hashtb)))
1106           (puthash id (if trail
1107                           (cons group trail)
1108                         (list group))
1109                    gnus-registry-hashtb)
1110
1111           (when (and (gnus-registry-track-subject-p)
1112                      subject)
1113             (gnus-registry-store-extra-entry
1114              id
1115              'subject
1116              (gnus-registry-simplify-subject subject)))
1117           (when (and (gnus-registry-track-sender-p)
1118                      sender)
1119             (gnus-registry-store-extra-entry
1120              id
1121              'sender
1122              sender))
1123
1124           (gnus-registry-store-extra-entry id 'mtime (current-time)))))))
1125
1126 (defun gnus-registry-clear ()
1127   "Clear the Gnus registry."
1128   (interactive)
1129   (setq gnus-registry-alist nil)
1130   (setq gnus-registry-hashtb (gnus-alist-to-hashtable gnus-registry-alist))
1131   (setq gnus-registry-dirty t))
1132
1133 ;;;###autoload
1134 (defun gnus-registry-initialize ()
1135 "Initialize the Gnus registry."
1136   (interactive)
1137   (gnus-message 5 "Initializing the registry")
1138   (setq gnus-registry-install t)        ; in case it was 'ask or nil
1139   (gnus-registry-install-hooks)
1140   (gnus-registry-install-shortcuts)
1141   (gnus-registry-read))
1142
1143 ;;;###autoload
1144 (defun gnus-registry-install-hooks ()
1145   "Install the registry hooks."
1146   (interactive)
1147   (add-hook 'gnus-summary-article-move-hook 'gnus-registry-action)
1148   (add-hook 'gnus-summary-article-delete-hook 'gnus-registry-action)
1149   (add-hook 'gnus-summary-article-expire-hook 'gnus-registry-action)
1150   (add-hook 'nnmail-spool-hook 'gnus-registry-spool-action)
1151
1152   (add-hook 'gnus-save-newsrc-hook 'gnus-registry-save)
1153   (add-hook 'gnus-read-newsrc-el-hook 'gnus-registry-read)
1154
1155   (add-hook 'gnus-summary-prepare-hook 'gnus-registry-register-message-ids))
1156
1157 (defun gnus-registry-unload-hook ()
1158   "Uninstall the registry hooks."
1159   (interactive)
1160   (remove-hook 'gnus-summary-article-move-hook 'gnus-registry-action)
1161   (remove-hook 'gnus-summary-article-delete-hook 'gnus-registry-action)
1162   (remove-hook 'gnus-summary-article-expire-hook 'gnus-registry-action)
1163   (remove-hook 'nnmail-spool-hook 'gnus-registry-spool-action)
1164
1165   (remove-hook 'gnus-save-newsrc-hook 'gnus-registry-save)
1166   (remove-hook 'gnus-read-newsrc-el-hook 'gnus-registry-read)
1167
1168   (remove-hook 'gnus-summary-prepare-hook 'gnus-registry-register-message-ids))
1169
1170 (add-hook 'gnus-registry-unload-hook 'gnus-registry-unload-hook)
1171
1172 (defun gnus-registry-install-p ()
1173   (interactive)
1174   (when (eq gnus-registry-install 'ask)
1175     (setq gnus-registry-install
1176           (gnus-y-or-n-p
1177            (concat "Enable the Gnus registry?  "
1178                    "See the variable `gnus-registry-install' "
1179                    "to get rid of this query permanently. ")))
1180     (when gnus-registry-install
1181       ;; we just set gnus-registry-install to t, so initialize the registry!
1182       (gnus-registry-initialize)))
1183 ;;; we could call it here: (customize-variable 'gnus-registry-install)
1184   gnus-registry-install)
1185
1186 (when (or (eq gnus-registry-install t)
1187           (gnus-registry-install-p))
1188   (gnus-registry-initialize))
1189
1190 ;; TODO: a few things
1191
1192 (provide 'gnus-registry)
1193
1194 ;; arch-tag: 5cba0a32-718a-4a97-8c91-0a15af21da94
1195 ;;; gnus-registry.el ends here