Add subject and sender tracking in Gnus registry for incoming mail.
[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 (mail-header-subject data-header))
298          (sender (mail-header-from data-header))
299          (from (gnus-group-guess-full-name-from-command-method from))
300          (to (if to (gnus-group-guess-full-name-from-command-method to) nil))
301          (to-name (if to to "the Bit Bucket")))
302     (gnus-message 7 "Gnus registry: article %s %s from %s to %s"
303                   id (if method "respooling" "going") from to)
304
305     (gnus-registry-handle-action
306      id
307      ;; unless copying, remove the old "from" group
308      (if (not (equal 'copy action)) from nil)
309      to subject sender)))
310
311 (defun gnus-registry-spool-action (id group &optional subject sender)
312   (let ((to (gnus-group-guess-full-name-from-command-method group))
313         (subject (or subject (message-fetch-field "subject")))
314         (sender (or sender (message-fetch-field "from"))))
315     (when (and (stringp id) (string-match "\r$" id))
316       (setq id (substring id 0 -1)))
317     (gnus-message 7 "Gnus registry: article %s spooled to %s"
318                   id
319                   to)
320     (gnus-registry-handle-action id nil to subject sender)))
321
322 (defun gnus-registry-handle-action (id from to subject sender)
323   (gnus-message
324    10
325    "gnus-registry-handle-action %S" (list id from to subject sender))
326   (let ((db gnus-registry-db)
327         ;; safe if not found
328         (entry (gnus-registry-get-or-make-entry id))
329         (subject (gnus-string-remove-all-properties
330                   (gnus-registry-simplify-subject subject)))
331         (sender (gnus-string-remove-all-properties sender)))
332
333     ;; this could be done by calling `gnus-registry-set-id-key'
334     ;; several times but it's better to bunch the transactions
335     ;; together
336
337     (registry-delete db (list id) nil)
338     (when from
339       (setq entry (cons (delete from (assoc 'group entry))
340                         (assq-delete-all 'group entry))))
341
342     (dolist (kv `((group ,to) (sender ,sender) (subject ,subject)))
343       (when (second kv)
344         (let ((new (or (assq (first kv) entry)
345                        (list (first kv)))))
346           (add-to-list 'new (second kv) t)
347           (setq entry (cons new
348                             (assq-delete-all (first kv) entry))))))
349     (gnus-message 10 "Gnus registry: new entry for %s is %S"
350                   id
351                   entry)
352     (registry-insert db id entry)))
353
354 ;; Function for nn{mail|imap}-split-fancy: look up all references in
355 ;; the cache and if a match is found, return that group.
356 (defun gnus-registry-split-fancy-with-parent ()
357   "Split this message into the same group as its parent.  The parent
358 is obtained from the registry.  This function can be used as an entry
359 in `nnmail-split-fancy' or `nnimap-split-fancy', for example like
360 this: (: gnus-registry-split-fancy-with-parent)
361
362 This function tracks ALL backends, unlike
363 `nnmail-split-fancy-with-parent' which tracks only nnmail
364 messages.
365
366 For a message to be split, it looks for the parent message in the
367 References or In-Reply-To header and then looks in the registry
368 to see which group that message was put in.  This group is
369 returned, unless `gnus-registry-follow-group-p' return nil for
370 that group.
371
372 See the Info node `(gnus)Fancy Mail Splitting' for more details."
373   (let* ((refstr (or (message-fetch-field "references") "")) ; guaranteed
374          (reply-to (message-fetch-field "in-reply-to"))      ; may be nil
375          ;; now, if reply-to is valid, append it to the References
376          (refstr (if reply-to
377                      (concat refstr " " reply-to)
378                    refstr))
379          (references (and refstr (gnus-extract-references refstr)))
380          ;; these may not be used, but the code is cleaner having them up here
381          (sender (gnus-string-remove-all-properties
382                   (message-fetch-field "from")))
383          (subject (gnus-string-remove-all-properties
384                    (gnus-registry-simplify-subject
385                     (message-fetch-field "subject"))))
386
387          (nnmail-split-fancy-with-parent-ignore-groups
388           (if (listp nnmail-split-fancy-with-parent-ignore-groups)
389               nnmail-split-fancy-with-parent-ignore-groups
390             (list nnmail-split-fancy-with-parent-ignore-groups))))
391     (gnus-registry--split-fancy-with-parent-internal
392      :references references
393      :refstr refstr
394      :sender sender
395      :subject subject
396      :log-agent "Gnus registry fancy splitting with parent")))
397
398 (defun* gnus-registry--split-fancy-with-parent-internal
399     (&rest spec
400            &key references refstr sender subject log-agent
401            &allow-other-keys)
402   (gnus-message
403    10
404    "gnus-registry--split-fancy-with-parent-internal %S" spec)
405   (let ((db gnus-registry-db)
406         found)
407     ;; this is a big chain of statements.  it uses
408     ;; gnus-registry-post-process-groups to filter the results after
409     ;; every step.
410     ;; the references string must be valid and parse to valid references
411     (when references
412       (gnus-message
413        9
414        "%s is tracing references %s"
415        log-agent refstr)
416       (dolist (reference (nreverse references))
417         (gnus-message 9 "%s is looking up %s" log-agent reference)
418         (loop for group in (gnus-registry-get-id-key reference 'group)
419               when (gnus-registry-follow-group-p group)
420               do (gnus-message 7 "%s traced %s to %s" log-agent reference group)
421               do (push group found)))
422       ;; filter the found groups and return them
423       ;; the found groups are the full groups
424       (setq found (gnus-registry-post-process-groups
425                    "references" refstr found)))
426
427      ;; else: there were no matches, try the extra tracking by sender
428      (when (and (null found)
429                 (memq 'sender gnus-registry-track-extra)
430                 sender
431                 (gnus-grep-in-list
432                  sender
433                  gnus-registry-unfollowed-addresses))
434        (let ((groups (apply
435                       'append
436                       (mapcar
437                        (lambda (reference)
438                          (gnus-registry-get-id-key reference 'group))
439                        (registry-lookup-secondary-value db 'sender sender)))))
440          (setq found
441                (loop for group in groups
442                      when (gnus-registry-follow-group-p group)
443                      do (gnus-message
444                          ;; warn more if gnus-registry-track-extra
445                          (if gnus-registry-track-extra 7 9)
446                          "%s (extra tracking) traced sender '%s' to %s"
447                          log-agent sender group)
448                      collect group)))
449
450        ;; filter the found groups and return them
451        ;; the found groups are NOT the full groups
452        (setq found (gnus-registry-post-process-groups
453                     "sender" sender found)))
454
455      ;; else: there were no matches, now try the extra tracking by subject
456      (when (and (null found)
457                 (memq 'subject gnus-registry-track-extra)
458                 subject
459                 (< gnus-registry-minimum-subject-length (length subject)))
460        (let ((groups (apply
461                       'append
462                       (mapcar
463                        (lambda (reference)
464                          (gnus-registry-get-id-key reference 'group))
465                        (registry-lookup-secondary-value db 'subject subject)))))
466          (setq found
467                (loop for group in groups
468                      when (gnus-registry-follow-group-p group)
469                      do (gnus-message
470                          ;; warn more if gnus-registry-track-extra
471                          (if gnus-registry-track-extra 7 9)
472                          "%s (extra tracking) traced subject '%s' to %s"
473                          log-agent subject group)
474                      collect group))
475          ;; filter the found groups and return them
476          ;; the found groups are NOT the full groups
477          (setq found (gnus-registry-post-process-groups
478                       "subject" subject found))))
479      ;; after the (cond) we extract the actual value safely
480      (car-safe found)))
481
482 (defun gnus-registry-post-process-groups (mode key groups)
483   "Inspects GROUPS found by MODE for KEY to determine which ones to follow.
484
485 MODE can be 'subject' or 'sender' for example.  The KEY is the
486 value by which MODE was searched.
487
488 Transforms each group name to the equivalent short name.
489
490 Checks if the current Gnus method (from `gnus-command-method' or
491 from `gnus-newsgroup-name') is the same as the group's method.
492 Foreign methods are not supported so they are rejected.
493
494 Reduces the list to a single group, or complains if that's not
495 possible.  Uses `gnus-registry-split-strategy'."
496   (let ((log-agent "gnus-registry-post-process-group")
497         (desc (format "%d groups" (length groups)))
498         out chosen)
499     ;; the strategy can be nil, in which case chosen is nil
500     (setq chosen
501           (case gnus-registry-split-strategy
502             ;; default, take only one-element lists into chosen
503             ((nil)
504              (and (= (length groups) 1)
505                   (car-safe groups)))
506
507             ((first)
508              (car-safe groups))
509
510             ((majority)
511              (let ((freq (make-hash-table
512                           :size 256
513                           :test 'equal)))
514                (mapc (lambda (x) (let ((x (gnus-group-short-name x)))
515                               (puthash x (1+ (gethash x freq 0)) freq)))
516                      groups)
517                (setq desc (format "%d groups, %d unique"
518                                   (length groups)
519                                   (hash-table-count freq)))
520                (car-safe
521                 (sort groups
522                       (lambda (a b)
523                         (> (gethash (gnus-group-short-name a) freq 0)
524                            (gethash (gnus-group-short-name b) freq 0)))))))))
525
526     (if chosen
527         (gnus-message
528          9
529          "%s: strategy %s on %s produced %s"
530          log-agent gnus-registry-split-strategy desc chosen)
531       (gnus-message
532        9
533        "%s: strategy %s on %s did not produce an answer"
534        log-agent
535        (or gnus-registry-split-strategy "default")
536        desc))
537
538     (setq groups (and chosen (list chosen)))
539
540     (dolist (group groups)
541       (let ((m1 (gnus-find-method-for-group group))
542             (m2 (or gnus-command-method
543                     (gnus-find-method-for-group gnus-newsgroup-name)))
544             (short-name (gnus-group-short-name group)))
545         (if (gnus-methods-equal-p m1 m2)
546             (progn
547               ;; this is REALLY just for debugging
548               (when (not (equal group short-name))
549                 (gnus-message
550                  10
551                  "%s: stripped group %s to %s"
552                  log-agent group short-name))
553               (add-to-list 'out short-name))
554           ;; else...
555           (gnus-message
556            7
557            "%s: ignored foreign group %s"
558            log-agent group))))
559
560     (setq out (delq nil out))
561
562     (cond
563      ((= (length out) 1) out)
564      ((null out)
565       (gnus-message
566        5
567        "%s: no matches for %s %s."
568        log-agent out mode key)
569       nil)
570      (t (gnus-message
571          5
572          "%s: too many extra matches (%s) for %s %s.  Returning none."
573          log-agent out mode key)
574         nil))))
575
576 (defun gnus-registry-follow-group-p (group)
577   "Determines if a group name should be followed.
578 Consults `gnus-registry-unfollowed-groups' and
579 `nnmail-split-fancy-with-parent-ignore-groups'."
580   (and group
581        (not (or (gnus-grep-in-list
582                  group
583                  gnus-registry-unfollowed-groups)
584                 (gnus-grep-in-list
585                  group
586                  nnmail-split-fancy-with-parent-ignore-groups)))))
587
588 (defun gnus-registry-wash-for-keywords (&optional force)
589   "Get the keywords of the current article.
590 Overrides existing keywords with FORCE set non-nil."
591   (interactive)
592   (let ((id (gnus-registry-fetch-message-id-fast gnus-current-article))
593         word words)
594     (if (or (not (gnus-registry-get-id-key id 'keyword))
595             force)
596         (with-current-buffer gnus-article-buffer
597           (article-goto-body)
598           (save-window-excursion
599             (save-restriction
600               (narrow-to-region (point) (point-max))
601               (with-syntax-table gnus-adaptive-word-syntax-table
602                 (while (re-search-forward "\\b\\w+\\b" nil t)
603                   (setq word (gnus-string-remove-all-properties
604                               (downcase (buffer-substring
605                                          (match-beginning 0) (match-end 0)))))
606                   (if (> (length word) 2)
607                       (push word words))))))
608           (gnus-registry-set-id-key id 'keyword words)))))
609
610 (defun gnus-registry-keywords ()
611   (let ((table (registry-lookup-secondary gnus-registry-db 'keyword)))
612     (when table (maphash (lambda (k v) k) table))))
613
614 (defun gnus-registry-find-keywords (keyword)
615   (interactive (list
616                 (completing-read "Keyword: " (gnus-registry-keywords) nil t)))
617   (registry-lookup-secondary-value gnus-registry-db 'keyword keyword))
618
619 (defun gnus-registry-register-message-ids ()
620   "Register the Message-ID of every article in the group"
621   (unless (gnus-parameter-registry-ignore gnus-newsgroup-name)
622     (dolist (article gnus-newsgroup-articles)
623       (let* ((id (gnus-registry-fetch-message-id-fast article))
624              (groups (gnus-registry-get-id-key id 'group)))
625         (unless (member gnus-newsgroup-name groups)
626           (gnus-message 9 "Registry: Registering article %d with group %s"
627                         article gnus-newsgroup-name)
628           (gnus-registry-handle-action id nil gnus-newsgroup-name
629            (gnus-registry-fetch-simplified-message-subject-fast article)
630            (gnus-registry-fetch-sender-fast article)))))))
631
632 ;; message field fetchers
633 (defun gnus-registry-fetch-message-id-fast (article)
634   "Fetch the Message-ID quickly, using the internal gnus-data-list function"
635   (if (and (numberp article)
636            (assoc article (gnus-data-list nil)))
637       (mail-header-id (gnus-data-header (assoc article (gnus-data-list nil))))
638     nil))
639
640 (defun gnus-registry-simplify-subject (subject)
641   (if (stringp subject)
642       (gnus-simplify-subject subject)
643     nil))
644
645 (defun gnus-registry-fetch-simplified-message-subject-fast (article)
646   "Fetch the Subject quickly, using the internal gnus-data-list function"
647   (if (and (numberp article)
648            (assoc article (gnus-data-list nil)))
649       (gnus-string-remove-all-properties
650        (gnus-registry-simplify-subject
651         (mail-header-subject (gnus-data-header
652                               (assoc article (gnus-data-list nil))))))
653     nil))
654
655 (defun gnus-registry-fetch-sender-fast (article)
656   "Fetch the Sender quickly, using the internal gnus-data-list function"
657   (if (and (numberp article)
658            (assoc article (gnus-data-list nil)))
659       (gnus-string-remove-all-properties
660        (mail-header-from (gnus-data-header
661                           (assoc article (gnus-data-list nil)))))
662     nil))
663
664 ;; registry marks glue
665 (defun gnus-registry-do-marks (type function)
666   "For each known mark, call FUNCTION for each cell of type TYPE.
667
668 FUNCTION should take two parameters, a mark symbol and the cell value."
669   (dolist (mark-info gnus-registry-marks)
670     (let* ((mark (car-safe mark-info))
671            (data (cdr-safe mark-info))
672            (cell-data (plist-get data type)))
673       (when cell-data
674         (funcall function mark cell-data)))))
675
676 ;;; this is ugly code, but I don't know how to do it better
677 (defun gnus-registry-install-shortcuts ()
678   "Install the keyboard shortcuts and menus for the registry.
679 Uses `gnus-registry-marks' to find what shortcuts to install."
680   (let (keys-plist)
681     (setq gnus-registry-misc-menus nil)
682     (gnus-registry-do-marks
683      :char
684      (lambda (mark data)
685        (let ((function-format
686               (format "gnus-registry-%%s-article-%s-mark" mark)))
687
688 ;;; The following generates these functions:
689 ;;; (defun gnus-registry-set-article-Important-mark (&rest articles)
690 ;;;   "Apply the Important mark to process-marked ARTICLES."
691 ;;;   (interactive (gnus-summary-work-articles current-prefix-arg))
692 ;;;   (gnus-registry-set-article-mark-internal 'Important articles nil t))
693 ;;; (defun gnus-registry-remove-article-Important-mark (&rest articles)
694 ;;;   "Apply the Important mark to process-marked ARTICLES."
695 ;;;   (interactive (gnus-summary-work-articles current-prefix-arg))
696 ;;;   (gnus-registry-set-article-mark-internal 'Important articles t t))
697
698          (dolist (remove '(t nil))
699            (let* ((variant-name (if remove "remove" "set"))
700                   (function-name (format function-format variant-name))
701                   (shortcut (format "%c" data))
702                   (shortcut (if remove (upcase shortcut) shortcut)))
703              (unintern function-name obarray)
704              (eval
705               `(defun
706                  ;; function name
707                  ,(intern function-name)
708                  ;; parameter definition
709                  (&rest articles)
710                  ;; documentation
711                  ,(format
712                    "%s the %s mark over process-marked ARTICLES."
713                    (upcase-initials variant-name)
714                    mark)
715                  ;; interactive definition
716                  (interactive
717                   (gnus-summary-work-articles current-prefix-arg))
718                  ;; actual code
719
720                  ;; if this is called and the user doesn't want the
721                  ;; registry enabled, we'll ask anyhow
722                  (when (eq gnus-registry-install nil)
723                    (setq gnus-registry-install 'ask))
724
725                  ;; now the user is asked if gnus-registry-install is 'ask
726                  (when (gnus-registry-install-p)
727                    (gnus-registry-set-article-mark-internal
728                     ;; all this just to get the mark, I must be doing it wrong
729                     (intern ,(symbol-name mark))
730                     articles ,remove t)
731                    (gnus-message
732                     9
733                     "Applying mark %s to %d articles"
734                     ,(symbol-name mark) (length articles))
735                    (dolist (article articles)
736                      (gnus-summary-update-article
737                       article
738                       (assoc article (gnus-data-list nil)))))))
739              (push (intern function-name) keys-plist)
740              (push shortcut keys-plist)
741              (push (vector (format "%s %s"
742                                    (upcase-initials variant-name)
743                                    (symbol-name mark))
744                            (intern function-name) t)
745                    gnus-registry-misc-menus)
746              (gnus-message
747               9
748               "Defined mark handling function %s"
749               function-name))))))
750     (gnus-define-keys-1
751      '(gnus-registry-mark-map "M" gnus-summary-mark-map)
752      keys-plist)
753     (add-hook 'gnus-summary-menu-hook
754               (lambda ()
755                 (easy-menu-add-item
756                  gnus-summary-misc-menu
757                  nil
758                  (cons "Registry Marks" gnus-registry-misc-menus))))))
759
760 ;;; use like this:
761 ;;; (defalias 'gnus-user-format-function-M
762 ;;;           'gnus-registry-user-format-function-M)
763 (defun gnus-registry-user-format-function-M (headers)
764   (let* ((id (mail-header-message-id headers))
765          (marks (when id (gnus-registry-get-id-key id 'mark))))
766     (apply 'concat (mapcar (lambda (mark)
767                              (let ((c
768                                     (plist-get
769                                      (cdr-safe
770                                       (assoc mark gnus-registry-marks))
771                                      :char)))
772                                (if c
773                                    (list c)
774                                  nil)))
775                            marks))))
776
777 (defun gnus-registry-read-mark ()
778   "Read a mark name from the user with completion."
779   (let ((mark (gnus-completing-read
780                "Label"
781                (mapcar 'symbol-name (mapcar 'car gnus-registry-marks))
782                nil nil nil
783                (symbol-name gnus-registry-default-mark))))
784     (when (stringp mark)
785       (intern mark))))
786
787 (defun gnus-registry-set-article-mark (&rest articles)
788   "Apply a mark to process-marked ARTICLES."
789   (interactive (gnus-summary-work-articles current-prefix-arg))
790   (gnus-registry-set-article-mark-internal (gnus-registry-read-mark)
791                                            articles nil t))
792
793 (defun gnus-registry-remove-article-mark (&rest articles)
794   "Remove a mark from process-marked ARTICLES."
795   (interactive (gnus-summary-work-articles current-prefix-arg))
796   (gnus-registry-set-article-mark-internal (gnus-registry-read-mark)
797                                            articles t t))
798
799 (defun gnus-registry-set-article-mark-internal (mark
800                                                 articles
801                                                 &optional remove
802                                                 show-message)
803   "Apply or remove MARK across a list of ARTICLES."
804   (let ((article-id-list
805          (mapcar 'gnus-registry-fetch-message-id-fast articles)))
806     (dolist (id article-id-list)
807       (let* ((marks (delq mark (gnus-registry-get-id-key id 'mark)))
808              (marks (if remove marks (cons mark marks))))
809         (when show-message
810           (gnus-message 1 "%s mark %s with message ID %s, resulting in %S"
811                         (if remove "Removing" "Adding")
812                         mark id marks))
813         (gnus-registry-set-id-key id 'mark marks)))))
814
815 (defun gnus-registry-get-article-marks (&rest articles)
816   "Get the Gnus registry marks for ARTICLES and show them if interactive.
817 Uses process/prefix conventions.  For multiple articles,
818 only the last one's marks are returned."
819   (interactive (gnus-summary-work-articles 1))
820   (let* ((article (last articles))
821          (id (gnus-registry-fetch-message-id-fast article))
822          (marks (when id (gnus-registry-get-id-key id 'mark))))
823     (when (interactive-p)
824       (gnus-message 1 "Marks are %S" marks))
825     marks))
826
827 (defun gnus-registry-group-count (id)
828   "Get the number of groups of a message, based on the message ID."
829   (length (gnus-registry-get-id-key id 'group)))
830
831 (defun gnus-registry-get-or-make-entry (id)
832   (let* ((db gnus-registry-db)
833          ;; safe if not found
834          (entries (registry-lookup db (list id))))
835
836     (when (null entries)
837       (registry-insert db id (list (list 'creation-time (current-time))
838                                    '(group) '(sender) '(subject)))
839       (setq entries (registry-lookup db (list id))))
840
841     (nth 1 (assoc id entries))))
842
843 (defun gnus-registry-delete-entries (idlist)
844   (registry-delete gnus-registry-db idlist nil))
845
846 (defun gnus-registry-get-id-key (id key)
847   (cdr-safe (assq key (gnus-registry-get-or-make-entry id))))
848
849 (defun gnus-registry-set-id-key (id key vals)
850   (let* ((db gnus-registry-db)
851          (entry (gnus-registry-get-or-make-entry id)))
852     (registry-delete db (list id) nil)
853     (setq entry (cons (cons key vals) (assq-delete-all key entry)))
854     (registry-insert db id entry)
855     entry))
856
857 (defun gnus-registry-import-eld (file)
858   (interactive "fOld registry file to import? ")
859   ;; example content:
860   ;;   (setq gnus-registry-alist '(
861   ;; ("<messageID>" ((marks nil)
862   ;;                 (mtime 19365 1776 440496)
863   ;;                 (sender . "root (Cron Daemon)")
864   ;;                 (subject . "Cron"))
865   ;;  "cron" "nnml+private:cron")
866   (load file t)
867   (when (boundp 'gnus-registry-alist)
868     (let* ((old (symbol-value 'gnus-registry-alist))
869            (count 0)
870            (expected (length old))
871            entry)
872       (while (car-safe old)
873         (incf count)
874         ;; don't use progress reporters for backwards compatibility
875         (when (and (< 0 expected)
876                    (= 0 (mod count 100)))
877           (message "importing: %d of %d (%.2f%%)"
878                    count expected (/ (* 100 count) expected)))
879         (setq entry (car-safe old)
880               old (cdr-safe old))
881         (let* ((id (car-safe entry))
882                (new-entry (gnus-registry-get-or-make-entry id))
883                (rest (cdr-safe entry))
884                (groups (loop for p in rest
885                              when (stringp p)
886                              collect p))
887                extra-cell key val)
888           ;; remove all the strings from the entry
889           (delete* nil rest :test (lambda (a b) (stringp b)))
890           (gnus-registry-set-id-key id 'group groups)
891           ;; just use the first extra element
892           (setq rest (car-safe rest))
893           (while (car-safe rest)
894             (setq extra-cell (car-safe rest)
895                   key (car-safe extra-cell)
896                   val (cdr-safe extra-cell)
897                   rest (cdr-safe rest))
898             (when (and val (atom val))
899               (setq val (list val)))
900             (gnus-registry-set-id-key id key val))))
901       (message "Import done, collected %d entries" count))))
902
903 (ert-deftest gnus-registry-usage-test ()
904   (let* ((n 100)
905          (tempfile (make-temp-file "gnus-registry-persist"))
906          (db (gnus-registry-make-db tempfile))
907          (gnus-registry-db db)
908          back size)
909     (message "Adding %d keys to the test Gnus registry" n)
910     (dotimes (i n)
911       (let ((id (number-to-string i)))
912         (gnus-registry-handle-action id
913                                      (if (>= 50 i) "fromgroup" nil)
914                                      "togroup"
915                                      (when (>= 70 i)
916                                        (format "subject %d" (mod i 10)))
917                                      (when (>= 80 i)
918                                        (format "sender %d" (mod i 10))))))
919     (message "Testing Gnus registry size is %d" n)
920     (should (= n (registry-size db)))
921     (message "Looking up individual keys (registry-lookup)")
922     (should (equal (loop for e
923                          in (mapcar 'cadr
924                                     (registry-lookup db '("20" "83" "72")))
925                          collect (assq 'subject e)
926                          collect (assq 'sender e)
927                          collect (assq 'group e))
928                    '((subject "subject 0") (sender "sender 0") (group "togroup")
929                      (subject) (sender) (group "togroup")
930                      (subject) (sender "sender 2") (group "togroup"))))
931
932     (message "Looking up individual keys (gnus-registry-id-key)")
933     (should (equal (gnus-registry-get-id-key "34" 'group) '("togroup")))
934     (should (equal (gnus-registry-get-id-key "34" 'subject) '("subject 4")))
935     (message "Trying to insert a duplicate key")
936     (should-error (registry-insert db "55" '()))
937     (message "Looking up individual keys (gnus-registry-get-or-make-entry)")
938     (should (gnus-registry-get-or-make-entry "22"))
939     (message "Saving the Gnus registry to %s" tempfile)
940     (should (gnus-registry-save tempfile db))
941     (setq size (nth 7 (file-attributes tempfile)))
942     (message "Saving the Gnus registry to %s: size %d" tempfile size)
943     (should (< 0 size))
944     (with-temp-buffer
945       (insert-file-contents-literally tempfile)
946       (should (looking-at (concat ";; Object "
947                                   "Gnus Registry"
948                                   "\n;; EIEIO PERSISTENT OBJECT"))))
949     (message "Reading Gnus registry back")
950     (setq back (eieio-persistent-read tempfile))
951     (should back)
952     (message "Read Gnus registry back: %d keys, expected %d==%d"
953              (registry-size back) n (registry-size db))
954     (should (= (registry-size back) n))
955     (should (= (registry-size back) (registry-size db)))
956     (delete-file tempfile)
957     (message "Pruning Gnus registry to 0 by setting :max-soft")
958     (oset db :max-soft 0)
959     (registry-prune db)
960     (should (= (registry-size db) 0)))
961   (message "Done with Gnus registry usage testing."))
962
963 ;;;###autoload
964 (defun gnus-registry-initialize ()
965 "Initialize the Gnus registry."
966   (interactive)
967   (gnus-message 5 "Initializing the registry")
968   (setq gnus-registry-install t)        ; in case it was 'ask or nil
969   (gnus-registry-install-hooks)
970   (gnus-registry-install-shortcuts)
971   (gnus-registry-read))
972
973 ;;;###autoload
974 (defun gnus-registry-install-hooks ()
975   "Install the registry hooks."
976   (interactive)
977   (add-hook 'gnus-summary-article-move-hook 'gnus-registry-action)
978   (add-hook 'gnus-summary-article-delete-hook 'gnus-registry-action)
979   (add-hook 'gnus-summary-article-expire-hook 'gnus-registry-action)
980   (add-hook 'nnmail-spool-hook 'gnus-registry-spool-action)
981
982   (add-hook 'gnus-save-newsrc-hook 'gnus-registry-save)
983   (add-hook 'gnus-read-newsrc-el-hook 'gnus-registry-read)
984
985   (add-hook 'gnus-summary-prepare-hook 'gnus-registry-register-message-ids))
986
987 (defun gnus-registry-unload-hook ()
988   "Uninstall the registry hooks."
989   (interactive)
990   (remove-hook 'gnus-summary-article-move-hook 'gnus-registry-action)
991   (remove-hook 'gnus-summary-article-delete-hook 'gnus-registry-action)
992   (remove-hook 'gnus-summary-article-expire-hook 'gnus-registry-action)
993   (remove-hook 'nnmail-spool-hook 'gnus-registry-spool-action)
994
995   (remove-hook 'gnus-save-newsrc-hook 'gnus-registry-save)
996   (remove-hook 'gnus-read-newsrc-el-hook 'gnus-registry-read)
997
998   (remove-hook 'gnus-summary-prepare-hook 'gnus-registry-register-message-ids))
999
1000 (add-hook 'gnus-registry-unload-hook 'gnus-registry-unload-hook)
1001
1002 (defun gnus-registry-install-p ()
1003   (interactive)
1004   (when (eq gnus-registry-install 'ask)
1005     (setq gnus-registry-install
1006           (gnus-y-or-n-p
1007            (concat "Enable the Gnus registry?  "
1008                    "See the variable `gnus-registry-install' "
1009                    "to get rid of this query permanently. ")))
1010     (when gnus-registry-install
1011       ;; we just set gnus-registry-install to t, so initialize the registry!
1012       (gnus-registry-initialize)))
1013 ;;; we could call it here: (customize-variable 'gnus-registry-install)
1014   gnus-registry-install)
1015
1016 ;; TODO: a few things
1017
1018 (provide 'gnus-registry)
1019
1020 ;;; gnus-registry.el ends here