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