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