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