5145f01d635a322a3162653187b0edfa39109838
[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 ;; Gnus backends, not just nnmail.  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
40 ;; (gnus-registry-initialize)
41
42 ;; Then use this in your fancy-split:
43
44 ;; (: gnus-registry-split-fancy-with-parent)
45
46 ;; You should also consider using the nnregistry backend to look up
47 ;; articles.  See the Gnus manual for more information.
48
49 ;; TODO:
50
51 ;; - get the correct group on spool actions
52
53 ;; - articles that are spooled to a different backend should be moved
54 ;;   after splitting
55
56 ;;; Code:
57
58 (eval-when-compile (require 'cl))
59
60 (eval-when-compile
61   (when (null (ignore-errors (require 'ert)))
62     (defmacro* ert-deftest (name () &body docstring-keys-and-body))))
63
64 (ignore-errors
65   (require 'ert))
66 (require 'gnus)
67 (require 'gnus-int)
68 (require 'gnus-sum)
69 (require 'gnus-art)
70 (require 'gnus-util)
71 (require 'nnmail)
72 (require 'easymenu)
73 (require 'registry)
74
75 (defvar gnus-adaptive-word-syntax-table)
76
77 (defvar gnus-registry-dirty t
78  "Boolean set to t when the registry is modified")
79
80 (defgroup gnus-registry nil
81   "The Gnus registry."
82   :version "22.1"
83   :group 'gnus)
84
85 (defvar gnus-registry-marks
86   '((Important
87      :char ?i
88      :image "summary_important")
89     (Work
90      :char ?w
91      :image "summary_work")
92     (Personal
93      :char ?p
94      :image "summary_personal")
95     (To-Do
96      :char ?t
97      :image "summary_todo")
98     (Later
99      :char ?l
100      :image "summary_later"))
101
102   "List of registry marks and their options.
103
104 `gnus-registry-mark-article' will offer symbols from this list
105 for completion.
106
107 Each entry must have a character to be useful for summary mode
108 line display and for keyboard shortcuts.
109
110 Each entry must have an image string to be useful for visual
111 display.")
112
113 (defcustom gnus-registry-default-mark 'To-Do
114   "The default mark.  Should be a valid key for `gnus-registry-marks'."
115   :group 'gnus-registry
116   :type 'symbol)
117
118 (defcustom gnus-registry-unfollowed-addresses
119   (list (regexp-quote user-mail-address))
120   "List of addresses that gnus-registry-split-fancy-with-parent won't trace.
121 The addresses are matched, they don't have to be fully qualified."
122   :group 'gnus-registry
123   :type '(repeat regexp))
124
125 (defcustom gnus-registry-unfollowed-groups
126   '("delayed$" "drafts$" "queue$" "INBOX$" "^nnmairix:" "archive")
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 Gnus registry 'never split a
130 message into a group that matches one of these, regardless of
131 references.'
132
133 nnmairix groups are specifically excluded because they are ephemeral."
134   :group 'gnus-registry
135   :type '(repeat regexp))
136
137 (defcustom gnus-registry-install 'ask
138   "Whether the registry should be installed."
139   :group 'gnus-registry
140   :type '(choice (const :tag "Never Install" nil)
141                  (const :tag "Always Install" t)
142                  (const :tag "Ask Me" ask)))
143
144 (defvar gnus-summary-misc-menu) ;; Avoid byte compiler warning.
145
146 (defvar gnus-registry-misc-menus nil)   ; ugly way to keep the menus
147
148 (make-obsolete-variable 'gnus-registry-clean-empty nil "23.4")
149 (make-obsolete-variable 'gnus-registry-use-long-group-names nil "23.4")
150 (make-obsolete-variable 'gnus-registry-max-track-groups nil "23.4")
151 (make-obsolete-variable 'gnus-registry-entry-caching nil "23.4")
152 (make-obsolete-variable 'gnus-registry-trim-articles-without-groups nil "23.4")
153
154 (defcustom gnus-registry-track-extra '(subject sender)
155   "Whether the registry should track extra data about a message.
156 The Subject and Sender (From:) headers are tracked this way by
157 default."
158   :group 'gnus-registry
159   :type
160   '(set :tag "Tracking choices"
161     (const :tag "Track by subject (Subject: header)" subject)
162     (const :tag "Track by sender (From: header)"  sender)))
163
164 (defcustom gnus-registry-split-strategy nil
165   "The splitting strategy applied to the keys in `gnus-registry-track-extra'.
166
167 Given a set of unique found groups G and counts for each element
168 of G, and a key K (typically 'sender or 'subject):
169
170 When nil, if G has only one element, use it.  Otherwise give up.
171 This is the fastest but also least useful strategy.
172
173 When 'majority, use the majority by count.  So if there is a
174 group with the most articles counted by K, use that.  Ties are
175 resolved in no particular order, simply the first one found wins.
176 This is the slowest strategy but also the most accurate one.
177
178 When 'first, the first element of G wins.  This is fast and
179 should be OK if your senders and subjects don't \"bleed\" across
180 groups."
181   :group 'gnus-registry
182   :type
183   '(choice :tag "Splitting strategy"
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-minimum-subject-length 5
189   "The minimum length of a subject before it's considered trackable."
190   :group 'gnus-registry
191   :type 'integer)
192
193 (defcustom gnus-registry-extra-entries-precious '(mark)
194   "What extra keys are precious, meaning entries with them won't get pruned.
195 By default, 'mark is included, so articles with marks are
196 considered precious.
197
198 Before you save the Gnus registry, it's pruned.  Any entries with
199 keys in this list will not be pruned.  All other entries go to
200 the Bit Bucket."
201   :group 'gnus-registry
202   :type '(repeat symbol))
203
204 (defcustom gnus-registry-cache-file
205   (nnheader-concat
206    (or gnus-dribble-directory gnus-home-directory "~/")
207    ".gnus.registry.eioio")
208   "File where the Gnus registry will be stored."
209   :group 'gnus-registry
210   :type 'file)
211
212 (defcustom gnus-registry-max-entries nil
213   "Maximum number of entries in the registry, nil for unlimited."
214   :group 'gnus-registry
215   :type '(radio (const :format "Unlimited " nil)
216                 (integer :format "Maximum number: %v")))
217
218 (defcustom gnus-registry-max-pruned-entries nil
219   "Maximum number of pruned entries in the registry, nil for unlimited."
220   :group 'gnus-registry
221   :type '(radio (const :format "Unlimited " nil)
222                 (integer :format "Maximum number: %v")))
223
224 (defun gnus-registry-fixup-registry (db)
225   (when db
226     (oset db :precious
227           (append gnus-registry-extra-entries-precious
228                   '()))
229     (oset db :max-hard
230           (or gnus-registry-max-entries
231               most-positive-fixnum))
232     (oset db :max-soft
233           (or gnus-registry-max-pruned-entries
234               most-positive-fixnum))
235     (oset db :tracked
236           (append gnus-registry-track-extra
237                   '(mark group keyword))))
238   db)
239
240 (defun gnus-registry-make-db (&optional file)
241   (interactive "fGnus registry persistence file: \n")
242   (gnus-registry-fixup-registry
243    (registry-db
244     "Gnus Registry"
245     :file (or file gnus-registry-cache-file)
246     ;; these parameters are set in `gnus-registry-fixup-registry'
247     :max-hard most-positive-fixnum
248     :max-soft most-positive-fixnum
249     :precious nil
250     :tracked nil)))
251
252 (defvar gnus-registry-db (gnus-registry-make-db)
253   "*The article registry by Message ID.  See `registry-db'")
254
255 ;; top-level registry data management
256 (defun gnus-registry-remake-db (&optional forsure)
257   "Remake the registry database after customization.
258 This is not required after changing `gnus-registry-cache-file'."
259   (interactive (list (y-or-n-p "Remake and CLEAR the Gnus registry? ")))
260   (when forsure
261     (gnus-message 1 "Remaking the Gnus registry")
262     (setq gnus-registry-db (gnus-registry-make-db))))
263
264 (defun gnus-registry-read ()
265   "Read the registry cache file."
266   (interactive)
267   (let ((file gnus-registry-cache-file))
268     (condition-case nil
269         (progn
270           (gnus-message 5 "Reading Gnus registry from %s..." file)
271           (setq gnus-registry-db (gnus-registry-fixup-registry
272                                   (eieio-persistent-read file)))
273           (gnus-message 5 "Reading Gnus registry from %s...done" file))
274       (error
275        (gnus-message
276         1
277         "The Gnus registry could not be loaded from %s, creating a new one"
278         file)
279        (gnus-registry-remake-db t)))))
280
281 (defun gnus-registry-save (&optional file db)
282   "Save the registry cache file."
283   (interactive)
284   (let ((file (or file gnus-registry-cache-file))
285         (db (or db gnus-registry-db)))
286     (gnus-message 5 "Saving Gnus registry (%d entries) to %s..."
287                   (registry-size db) file)
288     (registry-prune db)
289     ;; TODO: call (gnus-string-remove-all-properties v) on all elements?
290     (eieio-persistent-save db file)
291     (gnus-message 5 "Saving Gnus registry (size %d) to %s...done"
292                   (registry-size db) file)))
293
294 ;; article move/copy/spool/delete actions
295 (defun gnus-registry-action (action data-header from &optional to method)
296   (let* ((id (mail-header-id data-header))
297          (subject (gnus-string-remove-all-properties
298                    (gnus-registry-simplify-subject
299                     (mail-header-subject data-header))))
300          (sender (gnus-string-remove-all-properties
301                   (mail-header-from data-header)))
302          (from (gnus-group-guess-full-name-from-command-method from))
303          (to (if to (gnus-group-guess-full-name-from-command-method to) nil))
304          (to-name (if to to "the Bit Bucket")))
305     (gnus-message 7 "Gnus registry: article %s %s from %s to %s"
306                   id (if method "respooling" "going") from to)
307
308     (gnus-registry-handle-action
309      id
310      ;; unless copying, remove the old "from" group
311      (if (not (equal 'copy action)) from nil)
312      to subject sender)))
313
314 (defun gnus-registry-spool-action (id group &optional subject sender)
315   (let ((to (gnus-group-guess-full-name-from-command-method group)))
316     (when (and (stringp id) (string-match "\r$" id))
317       (setq id (substring id 0 -1)))
318     (gnus-message 7 "Gnus registry: article %s spooled to %s"
319                   id
320                   to)
321     (gnus-registry-handle-action id nil to subject sender)))
322
323 (defun gnus-registry-handle-action (id from to subject sender)
324   (let ((db gnus-registry-db)
325         ;; safe if not found
326         (entry (gnus-registry-get-or-make-entry id)))
327
328     ;; this could be done by calling `gnus-registry-set-id-key'
329     ;; several times but it's better to bunch the transactions
330     ;; together
331
332     (registry-delete db (list id) nil)
333     (when from
334       (setq entry (cons (delete from (assoc 'group entry))
335                         (assq-delete-all 'group entry))))
336
337     (dolist (kv `((group ,to) (sender ,sender) (subject ,subject)))
338       (when (second kv)
339         (let ((new (or (assq (first kv) entry)
340                        (list (first kv)))))
341           (add-to-list 'new (second kv) t)
342           (setq entry (cons new
343                             (assq-delete-all (first kv) entry))))))
344     (gnus-message 10 "Gnus registry: new entry for %s is %S"
345                   id
346                   entry)
347     (registry-insert db id entry)))
348
349 ;; Function for nn{mail|imap}-split-fancy: look up all references in
350 ;; the cache and if a match is found, return that group.
351 (defun gnus-registry-split-fancy-with-parent ()
352   "Split this message into the same group as its parent.  The parent
353 is obtained from the registry.  This function can be used as an entry
354 in `nnmail-split-fancy' or `nnimap-split-fancy', for example like
355 this: (: gnus-registry-split-fancy-with-parent)
356
357 This function tracks ALL backends, unlike
358 `nnmail-split-fancy-with-parent' which tracks only nnmail
359 messages.
360
361 For a message to be split, it looks for the parent message in the
362 References or In-Reply-To header and then looks in the registry
363 to see which group that message was put in.  This group is
364 returned, unless `gnus-registry-follow-group-p' return nil for
365 that group.
366
367 See the Info node `(gnus)Fancy Mail Splitting' for more details."
368   (let* ((refstr (or (message-fetch-field "references") "")) ; guaranteed
369          (reply-to (message-fetch-field "in-reply-to"))      ; may be nil
370          ;; now, if reply-to is valid, append it to the References
371          (refstr (if reply-to
372                      (concat refstr " " reply-to)
373                    refstr))
374          (references (and refstr (gnus-extract-references refstr)))
375          ;; these may not be used, but the code is cleaner having them up here
376          (sender (gnus-string-remove-all-properties
377                   (message-fetch-field "from")))
378          (subject (gnus-string-remove-all-properties
379                    (gnus-registry-simplify-subject
380                     (message-fetch-field "subject"))))
381
382          (nnmail-split-fancy-with-parent-ignore-groups
383           (if (listp nnmail-split-fancy-with-parent-ignore-groups)
384               nnmail-split-fancy-with-parent-ignore-groups
385             (list nnmail-split-fancy-with-parent-ignore-groups))))
386     (gnus-registry--split-fancy-with-parent-internal
387      :references references
388      :refstr refstr
389      :sender sender
390      :subject subject
391      :log-agent "Gnus registry fancy splitting with parent")))
392
393 (defun* gnus-registry--split-fancy-with-parent-internal
394     (&rest spec
395            &key references refstr sender subject log-agent
396            &allow-other-keys)
397   (gnus-message
398    10
399    "gnus-registry--split-fancy-with-parent-internal %S" spec)
400   (let ((db gnus-registry-db)
401         found)
402     ;; this is a big chain of statements.  it uses
403     ;; gnus-registry-post-process-groups to filter the results after
404     ;; every step.
405     ;; the references string must be valid and parse to valid references
406     (when references
407       (gnus-message
408        9
409        "%s is tracing references %s"
410        log-agent refstr)
411       (dolist (reference (nreverse references))
412         (gnus-message 9 "%s is looking up %s" log-agent reference)
413         (loop for group in (gnus-registry-get-id-key reference 'group)
414               when (gnus-registry-follow-group-p group)
415               do (gnus-message 7 "%s traced %s to %s" log-agent reference group)
416               do (push group found)))
417       ;; filter the found groups and return them
418       ;; the found groups are the full groups
419       (setq found (gnus-registry-post-process-groups
420                    "references" refstr found)))
421
422      ;; else: there were no matches, try the extra tracking by sender
423      (when (and (null found)
424                 (memq 'sender gnus-registry-track-extra)
425                 sender
426                 (gnus-grep-in-list
427                  sender
428                  gnus-registry-unfollowed-addresses))
429        (let ((groups (apply
430                       'append
431                       (mapcar
432                        (lambda (reference)
433                          (gnus-registry-get-id-key reference 'group))
434                        (registry-lookup-secondary-value db 'sender sender)))))
435          (setq found
436                (loop for group in groups
437                      when (gnus-registry-follow-group-p group)
438                      do (gnus-message
439                          ;; warn more if gnus-registry-track-extra
440                          (if gnus-registry-track-extra 7 9)
441                          "%s (extra tracking) traced sender '%s' to %s"
442                          log-agent sender group)
443                      collect group)))
444
445        ;; filter the found groups and return them
446        ;; the found groups are NOT the full groups
447        (setq found (gnus-registry-post-process-groups
448                     "sender" sender found)))
449
450      ;; else: there were no matches, now try the extra tracking by subject
451      (when (and (null found)
452                 (memq 'subject gnus-registry-track-extra)
453                 subject
454                 (< gnus-registry-minimum-subject-length (length subject)))
455        (let ((groups (apply
456                       'append
457                       (mapcar
458                        (lambda (reference)
459                          (gnus-registry-get-id-key reference 'group))
460                        (registry-lookup-secondary-value db 'subject subject)))))
461          (setq found
462                (loop for group in groups
463                      when (gnus-registry-follow-group-p group)
464                      do (gnus-message
465                          ;; warn more if gnus-registry-track-extra
466                          (if gnus-registry-track-extra 7 9)
467                          "%s (extra tracking) traced subject '%s' to %s"
468                          log-agent subject group)
469                      collect group))
470          ;; filter the found groups and return them
471          ;; the found groups are NOT the full groups
472          (setq found (gnus-registry-post-process-groups
473                       "subject" subject found))))
474      ;; after the (cond) we extract the actual value safely
475      (car-safe found)))
476
477 (defun gnus-registry-post-process-groups (mode key groups)
478   "Inspects GROUPS found by MODE for KEY to determine which ones to follow.
479
480 MODE can be 'subject' or 'sender' for example.  The KEY is the
481 value by which MODE was searched.
482
483 Transforms each group name to the equivalent short name.
484
485 Checks if the current Gnus method (from `gnus-command-method' or
486 from `gnus-newsgroup-name') is the same as the group's method.
487 Foreign methods are not supported so they are rejected.
488
489 Reduces the list to a single group, or complains if that's not
490 possible.  Uses `gnus-registry-split-strategy'."
491   (let ((log-agent "gnus-registry-post-process-group")
492         (desc (format "%d groups" (length groups)))
493         out chosen)
494     ;; the strategy can be nil, in which case chosen is nil
495     (setq chosen
496           (case gnus-registry-split-strategy
497             ;; default, take only one-element lists into chosen
498             ((nil)
499              (and (= (length groups) 1)
500                   (car-safe groups)))
501
502             ((first)
503              (car-safe groups))
504
505             ((majority)
506              (let ((freq (make-hash-table
507                           :size 256
508                           :test 'equal)))
509                (mapc (lambda (x) (let ((x (gnus-group-short-name x)))
510                               (puthash x (1+ (gethash x freq 0)) freq)))
511                      groups)
512                (setq desc (format "%d groups, %d unique"
513                                   (length groups)
514                                   (hash-table-count freq)))
515                (car-safe
516                 (sort groups
517                       (lambda (a b)
518                         (> (gethash (gnus-group-short-name a) freq 0)
519                            (gethash (gnus-group-short-name b) freq 0)))))))))
520
521     (if chosen
522         (gnus-message
523          9
524          "%s: strategy %s on %s produced %s"
525          log-agent gnus-registry-split-strategy desc chosen)
526       (gnus-message
527        9
528        "%s: strategy %s on %s did not produce an answer"
529        log-agent
530        (or gnus-registry-split-strategy "default")
531        desc))
532
533     (setq groups (and chosen (list chosen)))
534
535     (dolist (group groups)
536       (let ((m1 (gnus-find-method-for-group group))
537             (m2 (or gnus-command-method
538                     (gnus-find-method-for-group gnus-newsgroup-name)))
539             (short-name (gnus-group-short-name group)))
540         (if (gnus-methods-equal-p m1 m2)
541             (progn
542               ;; this is REALLY just for debugging
543               (when (not (equal group short-name))
544                 (gnus-message
545                  10
546                  "%s: stripped group %s to %s"
547                  log-agent group short-name))
548               (add-to-list 'out short-name))
549           ;; else...
550           (gnus-message
551            7
552            "%s: ignored foreign group %s"
553            log-agent group))))
554
555     (setq out (delq nil out))
556
557     (cond
558      ((= (length out) 1) out)
559      ((null out)
560       (gnus-message
561        5
562        "%s: no matches for %s %s."
563        log-agent out mode key)
564       nil)
565      (t (gnus-message
566          5
567          "%s: too many extra matches (%s) for %s %s.  Returning none."
568          log-agent out mode key)
569         nil))))
570
571 (defun gnus-registry-follow-group-p (group)
572   "Determines if a group name should be followed.
573 Consults `gnus-registry-unfollowed-groups' and
574 `nnmail-split-fancy-with-parent-ignore-groups'."
575   (and group
576        (not (or (gnus-grep-in-list
577                  group
578                  gnus-registry-unfollowed-groups)
579                 (gnus-grep-in-list
580                  group
581                  nnmail-split-fancy-with-parent-ignore-groups)))))
582
583 (defun gnus-registry-wash-for-keywords (&optional force)
584   "Get the keywords of the current article.
585 Overrides existing keywords with FORCE set non-nil."
586   (interactive)
587   (let ((id (gnus-registry-fetch-message-id-fast gnus-current-article))
588         word words)
589     (if (or (not (gnus-registry-get-id-key id 'keyword))
590             force)
591         (with-current-buffer gnus-article-buffer
592           (article-goto-body)
593           (save-window-excursion
594             (save-restriction
595               (narrow-to-region (point) (point-max))
596               (with-syntax-table gnus-adaptive-word-syntax-table
597                 (while (re-search-forward "\\b\\w+\\b" nil t)
598                   (setq word (gnus-string-remove-all-properties
599                               (downcase (buffer-substring
600                                          (match-beginning 0) (match-end 0)))))
601                   (if (> (length word) 2)
602                       (push word words))))))
603           (gnus-registry-set-id-key id 'keyword words)))))
604
605 (defun gnus-registry-keywords ()
606   (let ((table (registry-lookup-secondary gnus-registry-db 'keyword)))
607     (when table (maphash (lambda (k v) k) table))))
608
609 (defun gnus-registry-find-keywords (keyword)
610   (interactive (list
611                 (completing-read "Keyword: " (gnus-registry-keywords) nil t)))
612   (registry-lookup-secondary-value gnus-registry-db 'keyword keyword))
613
614 (defun gnus-registry-register-message-ids ()
615   "Register the Message-ID of every article in the group"
616   (unless (gnus-parameter-registry-ignore gnus-newsgroup-name)
617     (dolist (article gnus-newsgroup-articles)
618       (let* ((id (gnus-registry-fetch-message-id-fast article))
619              (groups (gnus-registry-get-id-key id 'group)))
620         (unless (member gnus-newsgroup-name groups)
621           (gnus-message 9 "Registry: Registering article %d with group %s"
622                         article gnus-newsgroup-name)
623           (gnus-registry-handle-action id nil gnus-newsgroup-name
624            (gnus-registry-fetch-simplified-message-subject-fast article)
625            (gnus-registry-fetch-sender-fast article)))))))
626
627 ;; message field fetchers
628 (defun gnus-registry-fetch-message-id-fast (article)
629   "Fetch the Message-ID quickly, using the internal gnus-data-list function"
630   (if (and (numberp article)
631            (assoc article (gnus-data-list nil)))
632       (mail-header-id (gnus-data-header (assoc article (gnus-data-list nil))))
633     nil))
634
635 (defun gnus-registry-simplify-subject (subject)
636   (if (stringp subject)
637       (gnus-simplify-subject subject)
638     nil))
639
640 (defun gnus-registry-fetch-simplified-message-subject-fast (article)
641   "Fetch the Subject quickly, using the internal gnus-data-list function"
642   (if (and (numberp article)
643            (assoc article (gnus-data-list nil)))
644       (gnus-string-remove-all-properties
645        (gnus-registry-simplify-subject
646         (mail-header-subject (gnus-data-header
647                               (assoc article (gnus-data-list nil))))))
648     nil))
649
650 (defun gnus-registry-fetch-sender-fast (article)
651   "Fetch the Sender quickly, using the internal gnus-data-list function"
652   (if (and (numberp article)
653            (assoc article (gnus-data-list nil)))
654       (gnus-string-remove-all-properties
655        (mail-header-from (gnus-data-header
656                           (assoc article (gnus-data-list nil)))))
657     nil))
658
659 ;; registry marks glue
660 (defun gnus-registry-do-marks (type function)
661   "For each known mark, call FUNCTION for each cell of type TYPE.
662
663 FUNCTION should take two parameters, a mark symbol and the cell value."
664   (dolist (mark-info gnus-registry-marks)
665     (let* ((mark (car-safe mark-info))
666            (data (cdr-safe mark-info))
667            (cell-data (plist-get data type)))
668       (when cell-data
669         (funcall function mark cell-data)))))
670
671 ;;; this is ugly code, but I don't know how to do it better
672 (defun gnus-registry-install-shortcuts ()
673   "Install the keyboard shortcuts and menus for the registry.
674 Uses `gnus-registry-marks' to find what shortcuts to install."
675   (let (keys-plist)
676     (setq gnus-registry-misc-menus nil)
677     (gnus-registry-do-marks
678      :char
679      (lambda (mark data)
680        (let ((function-format
681               (format "gnus-registry-%%s-article-%s-mark" mark)))
682
683 ;;; The following generates these functions:
684 ;;; (defun gnus-registry-set-article-Important-mark (&rest articles)
685 ;;;   "Apply the Important mark to process-marked ARTICLES."
686 ;;;   (interactive (gnus-summary-work-articles current-prefix-arg))
687 ;;;   (gnus-registry-set-article-mark-internal 'Important articles nil t))
688 ;;; (defun gnus-registry-remove-article-Important-mark (&rest articles)
689 ;;;   "Apply the Important mark to process-marked ARTICLES."
690 ;;;   (interactive (gnus-summary-work-articles current-prefix-arg))
691 ;;;   (gnus-registry-set-article-mark-internal 'Important articles t t))
692
693          (dolist (remove '(t nil))
694            (let* ((variant-name (if remove "remove" "set"))
695                   (function-name (format function-format variant-name))
696                   (shortcut (format "%c" data))
697                   (shortcut (if remove (upcase shortcut) shortcut)))
698              (unintern function-name obarray)
699              (eval
700               `(defun
701                  ;; function name
702                  ,(intern function-name)
703                  ;; parameter definition
704                  (&rest articles)
705                  ;; documentation
706                  ,(format
707                    "%s the %s mark over process-marked ARTICLES."
708                    (upcase-initials variant-name)
709                    mark)
710                  ;; interactive definition
711                  (interactive
712                   (gnus-summary-work-articles current-prefix-arg))
713                  ;; actual code
714
715                  ;; if this is called and the user doesn't want the
716                  ;; registry enabled, we'll ask anyhow
717                  (when (eq gnus-registry-install nil)
718                    (setq gnus-registry-install 'ask))
719
720                  ;; now the user is asked if gnus-registry-install is 'ask
721                  (when (gnus-registry-install-p)
722                    (gnus-registry-set-article-mark-internal
723                     ;; all this just to get the mark, I must be doing it wrong
724                     (intern ,(symbol-name mark))
725                     articles ,remove t)
726                    (gnus-message
727                     9
728                     "Applying mark %s to %d articles"
729                     ,(symbol-name mark) (length articles))
730                    (dolist (article articles)
731                      (gnus-summary-update-article
732                       article
733                       (assoc article (gnus-data-list nil)))))))
734              (push (intern function-name) keys-plist)
735              (push shortcut keys-plist)
736              (push (vector (format "%s %s"
737                                    (upcase-initials variant-name)
738                                    (symbol-name mark))
739                            (intern function-name) t)
740                    gnus-registry-misc-menus)
741              (gnus-message
742               9
743               "Defined mark handling function %s"
744               function-name))))))
745     (gnus-define-keys-1
746      '(gnus-registry-mark-map "M" gnus-summary-mark-map)
747      keys-plist)
748     (add-hook 'gnus-summary-menu-hook
749               (lambda ()
750                 (easy-menu-add-item
751                  gnus-summary-misc-menu
752                  nil
753                  (cons "Registry Marks" gnus-registry-misc-menus))))))
754
755 ;;; use like this:
756 ;;; (defalias 'gnus-user-format-function-M
757 ;;;           'gnus-registry-user-format-function-M)
758 (defun gnus-registry-user-format-function-M (headers)
759   (let* ((id (mail-header-message-id headers))
760          (marks (when id (gnus-registry-get-id-key id 'mark))))
761     (apply 'concat (mapcar (lambda (mark)
762                              (let ((c
763                                     (plist-get
764                                      (cdr-safe
765                                       (assoc mark gnus-registry-marks))
766                                      :char)))
767                                (if c
768                                    (list c)
769                                  nil)))
770                            marks))))
771
772 (defun gnus-registry-read-mark ()
773   "Read a mark name from the user with completion."
774   (let ((mark (gnus-completing-read
775                "Label"
776                (mapcar 'symbol-name (mapcar 'car gnus-registry-marks))
777                nil nil nil
778                (symbol-name gnus-registry-default-mark))))
779     (when (stringp mark)
780       (intern mark))))
781
782 (defun gnus-registry-set-article-mark (&rest articles)
783   "Apply a mark to process-marked ARTICLES."
784   (interactive (gnus-summary-work-articles current-prefix-arg))
785   (gnus-registry-set-article-mark-internal (gnus-registry-read-mark)
786                                            articles nil t))
787
788 (defun gnus-registry-remove-article-mark (&rest articles)
789   "Remove a mark from process-marked ARTICLES."
790   (interactive (gnus-summary-work-articles current-prefix-arg))
791   (gnus-registry-set-article-mark-internal (gnus-registry-read-mark)
792                                            articles t t))
793
794 (defun gnus-registry-set-article-mark-internal (mark
795                                                 articles
796                                                 &optional remove
797                                                 show-message)
798   "Apply or remove MARK across a list of ARTICLES."
799   (let ((article-id-list
800          (mapcar 'gnus-registry-fetch-message-id-fast articles)))
801     (dolist (id article-id-list)
802       (let* ((marks (delq mark (gnus-registry-get-id-key id 'mark)))
803              (marks (if remove marks (cons mark marks))))
804         (when show-message
805           (gnus-message 1 "%s mark %s with message ID %s, resulting in %S"
806                         (if remove "Removing" "Adding")
807                         mark id marks))
808         (gnus-registry-set-id-key id 'mark marks)))))
809
810 (defun gnus-registry-get-article-marks (&rest articles)
811   "Get the Gnus registry marks for ARTICLES and show them if interactive.
812 Uses process/prefix conventions.  For multiple articles,
813 only the last one's marks are returned."
814   (interactive (gnus-summary-work-articles 1))
815   (let* ((article (last articles))
816          (id (gnus-registry-fetch-message-id-fast article))
817          (marks (when id (gnus-registry-get-id-key id 'mark))))
818     (when (interactive-p)
819       (gnus-message 1 "Marks are %S" marks))
820     marks))
821
822 (defun gnus-registry-group-count (id)
823   "Get the number of groups of a message, based on the message ID."
824   (length (gnus-registry-get-id-key id 'group)))
825
826 (defun gnus-registry-get-or-make-entry (id)
827   (let* ((db gnus-registry-db)
828          ;; safe if not found
829          (entries (registry-lookup db (list id))))
830
831     (when (null entries)
832       (registry-insert db id (list (list 'creation-time (current-time))
833                                    '(group) '(sender) '(subject)))
834       (setq entries (registry-lookup db (list id))))
835
836     (nth 1 (assoc id entries))))
837
838 (defun gnus-registry-delete-entries (idlist)
839   (registry-delete gnus-registry-db idlist nil))
840
841 (defun gnus-registry-get-id-key (id key)
842   (cdr-safe (assq key (gnus-registry-get-or-make-entry id))))
843
844 (defun gnus-registry-set-id-key (id key vals)
845   (let* ((db gnus-registry-db)
846          (entry (gnus-registry-get-or-make-entry id)))
847     (registry-delete db (list id) nil)
848     (setq entry (cons (cons key vals) (assq-delete-all key entry)))
849     (registry-insert db id entry)
850     entry))
851
852 (defun gnus-registry-import-eld (file)
853   (interactive "fOld registry file to import? ")
854   ;; example content:
855   ;;   (setq gnus-registry-alist '(
856   ;; ("<messageID>" ((marks nil)
857   ;;                 (mtime 19365 1776 440496)
858   ;;                 (sender . "root (Cron Daemon)")
859   ;;                 (subject . "Cron"))
860   ;;  "cron" "nnml+private:cron")
861   (load file t)
862   (when (boundp 'gnus-registry-alist)
863     (let* ((old (symbol-value 'gnus-registry-alist))
864            (count 0)
865            (expected (length old))
866            entry)
867       (while (car-safe old)
868         (incf count)
869         ;; don't use progress reporters for backwards compatibility
870         (when (and (< 0 expected)
871                    (= 0 (mod count 100)))
872           (message "importing: %d of %d (%.2f%%)"
873                    count expected (/ (* 100 count) expected)))
874         (setq entry (car-safe old)
875               old (cdr-safe old))
876         (let* ((id (car-safe entry))
877                (new-entry (gnus-registry-get-or-make-entry id))
878                (rest (cdr-safe entry))
879                (groups (loop for p in rest
880                              when (stringp p)
881                              collect p))
882                extra-cell key val)
883           ;; remove all the strings from the entry
884           (delete* nil rest :test (lambda (a b) (stringp b)))
885           (gnus-registry-set-id-key id 'group groups)
886           ;; just use the first extra element
887           (setq rest (car-safe rest))
888           (while (car-safe rest)
889             (setq extra-cell (car-safe rest)
890                   key (car-safe extra-cell)
891                   val (cdr-safe extra-cell)
892                   rest (cdr-safe rest))
893             (when (and val (atom val))
894               (setq val (list val)))
895             (gnus-registry-set-id-key id key val))))
896       (message "Import done, collected %d entries" count))))
897
898 (ert-deftest gnus-registry-usage-test ()
899   (let* ((n 100)
900          (tempfile (make-temp-file "gnus-registry-persist"))
901          (db (gnus-registry-make-db tempfile))
902          (gnus-registry-db db)
903          back size)
904     (message "Adding %d keys to the test Gnus registry" n)
905     (dotimes (i n)
906       (let ((id (number-to-string i)))
907         (gnus-registry-handle-action id
908                                      (if (>= 50 i) "fromgroup" nil)
909                                      "togroup"
910                                      (when (>= 70 i)
911                                        (format "subject %d" (mod i 10)))
912                                      (when (>= 80 i)
913                                        (format "sender %d" (mod i 10))))))
914     (message "Testing Gnus registry size is %d" n)
915     (should (= n (registry-size db)))
916     (message "Looking up individual keys (registry-lookup)")
917     (should (equal (loop for e
918                          in (mapcar 'cadr
919                                     (registry-lookup db '("20" "83" "72")))
920                          collect (assq 'subject e)
921                          collect (assq 'sender e)
922                          collect (assq 'group e))
923                    '((subject "subject 0") (sender "sender 0") (group "togroup")
924                      (subject) (sender) (group "togroup")
925                      (subject) (sender "sender 2") (group "togroup"))))
926
927     (message "Looking up individual keys (gnus-registry-id-key)")
928     (should (equal (gnus-registry-get-id-key "34" 'group) '("togroup")))
929     (should (equal (gnus-registry-get-id-key "34" 'subject) '("subject 4")))
930     (message "Trying to insert a duplicate key")
931     (should-error (registry-insert db "55" '()))
932     (message "Looking up individual keys (gnus-registry-get-or-make-entry)")
933     (should (gnus-registry-get-or-make-entry "22"))
934     (message "Saving the Gnus registry to %s" tempfile)
935     (should (gnus-registry-save tempfile db))
936     (setq size (nth 7 (file-attributes tempfile)))
937     (message "Saving the Gnus registry to %s: size %d" tempfile size)
938     (should (< 0 size))
939     (with-temp-buffer
940       (insert-file-contents-literally tempfile)
941       (should (looking-at (concat ";; Object "
942                                   "Gnus Registry"
943                                   "\n;; EIEIO PERSISTENT OBJECT"))))
944     (message "Reading Gnus registry back")
945     (setq back (eieio-persistent-read tempfile))
946     (should back)
947     (message "Read Gnus registry back: %d keys, expected %d==%d"
948              (registry-size back) n (registry-size db))
949     (should (= (registry-size back) n))
950     (should (= (registry-size back) (registry-size db)))
951     (delete-file tempfile)
952     (message "Pruning Gnus registry to 0 by setting :max-soft")
953     (oset db :max-soft 0)
954     (registry-prune db)
955     (should (= (registry-size db) 0)))
956   (message "Done with Gnus registry usage testing."))
957
958 ;;;###autoload
959 (defun gnus-registry-initialize ()
960 "Initialize the Gnus registry."
961   (interactive)
962   (gnus-message 5 "Initializing the registry")
963   (setq gnus-registry-install t)        ; in case it was 'ask or nil
964   (gnus-registry-install-hooks)
965   (gnus-registry-install-shortcuts)
966   (gnus-registry-read))
967
968 ;;;###autoload
969 (defun gnus-registry-install-hooks ()
970   "Install the registry hooks."
971   (interactive)
972   (add-hook 'gnus-summary-article-move-hook 'gnus-registry-action)
973   (add-hook 'gnus-summary-article-delete-hook 'gnus-registry-action)
974   (add-hook 'gnus-summary-article-expire-hook 'gnus-registry-action)
975   (add-hook 'nnmail-spool-hook 'gnus-registry-spool-action)
976
977   (add-hook 'gnus-save-newsrc-hook 'gnus-registry-save)
978   (add-hook 'gnus-read-newsrc-el-hook 'gnus-registry-read)
979
980   (add-hook 'gnus-summary-prepare-hook 'gnus-registry-register-message-ids))
981
982 (defun gnus-registry-unload-hook ()
983   "Uninstall the registry hooks."
984   (interactive)
985   (remove-hook 'gnus-summary-article-move-hook 'gnus-registry-action)
986   (remove-hook 'gnus-summary-article-delete-hook 'gnus-registry-action)
987   (remove-hook 'gnus-summary-article-expire-hook 'gnus-registry-action)
988   (remove-hook 'nnmail-spool-hook 'gnus-registry-spool-action)
989
990   (remove-hook 'gnus-save-newsrc-hook 'gnus-registry-save)
991   (remove-hook 'gnus-read-newsrc-el-hook 'gnus-registry-read)
992
993   (remove-hook 'gnus-summary-prepare-hook 'gnus-registry-register-message-ids))
994
995 (add-hook 'gnus-registry-unload-hook 'gnus-registry-unload-hook)
996
997 (defun gnus-registry-install-p ()
998   (interactive)
999   (when (eq gnus-registry-install 'ask)
1000     (setq gnus-registry-install
1001           (gnus-y-or-n-p
1002            (concat "Enable the Gnus registry?  "
1003                    "See the variable `gnus-registry-install' "
1004                    "to get rid of this query permanently. ")))
1005     (when gnus-registry-install
1006       ;; we just set gnus-registry-install to t, so initialize the registry!
1007       (gnus-registry-initialize)))
1008 ;;; we could call it here: (customize-variable 'gnus-registry-install)
1009   gnus-registry-install)
1010
1011 ;; TODO: a few things
1012
1013 (provide 'gnus-registry)
1014
1015 ;;; gnus-registry.el ends here