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