Merge the t-gnus-6_17-quimby branch.
[elisp/gnus.git-] / lisp / nnvirtual.el
1 ;;; nnvirtual.el --- virtual newsgroups access for Gnus
2
3 ;; Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
4 ;;   2003, 2004, 2005, 2006 Free Software Foundation, Inc.
5
6 ;; Author: David Moore <dmoore@ucsd.edu>
7 ;;      Lars Magne Ingebrigtsen <larsi@gnus.org>
8 ;;      Masanobu UMEDA <umerin@flab.flab.fujitsu.junet>
9 ;; Keywords: news
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
25 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26 ;; Boston, MA 02110-1301, USA.
27
28 ;;; Commentary:
29
30 ;; The other access methods (nntp, nnspool, etc) are general news
31 ;; access methods.  This module relies on Gnus and can not be used
32 ;; separately.
33
34 ;;; Code:
35
36 (eval-when-compile (require 'cl))
37
38 (require 'nntp)
39 (require 'nnheader)
40 (require 'gnus)
41 (require 'nnoo)
42 (require 'gnus-util)
43 (require 'gnus-start)
44 (require 'gnus-sum)
45 (require 'gnus-msg)
46
47 (nnoo-declare nnvirtual)
48
49 (defvoo nnvirtual-always-rescan t
50   "If non-nil, always scan groups for unread articles when entering a group.
51 If this variable is nil and you read articles in a component group
52 after the virtual group has been activated, the read articles from the
53 component group will show up when you enter the virtual group.")
54
55 (defvoo nnvirtual-component-regexp nil
56   "Regexp to match component groups.")
57
58 (defvoo nnvirtual-component-groups nil
59   "Component group in this nnvirtual group.")
60
61 \f
62
63 (defconst nnvirtual-version "nnvirtual 1.1")
64
65 (defvoo nnvirtual-current-group nil)
66
67 (defvoo nnvirtual-mapping-table nil
68   "Table of rules on how to map between component group and article number to virtual article number.")
69
70 (defvoo nnvirtual-mapping-offsets nil
71   "Table indexed by component group to an offset to be applied to article numbers in that group.")
72
73 (defvoo nnvirtual-mapping-len 0
74   "Number of articles in this virtual group.")
75
76 (defvoo nnvirtual-mapping-reads nil
77   "Compressed sequence of read articles on the virtual group as computed from the unread status of individual component groups.")
78
79 (defvoo nnvirtual-mapping-marks nil
80   "Compressed marks alist for the virtual group as computed from the marks of individual component groups.")
81
82 (defvoo nnvirtual-info-installed nil
83   "T if we have already installed the group info for this group, and shouldn't blast over it again.")
84
85 (defvoo nnvirtual-status-string "")
86
87 (eval-and-compile
88   (autoload 'gnus-cache-articles-in-group "gnus-cache"))
89
90 \f
91
92 ;;; Interface functions.
93
94 (nnoo-define-basics nnvirtual)
95
96
97 (deffoo nnvirtual-retrieve-headers (articles &optional newsgroup
98                                              server fetch-old)
99   (when (nnvirtual-possibly-change-server server)
100     (save-excursion
101       (set-buffer nntp-server-buffer)
102       (erase-buffer)
103       (if (stringp (car articles))
104           'headers
105         (let ((vbuf (nnheader-set-temp-buffer
106                      (get-buffer-create " *virtual headers*")))
107               (carticles (nnvirtual-partition-sequence articles))
108               (system-name (system-name))
109               cgroup carticle article result prefix)
110           (while carticles
111             (setq cgroup (caar carticles))
112             (setq articles (cdar carticles))
113             (pop carticles)
114             (when (and articles
115                        (gnus-check-server
116                         (gnus-find-method-for-group cgroup) t)
117                        (gnus-request-group cgroup t)
118                        (setq prefix (gnus-group-real-prefix cgroup))
119                        ;; FIX FIX FIX we want to check the cache!
120                        ;; This is probably evil if people have set
121                        ;; gnus-use-cache to nil themselves, but I
122                        ;; have no way of finding the true value of it.
123                        (let ((gnus-use-cache t))
124                          (setq result (gnus-retrieve-headers
125                                        articles cgroup nil))))
126               (set-buffer nntp-server-buffer)
127               ;; If we got HEAD headers, we convert them into NOV
128               ;; headers.  This is slow, inefficient and, come to think
129               ;; of it, downright evil.  So sue me.  I couldn't be
130               ;; bothered to write a header parse routine that could
131               ;; parse a mixed HEAD/NOV buffer.
132               (when (eq result 'headers)
133                 (nnvirtual-convert-headers))
134               (goto-char (point-min))
135               (while (not (eobp))
136                 (delete-region (point)
137                                (progn
138                                  (setq carticle (read nntp-server-buffer))
139                                  (point)))
140
141                 ;; We remove this article from the articles list, if
142                 ;; anything is left in the articles list after going through
143                 ;; the entire buffer, then those articles have been
144                 ;; expired or canceled, so we appropriately update the
145                 ;; component group below.  They should be coming up
146                 ;; generally in order, so this shouldn't be slow.
147                 (setq articles (delq carticle articles))
148
149                 (setq article (nnvirtual-reverse-map-article cgroup carticle))
150                 (if (null article)
151                     ;; This line has no reverse mapping, that means it
152                     ;; was an extra article reference returned by nntp.
153                     (progn
154                       (beginning-of-line)
155                       (delete-region (point) (progn (forward-line 1) (point))))
156                   ;; Otherwise insert the virtual article number,
157                   ;; and clean up the xrefs.
158                   (princ article nntp-server-buffer)
159                   (nnvirtual-update-xref-header cgroup carticle
160                                                 prefix system-name)
161                   (forward-line 1))
162                 )
163
164               (set-buffer vbuf)
165               (goto-char (point-max))
166               (insert-buffer-substring nntp-server-buffer))
167             ;; Anything left in articles is expired or canceled.
168             ;; Could be smart and not tell it about articles already known?
169             (when articles
170               (gnus-group-make-articles-read cgroup articles))
171             )
172
173           ;; The headers are ready for reading, so they are inserted into
174           ;; the nntp-server-buffer, which is where Gnus expects to find
175           ;; them.
176           (prog1
177               (save-excursion
178                 (set-buffer nntp-server-buffer)
179                 (erase-buffer)
180                 (insert-buffer-substring vbuf)
181                 ;; FIX FIX FIX, we should be able to sort faster than
182                 ;; this if needed, since each cgroup is sorted, we just
183                 ;; need to merge
184                 (sort-numeric-fields 1 (point-min) (point-max))
185                 'nov)
186             (kill-buffer vbuf)))))))
187
188
189 (defvoo nnvirtual-last-accessed-component-group nil)
190
191 (deffoo nnvirtual-request-article (article &optional group server buffer)
192   (when (nnvirtual-possibly-change-server server)
193     (if (stringp article)
194         ;; This is a fetch by Message-ID.
195         (cond
196          ((not nnvirtual-last-accessed-component-group)
197           (nnheader-report
198            'nnvirtual "Don't know what server to request from"))
199          (t
200           (save-excursion
201             (when buffer
202               (set-buffer buffer))
203             (let* ((gnus-override-method nil)
204                    (method (gnus-find-method-for-group
205                             nnvirtual-last-accessed-component-group)))
206               (funcall (gnus-get-function method 'request-article)
207                        article nil (nth 1 method) buffer)))))
208       ;; This is a fetch by number.
209       (let* ((amap (nnvirtual-map-article article))
210              (cgroup (car amap)))
211         (cond
212          ((not amap)
213           (nnheader-report 'nnvirtual "No such article: %s" article))
214          ((not (gnus-check-group cgroup))
215           (nnheader-report
216            'nnvirtual "Can't open server where %s exists" cgroup))
217          ((not (gnus-request-group cgroup t))
218           (nnheader-report 'nnvirtual "Can't open component group %s" cgroup))
219          (t
220           (setq nnvirtual-last-accessed-component-group cgroup)
221           (if buffer
222               (save-excursion
223                 (set-buffer buffer)
224                 ;; We bind this here to avoid double decoding.
225                 (let ((gnus-article-decode-hook nil))
226                   (gnus-request-article-this-buffer (cdr amap) cgroup)))
227             (gnus-request-article (cdr amap) cgroup))))))))
228
229
230 (deffoo nnvirtual-open-server (server &optional defs)
231   (unless (assq 'nnvirtual-component-regexp defs)
232     (push `(nnvirtual-component-regexp ,server)
233           defs))
234   (nnoo-change-server 'nnvirtual server defs)
235   (if nnvirtual-component-groups
236       t
237     (setq nnvirtual-mapping-table nil
238           nnvirtual-mapping-offsets nil
239           nnvirtual-mapping-len 0
240           nnvirtual-mapping-reads nil
241           nnvirtual-mapping-marks nil
242           nnvirtual-info-installed nil)
243     (when nnvirtual-component-regexp
244       ;; Go through the newsrc alist and find all component groups.
245       (let ((newsrc (cdr gnus-newsrc-alist))
246             group)
247         (while (setq group (car (pop newsrc)))
248           (when (string-match nnvirtual-component-regexp group) ; Match
249             ;; Add this group to the list of component groups.
250             (setq nnvirtual-component-groups
251                   (cons group (delete group nnvirtual-component-groups)))))))
252     (if (not nnvirtual-component-groups)
253         (nnheader-report 'nnvirtual "No component groups: %s" server)
254       t)))
255
256
257 (deffoo nnvirtual-request-group (group &optional server dont-check)
258   (nnvirtual-possibly-change-server server)
259   (setq nnvirtual-component-groups
260         (delete (nnvirtual-current-group) nnvirtual-component-groups))
261   (cond
262    ((null nnvirtual-component-groups)
263     (setq nnvirtual-current-group nil)
264     (nnheader-report 'nnvirtual "No component groups in %s" group))
265    (t
266     (setq nnvirtual-current-group group)
267     (when (or (not dont-check)
268               nnvirtual-always-rescan)
269       (nnvirtual-create-mapping)
270       (when nnvirtual-always-rescan
271         (nnvirtual-request-update-info
272          (nnvirtual-current-group)
273          (gnus-get-info (nnvirtual-current-group)))))
274     (nnheader-insert "211 %d 1 %d %s\n"
275                      nnvirtual-mapping-len nnvirtual-mapping-len group))))
276
277
278 (deffoo nnvirtual-request-type (group &optional article)
279   (if (not article)
280       'unknown
281     (if (numberp article)
282         (let ((mart (nnvirtual-map-article article)))
283           (if mart
284               (gnus-request-type (car mart) (cdr mart))))
285       (gnus-request-type
286        nnvirtual-last-accessed-component-group nil))))
287
288 (deffoo nnvirtual-request-update-mark (group article mark)
289   (let* ((nart (nnvirtual-map-article article))
290          (cgroup (car nart)))
291     (when (and nart
292                (memq mark gnus-auto-expirable-marks)
293                ;; The component group might be a virtual group.
294                (= mark (gnus-request-update-mark cgroup (cdr nart) mark))
295                (gnus-group-auto-expirable-p cgroup))
296       (setq mark gnus-expirable-mark)))
297   mark)
298
299
300 (deffoo nnvirtual-close-group (group &optional server)
301   (when (and (nnvirtual-possibly-change-server server)
302              (not (gnus-ephemeral-group-p (nnvirtual-current-group))))
303     (nnvirtual-update-read-and-marked t t))
304   t)
305
306
307 (deffoo nnvirtual-request-list (&optional server)
308   (nnheader-report 'nnvirtual "LIST is not implemented."))
309
310
311 (deffoo nnvirtual-request-newgroups (date &optional server)
312   (nnheader-report 'nnvirtual "NEWGROUPS is not supported."))
313
314
315 (deffoo nnvirtual-request-list-newsgroups (&optional server)
316   (nnheader-report 'nnvirtual "LIST NEWSGROUPS is not implemented."))
317
318
319 (deffoo nnvirtual-request-update-info (group info &optional server)
320   (when (and (nnvirtual-possibly-change-server server)
321              (not nnvirtual-info-installed))
322     ;; Install the precomputed lists atomically, so the virtual group
323     ;; is not left in a half-way state in case of C-g.
324     (gnus-atomic-progn
325       (setcar (cddr info) nnvirtual-mapping-reads)
326       (if (nthcdr 3 info)
327           (setcar (nthcdr 3 info) nnvirtual-mapping-marks)
328         (when nnvirtual-mapping-marks
329           (setcdr (nthcdr 2 info) (list nnvirtual-mapping-marks))))
330       (setq nnvirtual-info-installed t))
331     t))
332
333
334 (deffoo nnvirtual-catchup-group (group &optional server all)
335   (when (and (nnvirtual-possibly-change-server server)
336              (not (gnus-ephemeral-group-p (nnvirtual-current-group))))
337     ;; copy over existing marks first, in case they set anything
338     (nnvirtual-update-read-and-marked nil nil)
339     ;; do a catchup on all component groups
340     (let ((gnus-group-marked (copy-sequence nnvirtual-component-groups))
341           (gnus-expert-user t))
342       ;; Make sure all groups are activated.
343       (mapc
344        (lambda (g)
345          (when (not (numberp (gnus-group-unread g)))
346            (gnus-activate-group g)))
347        nnvirtual-component-groups)
348       (save-excursion
349         (set-buffer gnus-group-buffer)
350         (gnus-group-catchup-current nil all)))))
351
352
353 (deffoo nnvirtual-find-group-art (group article)
354   "Return the real group and article for virtual GROUP and ARTICLE."
355   (nnvirtual-map-article article))
356
357
358 (deffoo nnvirtual-request-post (&optional server)
359   (if (not gnus-message-group-art)
360       (nnheader-report 'nnvirtual "Can't post to an nnvirtual group")
361     (let ((group (car (nnvirtual-find-group-art
362                        (car gnus-message-group-art)
363                        (cdr gnus-message-group-art)))))
364       (gnus-request-post (gnus-find-method-for-group group)))))
365
366
367 (deffoo nnvirtual-request-expire-articles (articles group
368                                                     &optional server force)
369   (nnvirtual-possibly-change-server server)
370   (setq nnvirtual-component-groups
371         (delete (nnvirtual-current-group) nnvirtual-component-groups))
372   (let (unexpired)
373     (dolist (group nnvirtual-component-groups)
374       (setq unexpired (nconc unexpired
375                              (mapcar
376                               #'(lambda (article)
377                                   (nnvirtual-reverse-map-article
378                                    group article))
379                               (gnus-uncompress-range
380                                (gnus-group-expire-articles-1 group))))))
381     (sort (delq nil unexpired) '<)))
382
383 \f
384 ;;; Internal functions.
385
386 (defun nnvirtual-convert-headers ()
387   "Convert HEAD headers into NOV headers."
388   (with-current-buffer nntp-server-buffer
389     (let* ((dependencies (make-vector 100 0))
390            (headers (gnus-get-newsgroup-headers dependencies)))
391       (erase-buffer)
392       (mapc 'nnheader-insert-nov headers))))
393
394
395 (defun nnvirtual-update-xref-header (group article prefix system-name)
396   "Edit current NOV header in current buffer to have an xref to the component group, and also server prefix any existing xref lines."
397   ;; Move to beginning of Xref field, creating a slot if needed.
398   (beginning-of-line)
399   (looking-at
400    "[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t")
401   (goto-char (match-end 0))
402   (unless (search-forward "\t" (point-at-eol) 'move)
403     (insert "\t"))
404
405   ;; Remove any spaces at the beginning of the Xref field.
406   (while (eq (char-after (1- (point))) ? )
407     (forward-char -1)
408     (delete-char 1))
409
410   (insert "Xref: " system-name " " group ":")
411   (princ article (current-buffer))
412   (insert " ")
413
414   ;; If there were existing xref lines, clean them up to have the correct
415   ;; component server prefix.
416   (save-restriction
417     (narrow-to-region (point)
418                       (or (search-forward "\t" (point-at-eol) t)
419                           (point-at-eol)))
420     (goto-char (point-min))
421     (when (re-search-forward "Xref: *[^\n:0-9 ]+ *" nil t)
422       (replace-match "" t t))
423     (goto-char (point-min))
424     (when (re-search-forward
425            (concat (regexp-quote (gnus-group-real-name group)) ":[0-9]+")
426            nil t)
427       (replace-match "" t t))
428     (unless (eobp)
429       (insert " ")
430       (when (not (string= "" prefix))
431         (while (re-search-forward "[^ ]+:[0-9]+" nil t)
432           (save-excursion
433             (goto-char (match-beginning 0))
434             (insert prefix))))))
435
436   ;; Ensure a trailing \t.
437   (end-of-line)
438   (or (eq (char-after (1- (point))) ?\t)
439       (insert ?\t)))
440
441
442 (defun nnvirtual-possibly-change-server (server)
443   (or (not server)
444       (nnoo-current-server-p 'nnvirtual server)
445       (nnvirtual-open-server server)))
446
447
448 (defun nnvirtual-update-read-and-marked (read-p update-p)
449   "Copy marks from the virtual group to the component groups.
450 If READ-P is not nil, update the (un)read status of the components.
451 If UPDATE-P is not nil, call gnus-group-update-group on the components."
452   (when nnvirtual-current-group
453     (let ((unreads (and read-p
454                         (nnvirtual-partition-sequence
455                          (gnus-list-of-unread-articles
456                           (nnvirtual-current-group)))))
457           (type-marks
458            (delq nil
459                  (mapcar (lambda (ml)
460                            (if (eq (car ml) 'score)
461                                nil
462                              (cons (car ml)
463                                    (nnvirtual-partition-sequence (cdr ml)))))
464                          (gnus-info-marks (gnus-get-info
465                                            (nnvirtual-current-group))))))
466           type groups info)
467
468       ;; Ok, atomically move all of the (un)read info, clear any old
469       ;; marks, and move all of the current marks.  This way if someone
470       ;; hits C-g, you won't leave the component groups in a half-way state.
471       (progn
472         ;; move (un)read
473         ;; bind for workaround guns-update-read-articles
474         (let ((gnus-newsgroup-active nil))
475           (dolist (entry unreads)
476             (gnus-update-read-articles (car entry) (cdr entry))))
477
478         ;; clear all existing marks on the component groups
479         (dolist (group nnvirtual-component-groups)
480           (when (and (setq info (gnus-get-info group))
481                      (gnus-info-marks info))
482             (gnus-info-set-marks
483              info
484              (if (assq 'score (gnus-info-marks info))
485                  (list (assq 'score (gnus-info-marks info)))
486                nil))))
487
488         ;; Ok, currently type-marks is an assq list with keys of a mark type,
489         ;; with data of an assq list with keys of component group names
490         ;; and the articles which correspond to that key/group pair.
491         (dolist (mark type-marks)
492           (setq type (car mark))
493           (setq groups (cdr mark))
494           (dolist (carticles groups)
495             (gnus-add-marked-articles (car carticles) type (cdr carticles)
496                                       nil t))))
497
498       ;; possibly update the display, it is really slow
499       (when update-p
500         (dolist (group nnvirtual-component-groups)
501           (gnus-group-update-group group t))))))
502
503
504 (defun nnvirtual-current-group ()
505   "Return the prefixed name of the current nnvirtual group."
506   (concat "nnvirtual:" nnvirtual-current-group))
507
508
509
510 ;;; This is currently O(kn^2) to merge n lists of length k.
511 ;;; You could do it in O(knlogn), but we have a small n, and the
512 ;;; overhead of the other approach is probably greater.
513 (defun nnvirtual-merge-sorted-lists (&rest lists)
514   "Merge many sorted lists of numbers."
515   (if (null (cdr lists))
516       (car lists)
517     (sort (apply 'nconc lists) '<)))
518
519
520 ;;; We map between virtual articles and real articles in a manner
521 ;;; which keeps the size of the virtual active list the same as the
522 ;;; sum of the component active lists.
523
524 ;;; To achieve fair mixing of the groups, the last article in each of
525 ;;; N component groups will be in the last N articles in the virtual
526 ;;; group.
527
528 ;;; If you have 3 components A, B and C, with articles 1-8, 1-5, and
529 ;;; 6-7 respectively, then the virtual article numbers look like:
530 ;;;
531 ;;;  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15
532 ;;;  A1 A2 A3 A4 B1 A5 B2 A6 B3 A7 B4 C6 A8 B5 C7
533
534 ;;; To compute these mappings we generate a couple tables and then
535 ;;; do some fast operations on them.  Tables for the example above:
536 ;;;
537 ;;; Offsets - [(A 0) (B -3) (C -1)]
538 ;;;
539 ;;;               a  b  c  d  e
540 ;;; Mapping - ([  3  0  1  3  0 ]
541 ;;;            [  6  3  2  9  3 ]
542 ;;;            [  8  6  3 15  9 ])
543 ;;;
544 ;;; (note column 'e' is different in real algorithm, which is slightly
545 ;;;  different than described here, but this gives you the methodology.)
546 ;;;
547 ;;; The basic idea is this, when going from component->virtual, apply
548 ;;; the appropriate offset to the article number.  Then search the first
549 ;;; column of the table for a row where 'a' is less than or equal to the
550 ;;; modified number.  You can see that only group A can therefore go to
551 ;;; the first row, groups A and B to the second, and all to the last.
552 ;;; The third column of the table is telling us the number of groups
553 ;;; which might be able to reach that row (it might increase by more than
554 ;;; 1 if several groups have the same size).
555 ;;; Then column 'b' provides an additional offset you apply when you have
556 ;;; found the correct row.  You then multiply by 'c' and add on the groups
557 ;;; _position_ in the offset table.  The basic idea here is that on
558 ;;; any given row we are going to map back and forth using X'=X*c+Y and
559 ;;; X=(X'/c), Y=(X' mod c).  Then once you've done this transformation,
560 ;;; you apply a final offset from column 'e' to give the virtual article.
561 ;;;
562 ;;; Going the other direction, you instead search on column 'd' instead
563 ;;; of 'a', and apply everything in reverse order.
564
565 ;;; Convert component -> virtual:
566 ;;; set num = num - Offset(group)
567 ;;; find first row in Mapping where num <= 'a'
568 ;;; num = (num-'b')*c + Position(group) + 'e'
569
570 ;;; Convert virtual -> component:
571 ;;; find first row in Mapping where num <= 'd'
572 ;;; num = num - 'e'
573 ;;; group_pos = num mod 'c'
574 ;;; num = (num / 'c') + 'b' + Offset(group_pos)
575
576 ;;; Easy no? :)
577 ;;;
578 ;;; Well actually, you need to keep column e offset smaller by the 'c'
579 ;;; column for that line, and always add 1 more when going from
580 ;;; component -> virtual.  Otherwise you run into a problem with
581 ;;; unique reverse mapping.
582
583 (defun nnvirtual-map-article (article)
584   "Return a cons of the component group and article corresponding to the given virtual ARTICLE."
585   (let ((table nnvirtual-mapping-table)
586         entry group-pos)
587     (while (and table
588                 (> article (aref (car table) 3)))
589       (setq table (cdr table)))
590     (when (and table
591                (> article 0))
592       (setq entry (car table))
593       (setq article (- article (aref entry 4) 1))
594       (setq group-pos (mod article (aref entry 2)))
595       (cons (car (aref nnvirtual-mapping-offsets group-pos))
596             (+ (/ article (aref entry 2))
597                (aref entry 1)
598                (cdr (aref nnvirtual-mapping-offsets group-pos)))
599             ))
600     ))
601
602
603
604 (defun nnvirtual-reverse-map-article (group article)
605   "Return the virtual article number corresponding to the given component GROUP and ARTICLE."
606   (when (numberp article)
607     (let ((table nnvirtual-mapping-table)
608           (group-pos 0)
609           entry)
610       (while (not (string= group (car (aref nnvirtual-mapping-offsets
611                                             group-pos))))
612         (setq group-pos (1+ group-pos)))
613       (setq article (- article (cdr (aref nnvirtual-mapping-offsets
614                                           group-pos))))
615       (while (and table
616                   (> article (aref (car table) 0)))
617         (setq table (cdr table)))
618       (setq entry (car table))
619       (when (and entry
620                  (> article 0)
621                  (< group-pos (aref entry 2))) ; article not out of range below
622         (+ (aref entry 4)
623            group-pos
624            (* (- article (aref entry 1))
625               (aref entry 2))
626            1))
627       )))
628
629
630 (defsubst nnvirtual-reverse-map-sequence (group articles)
631   "Return list of virtual article numbers for all ARTICLES in GROUP.
632 The ARTICLES should be sorted, and can be a compressed sequence.
633 If any of the article numbers has no corresponding virtual article,
634 then it is left out of the result."
635   (when (numberp (cdr-safe articles))
636     (setq articles (list articles)))
637   (let (result a i j new-a)
638     (while (setq a (pop articles))
639       (if (atom a)
640           (setq i a
641                 j a)
642         (setq i (car a)
643               j (cdr a)))
644       (while (<= i j)
645         ;; If this is slow, you can optimize by moving article checking
646         ;; into here.  You don't have to recompute the group-pos,
647         ;; nor scan the table every time.
648         (when (setq new-a (nnvirtual-reverse-map-article group i))
649           (push new-a result))
650         (setq i (1+ i))))
651     (nreverse result)))
652
653
654 (defun nnvirtual-partition-sequence (articles)
655   "Return an association list of component article numbers.
656 These are indexed by elements of nnvirtual-component-groups, based on
657 the sequence ARTICLES of virtual article numbers.  ARTICLES should be
658 sorted, and can be a compressed sequence.  If any of the article
659 numbers has no corresponding component article, then it is left out of
660 the result."
661   (when (numberp (cdr-safe articles))
662     (setq articles (list articles)))
663   (let ((carticles (mapcar 'list nnvirtual-component-groups))
664         a i j article entry)
665     (while (setq a (pop articles))
666       (if (atom a)
667           (setq i a
668                 j a)
669         (setq i (car a)
670               j (cdr a)))
671       (while (<= i j)
672         (when (setq article (nnvirtual-map-article i))
673           (setq entry (assoc (car article) carticles))
674           (setcdr entry (cons (cdr article) (cdr entry))))
675         (setq i (1+ i))))
676     (mapc (lambda (x) (setcdr x (nreverse (cdr x))))
677           carticles)
678     carticles))
679
680
681 (defun nnvirtual-create-mapping ()
682   "Build the tables necessary to map between component (group, article) to virtual article.
683 Generate the set of read messages and marks for the virtual group
684 based on the marks on the component groups."
685   (let ((cnt 0)
686         (tot 0)
687         (M 0)
688         (i 0)
689         actives all-unreads all-marks
690         active min max size unreads marks
691         next-M next-tot
692         reads beg)
693     ;; Ok, we loop over all component groups and collect a lot of
694     ;; information:
695     ;; Into actives we place (g size max), where size is max-min+1.
696     ;; Into all-unreads we put (g unreads).
697     ;; Into all-marks we put (g marks).
698     ;; We also increment cnt and tot here, and compute M (max of sizes).
699     (mapc (lambda (g)
700             (setq active (gnus-activate-group g)
701                   min (car active)
702                   max (cdr active))
703             (when (and active (>= max min) (not (zerop max)))
704               ;; store active information
705               (push (list g (- max min -1) max) actives)
706               ;; collect unread/mark info for later
707               (setq unreads (gnus-list-of-unread-articles g))
708               (setq marks (gnus-info-marks (gnus-get-info g)))
709               (when gnus-use-cache
710                 (push (cons 'cache
711                             (gnus-cache-articles-in-group g))
712                       marks))
713               (push (cons g unreads) all-unreads)
714               (push (cons g marks) all-marks)
715               ;; count groups, total #articles, and max size
716               (setq size (- max min -1))
717               (setq cnt (1+ cnt)
718                     tot (+ tot size)
719                     M (max M size))))
720           nnvirtual-component-groups)
721     
722     ;; Number of articles in the virtual group.
723     (setq nnvirtual-mapping-len tot)
724
725
726     ;; We want the actives list sorted by size, to build the tables.
727     (setq actives (sort actives (lambda (g1 g2) (< (nth 1 g1) (nth 1 g2)))))
728
729     ;; Build the offset table.  Largest sized groups are at the front.
730     (setq nnvirtual-mapping-offsets
731           (vconcat
732            (nreverse
733             (mapcar (lambda (entry)
734                       (cons (nth 0 entry)
735                             (- (nth 2 entry) M)))
736                     actives))))
737
738     ;; Build the mapping table.
739     (setq nnvirtual-mapping-table nil)
740     (setq actives (mapcar (lambda (entry) (nth 1 entry)) actives))
741     (while actives
742       (setq size (car actives))
743       (setq next-M (- M size))
744       (setq next-tot (- tot (* cnt size)))
745       ;; make current row in table
746       (push (vector M next-M cnt tot (- next-tot cnt))
747             nnvirtual-mapping-table)
748       ;; update M and tot
749       (setq M next-M)
750       (setq tot next-tot)
751       ;; subtract the current size from all entries.
752       (setq actives (mapcar (lambda (x) (- x size)) actives))
753       ;; remove anything that went to 0.
754       (while (and actives
755                   (= (car actives) 0))
756         (pop actives)
757         (setq cnt (- cnt 1))))
758
759
760     ;; Now that the mapping tables are generated, we can convert
761     ;; and combine the separate component unreads and marks lists
762     ;; into single lists of virtual article numbers.
763     (setq unreads (apply 'nnvirtual-merge-sorted-lists
764                          (mapcar (lambda (x)
765                                    (nnvirtual-reverse-map-sequence
766                                     (car x) (cdr x)))
767                                  all-unreads)))
768     (setq marks (mapcar
769                  (lambda (type)
770                    (cons (cdr type)
771                          (gnus-compress-sequence
772                           (apply
773                            'nnvirtual-merge-sorted-lists
774                            (mapcar (lambda (x)
775                                      (nnvirtual-reverse-map-sequence
776                                       (car x)
777                                       (cdr (assq (cdr type) (cdr x)))))
778                                    all-marks)))))
779                  gnus-article-mark-lists))
780
781     ;; Remove any empty marks lists, and store.
782     (setq nnvirtual-mapping-marks nil)
783     (dolist (mark marks)
784       (when (cdr mark)
785         (push mark nnvirtual-mapping-marks)))
786
787     ;; We need to convert the unreads to reads.  We compress the
788     ;; sequence as we go, otherwise it could be huge.
789     (while (and (<= (incf i) nnvirtual-mapping-len)
790                 unreads)
791       (if (= i (car unreads))
792           (setq unreads (cdr unreads))
793         ;; try to get a range.
794         (setq beg i)
795         (while (and (<= (incf i) nnvirtual-mapping-len)
796                     (not (= i (car unreads)))))
797         (setq i (- i 1))
798         (if (= i beg)
799             (push i reads)
800           (push (cons beg i) reads))
801         ))
802     (when (<= i nnvirtual-mapping-len)
803       (if (= i nnvirtual-mapping-len)
804           (push i reads)
805         (push (cons i nnvirtual-mapping-len) reads)))
806
807     ;; Store the reads list for later use.
808     (setq nnvirtual-mapping-reads (nreverse reads))
809
810     ;; Throw flag to show we changed the info.
811     (setq nnvirtual-info-installed nil)
812     ))
813
814 (provide 'nnvirtual)
815
816 ;;; nnvirtual.el ends here