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