Synch to Oort Gnus.
[elisp/gnus.git-] / lisp / gnus-agent.el
1 ;;; gnus-agent.el --- unplugged support for Semi-gnus
2 ;; Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;      Tatsuya Ichikawa <t-ichi@po.shiojiri.ne.jp>
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 (eval-when-compile (require 'cl))
29 (eval-when-compile (require 'gnus-clfns))
30
31 (require 'gnus)
32 (require 'gnus-cache)
33 (require 'nnvirtual)
34 (require 'gnus-sum)
35 (require 'gnus-score)
36 (require 'gnus-srvr)
37 (eval-when-compile
38   (if (featurep 'xemacs)
39       (require 'itimer)
40     (require 'timer))
41   (require 'gnus-group))
42
43 (eval-and-compile
44   (autoload 'gnus-server-update-server "gnus-srvr")
45   (autoload 'gnus-agent-customize-category "gnus-cus")
46 )
47
48 (defcustom gnus-agent-directory (nnheader-concat gnus-directory "agent/")
49   "Where the Gnus agent will store its files."
50   :group 'gnus-agent
51   :type 'directory)
52
53 (defcustom gnus-agent-plugged-hook nil
54   "Hook run when plugging into the network."
55   :group 'gnus-agent
56   :type 'hook)
57
58 (defcustom gnus-agent-unplugged-hook nil
59   "Hook run when unplugging from the network."
60   :group 'gnus-agent
61   :type 'hook)
62
63 (defcustom gnus-agent-handle-level gnus-level-subscribed
64   "Groups on levels higher than this variable will be ignored by the Agent."
65   :group 'gnus-agent
66   :type 'integer)
67
68 (defcustom gnus-agent-expire-days 7
69   "Read articles older than this will be expired.
70 This can also be a list of regexp/day pairs.  The regexps will be
71 matched against group names."
72   :group 'gnus-agent
73   :type '(choice (number :tag "days")
74                  (sexp :tag "List" nil)))
75
76 (defcustom gnus-agent-expire-all nil
77   "If non-nil, also expire unread, ticked and dormant articles.
78 If nil, only read articles will be expired."
79   :group 'gnus-agent
80   :type 'boolean)
81
82 (defcustom gnus-agent-group-mode-hook nil
83   "Hook run in Agent group minor modes."
84   :group 'gnus-agent
85   :type 'hook)
86
87 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
88 (when (featurep 'xemacs)
89   (add-hook 'gnus-agent-group-mode-hook 'gnus-xmas-agent-group-menu-add))
90
91 (defcustom gnus-agent-summary-mode-hook nil
92   "Hook run in Agent summary minor modes."
93   :group 'gnus-agent
94   :type 'hook)
95
96 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
97 (when (featurep 'xemacs)
98   (add-hook 'gnus-agent-summary-mode-hook 'gnus-xmas-agent-summary-menu-add))
99
100 (defcustom gnus-agent-server-mode-hook nil
101   "Hook run in Agent summary minor modes."
102   :group 'gnus-agent
103   :type 'hook)
104
105 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
106 (when (featurep 'xemacs)
107   (add-hook 'gnus-agent-server-mode-hook 'gnus-xmas-agent-server-menu-add))
108
109 (defcustom gnus-agent-confirmation-function 'y-or-n-p
110   "Function to confirm when error happens."
111   :version "21.1"
112   :group 'gnus-agent
113   :type 'function)
114
115 (defcustom gnus-agent-large-newsgroup nil
116   "*The number of articles which indicates a large newsgroup.
117 If the number of unread articles exceeds it, The number of articles to be
118 fetched will be limited to it. If not a positive integer, never consider it."
119   :group 'gnus-agent
120   :type '(choice (const nil)
121                  (integer :tag "Number")))
122
123 (defcustom gnus-agent-synchronize-flags 'ask
124   "Indicate if flags are synchronized when you plug in.
125 If this is `ask' the hook will query the user."
126   :version "21.1"
127   :type '(choice (const :tag "Always" t)
128                  (const :tag "Never" nil)
129                  (const :tag "Ask" ask))
130   :group 'gnus-agent)
131
132 (defcustom gnus-agent-go-online 'ask
133   "Indicate if offline servers go online when you plug in.
134 If this is `ask' the hook will query the user."
135   :version "21.1"
136   :type '(choice (const :tag "Always" t)
137                  (const :tag "Never" nil)
138                  (const :tag "Ask" ask))
139   :group 'gnus-agent)
140
141 (defcustom gnus-agent-mark-unread-after-downloaded t
142   "Indicate whether to mark articles unread after downloaded."
143   :version "21.1"
144   :type 'boolean
145   :group 'gnus-agent)
146
147 (defcustom gnus-agent-download-marks '(download)
148   "Marks for downloading."
149   :version "21.1"
150   :type '(repeat (symbol :tag "Mark"))
151   :group 'gnus-agent)
152
153 (defcustom gnus-agent-consider-all-articles nil
154   "If non-nil, consider also the read articles for downloading."
155   :version "21.4"
156   :type 'boolean
157   :group 'gnus-agent)
158
159 (defcustom gnus-agent-max-fetch-size 10000000 ;; 10 Mb
160   "Chunk size for `gnus-agent-fetch-session'.
161 The function will split its article fetches into chunks smaller than
162 this limit."
163   :group 'gnus-agent
164   :type 'integer)
165
166 (defcustom gnus-agent-enable-expiration 'ENABLE
167   "The default expiration state for each group.
168 When set to ENABLE, the default, gnus-agent-expire will expire old
169 contents from a group's local storage.  This value may be overridden
170 to disable expiration in specific categories, topics, and groups.  Of
171 course, you could change gnus-agent-enable-expiration to nil then
172 enable expiration per categories, topics, and groups."
173   :group 'gnus-agent
174   :type '(radio (const :format "Enable " ENABLE)
175                 (const :format "Disable " DISABLE)))
176
177 ;;; Internal variables
178
179 (defvar gnus-agent-history-buffers nil)
180 (defvar gnus-agent-buffer-alist nil)
181 (defvar gnus-agent-article-alist nil
182 "An assoc list identifying the articles whose headers have been fetched.  
183 If successfully fetched, these headers will be stored in the group's overview
184 file.  The key of each assoc pair is the article ID, the value of each assoc
185 pair is a flag indicating whether the identified article has been downloaded
186 \(gnus-agent-fetch-articles sets the value to the day of the download).
187 NOTES:
188 1) The last element of this list can not be expired as some 
189    routines (for example, get-agent-fetch-headers) use the last
190    value to track which articles have had their headers retrieved.
191 2) The gnus-agent-regenerate may destructively modify the value.
192 ")
193 (defvar gnus-agent-group-alist nil)
194 (defvar gnus-category-alist nil)
195 (defvar gnus-agent-current-history nil)
196 (defvar gnus-agent-overview-buffer nil)
197 (defvar gnus-category-predicate-cache nil)
198 (defvar gnus-category-group-cache nil)
199 (defvar gnus-agent-spam-hashtb nil)
200 (defvar gnus-agent-file-name nil)
201 (defvar gnus-agent-send-mail-function nil)
202 (defvar gnus-agent-file-coding-system 'raw-text)
203 (defvar gnus-agent-file-loading-cache nil)
204 (defvar gnus-agent-file-header-cache nil)
205
206 (defvar gnus-agent-auto-agentize-methods '(nntp nnimap)
207   "Initially, all servers from these methods are agentized.
208 The user may remove or add servers using the Server buffer.  See Info
209 node `(gnus)Server Buffer'.")
210
211 ;; Dynamic variables
212 (defvar gnus-headers)
213 (defvar gnus-score)
214
215 ;;;
216 ;;; Setup
217 ;;;
218
219 (defun gnus-open-agent ()
220   (setq gnus-agent t)
221   (gnus-agent-read-servers)
222   (gnus-category-read)
223   (gnus-agent-create-buffer)
224   (add-hook 'gnus-group-mode-hook 'gnus-agent-mode)
225   (add-hook 'gnus-summary-mode-hook 'gnus-agent-mode)
226   (add-hook 'gnus-server-mode-hook 'gnus-agent-mode))
227
228 (defun gnus-agent-create-buffer ()
229   (if (gnus-buffer-live-p gnus-agent-overview-buffer)
230       t
231     (setq gnus-agent-overview-buffer
232           (gnus-get-buffer-create " *Gnus agent overview*"))
233     (with-current-buffer gnus-agent-overview-buffer
234       (set-buffer-multibyte t))
235     nil))
236
237 (gnus-add-shutdown 'gnus-close-agent 'gnus)
238
239 (defun gnus-close-agent ()
240   (setq gnus-category-predicate-cache nil
241         gnus-category-group-cache nil
242         gnus-agent-spam-hashtb nil)
243   (gnus-kill-buffer gnus-agent-overview-buffer))
244
245 ;;;
246 ;;; Utility functions
247 ;;;
248
249 (defun gnus-agent-read-file (file)
250   "Load FILE and do a `read' there."
251   (with-temp-buffer
252     (ignore-errors
253       (nnheader-insert-file-contents file)
254       (goto-char (point-min))
255       (read (current-buffer)))))
256
257 (defsubst gnus-agent-method ()
258   (concat (symbol-name (car gnus-command-method)) "/"
259           (if (equal (cadr gnus-command-method) "")
260               "unnamed"
261             (cadr gnus-command-method))))
262
263 (defsubst gnus-agent-directory ()
264   "The name of the Gnus agent directory."
265   (nnheader-concat gnus-agent-directory
266                    (nnheader-translate-file-chars (gnus-agent-method)) "/"))
267
268 (defun gnus-agent-lib-file (file)
269   "The full name of the Gnus agent library FILE."
270   (expand-file-name file
271                     (file-name-as-directory
272                      (expand-file-name "agent.lib" (gnus-agent-directory)))))
273
274 (defun gnus-agent-cat-set-property (category property value)
275   (if value
276       (setcdr (or (assq property category)
277               (let ((cell (cons property nil)))
278                     (setcdr category (cons cell (cdr category)))
279                     cell)) value)
280     (let ((category category))
281       (while (cond ((eq property (caadr category))
282                     (setcdr category (cddr category))
283                     nil)
284                    (t
285                     (setq category (cdr category)))))))
286   category)
287
288 (defmacro gnus-agent-cat-defaccessor (name prop-name)
289   "Define accessor and setter methods for manipulating a list of the form
290 (NAME (PROPERTY1 VALUE1) ... (PROPERTY_N VALUE_N)).
291 Given the call (gnus-agent-cat-defaccessor func PROPERTY1), the list may be
292 manipulated as follows:
293   (func LIST): Returns VALUE1
294   (setf (func LIST) NEW_VALUE1): Replaces VALUE1 with NEW_VALUE1."
295   `(progn (defmacro ,name (category)
296             (list (quote cdr) (list (quote assq)
297                                     (quote (quote ,prop-name)) category)))
298
299           (define-setf-method ,name (category)
300             (let* ((--category--temp-- (gensym "--category--"))
301                    (--value--temp-- (gensym "--value--")))
302               (list (list --category--temp--) ; temporary-variables
303                     (list category)     ; value-forms
304                     (list --value--temp--) ; store-variables
305                     (let* ((category --category--temp--) ; store-form
306                            (value --value--temp--))
307                       (list (quote gnus-agent-cat-set-property)
308                             category
309                             (quote (quote ,prop-name))
310                             value))
311                     (list (quote ,name) --category--temp--) ; access-form
312                     )))))
313
314 (defmacro gnus-agent-cat-name (category)
315   `(car ,category))
316
317 (gnus-agent-cat-defaccessor
318  gnus-agent-cat-days-until-old    agent-days-until-old)
319 (gnus-agent-cat-defaccessor
320  gnus-agent-cat-enable-expiration agent-enable-expiration)
321 (gnus-agent-cat-defaccessor
322  gnus-agent-cat-groups            agent-groups)
323 (gnus-agent-cat-defaccessor
324  gnus-agent-cat-high-score        agent-high-score)
325 (gnus-agent-cat-defaccessor
326  gnus-agent-cat-length-when-long  agent-length-when-long)
327 (gnus-agent-cat-defaccessor
328  gnus-agent-cat-length-when-short agent-length-when-short)
329 (gnus-agent-cat-defaccessor
330  gnus-agent-cat-low-score         agent-low-score)
331 (gnus-agent-cat-defaccessor
332  gnus-agent-cat-predicate         agent-predicate)
333 (gnus-agent-cat-defaccessor
334  gnus-agent-cat-score-file        agent-score-file)
335
336 (defsetf gnus-agent-cat-groups (category) (groups)
337   (list 'gnus-agent-set-cat-groups category groups))
338
339 (defun gnus-agent-set-cat-groups (category groups)
340   (unless (eq groups 'ignore)
341     (let ((new-g groups)
342           (old-g (gnus-agent-cat-groups category)))
343       (cond ((eq new-g old-g)
344              ;; gnus-agent-add-group is fiddling with the group
345              ;; list. Still, Im done.
346              nil
347              )
348             ((eq new-g (cdr old-g))
349              ;; gnus-agent-add-group is fiddling with the group list
350              (setcdr (or (assq 'agent-groups category)
351                          (let ((cell (cons 'agent-groups nil)))
352                            (setcdr category (cons cell (cdr category)))
353                            cell)) new-g))
354             (t
355              (let ((groups groups))
356                (while groups
357                  (let* ((group        (pop groups))
358                         (old-category (gnus-group-category group)))
359                    (if (eq category old-category)
360                        nil
361                      (setf (gnus-agent-cat-groups old-category)
362                            (delete group (gnus-agent-cat-groups
363                                           old-category))))))
364                ;; Purge cache as preceeding loop invalidated it.
365                (setq gnus-category-group-cache nil))
366
367              (setcdr (or (assq 'agent-groups category)
368                          (let ((cell (cons 'agent-groups nil)))
369                            (setcdr category (cons cell (cdr category)))
370                            cell)) groups))))))
371
372 (defsubst gnus-agent-cat-make (name)
373   (list name '(agent-predicate . false)))
374
375 ;;; Fetching setup functions.
376
377 (defun gnus-agent-start-fetch ()
378   "Initialize data structures for efficient fetching."
379   (gnus-agent-create-buffer))
380
381 (defun gnus-agent-stop-fetch ()
382   "Save all data structures and clean up."
383   (setq gnus-agent-spam-hashtb nil)
384   (save-excursion
385     (set-buffer nntp-server-buffer)
386     (widen)))
387
388 (defmacro gnus-agent-with-fetch (&rest forms)
389   "Do FORMS safely."
390   `(unwind-protect
391        (let ((gnus-agent-fetching t))
392          (gnus-agent-start-fetch)
393          ,@forms)
394      (gnus-agent-stop-fetch)))
395
396 (put 'gnus-agent-with-fetch 'lisp-indent-function 0)
397 (put 'gnus-agent-with-fetch 'edebug-form-spec '(body))
398
399 (defmacro gnus-agent-append-to-list (tail value)
400   `(setq ,tail (setcdr ,tail (cons ,value nil))))
401
402 ;;;
403 ;;; Mode infestation
404 ;;;
405
406 (defvar gnus-agent-mode-hook nil
407   "Hook run when installing agent mode.")
408
409 (defvar gnus-agent-mode nil)
410 (defvar gnus-agent-mode-status '(gnus-agent-mode " Plugged"))
411
412 (defun gnus-agent-mode ()
413   "Minor mode for providing a agent support in Gnus buffers."
414   (let* ((buffer (progn (string-match "^gnus-\\(.*\\)-mode$"
415                                       (symbol-name major-mode))
416                         (match-string 1 (symbol-name major-mode))))
417          (mode (intern (format "gnus-agent-%s-mode" buffer))))
418     (set (make-local-variable 'gnus-agent-mode) t)
419     (set mode nil)
420     (set (make-local-variable mode) t)
421     ;; Set up the menu.
422     (when (gnus-visual-p 'agent-menu 'menu)
423       (funcall (intern (format "gnus-agent-%s-make-menu-bar" buffer))))
424     (unless (assq 'gnus-agent-mode minor-mode-alist)
425       (push gnus-agent-mode-status minor-mode-alist))
426     (unless (assq mode minor-mode-map-alist)
427       (push (cons mode (symbol-value (intern (format "gnus-agent-%s-mode-map"
428                                                      buffer))))
429             minor-mode-map-alist))
430     (when (eq major-mode 'gnus-group-mode)
431       (gnus-agent-toggle-plugged gnus-plugged))
432     (gnus-run-hooks 'gnus-agent-mode-hook
433                     (intern (format "gnus-agent-%s-mode-hook" buffer)))))
434
435 (defvar gnus-agent-group-mode-map (make-sparse-keymap))
436 (gnus-define-keys gnus-agent-group-mode-map
437   "Ju" gnus-agent-fetch-groups
438   "Jc" gnus-enter-category-buffer
439   "Jj" gnus-agent-toggle-plugged
440   "Js" gnus-agent-fetch-session
441   "JY" gnus-agent-synchronize-flags
442   "JS" gnus-group-send-queue
443   "Ja" gnus-agent-add-group
444   "Jr" gnus-agent-remove-group
445   "Jo" gnus-agent-toggle-group-plugged)
446
447 (defun gnus-agent-group-make-menu-bar ()
448   (unless (boundp 'gnus-agent-group-menu)
449     (easy-menu-define
450      gnus-agent-group-menu gnus-agent-group-mode-map ""
451      '("Agent"
452        ["Toggle plugged" gnus-agent-toggle-plugged t]
453        ["Toggle group plugged" gnus-agent-toggle-group-plugged t]
454        ["List categories" gnus-enter-category-buffer t]
455        ["Add (current) group to category" gnus-agent-add-group t]
456        ["Remove (current) group from category" gnus-agent-remove-group t]
457        ["Send queue" gnus-group-send-queue gnus-plugged]
458        ("Fetch"
459         ["All" gnus-agent-fetch-session gnus-plugged]
460         ["Group" gnus-agent-fetch-group gnus-plugged])
461        ["Synchronize flags" gnus-agent-synchronize-flags t]
462        ))))
463
464 (defvar gnus-agent-summary-mode-map (make-sparse-keymap))
465 (gnus-define-keys gnus-agent-summary-mode-map
466   "Jj" gnus-agent-toggle-plugged
467   "Ju" gnus-agent-summary-fetch-group
468   "JS" gnus-agent-fetch-group
469   "Js" gnus-agent-summary-fetch-series
470   "J#" gnus-agent-mark-article
471   "J\M-#" gnus-agent-unmark-article
472   "@" gnus-agent-toggle-mark
473   "Jc" gnus-agent-catchup)
474
475 (defun gnus-agent-summary-make-menu-bar ()
476   (unless (boundp 'gnus-agent-summary-menu)
477     (easy-menu-define
478      gnus-agent-summary-menu gnus-agent-summary-mode-map ""
479      '("Agent"
480        ["Toggle plugged" gnus-agent-toggle-plugged t]
481        ["Mark as downloadable" gnus-agent-mark-article t]
482        ["Unmark as downloadable" gnus-agent-unmark-article t]
483        ["Toggle mark" gnus-agent-toggle-mark t]
484        ["Fetch downloadable" gnus-agent-summary-fetch-group t]
485        ["Catchup undownloaded" gnus-agent-catchup t]))))
486
487 (defvar gnus-agent-server-mode-map (make-sparse-keymap))
488 (gnus-define-keys gnus-agent-server-mode-map
489   "Jj" gnus-agent-toggle-plugged
490   "Ja" gnus-agent-add-server
491   "Jr" gnus-agent-remove-server)
492
493 (defun gnus-agent-server-make-menu-bar ()
494   (unless (boundp 'gnus-agent-server-menu)
495     (easy-menu-define
496      gnus-agent-server-menu gnus-agent-server-mode-map ""
497      '("Agent"
498        ["Toggle plugged" gnus-agent-toggle-plugged t]
499        ["Add" gnus-agent-add-server t]
500        ["Remove" gnus-agent-remove-server t]))))
501
502 (defun gnus-agent-make-mode-line-string (string mouse-button mouse-func)
503   (if (and (fboundp 'propertize)
504            (fboundp 'make-mode-line-mouse-map))
505       (propertize string 'local-map
506                   (make-mode-line-mouse-map mouse-button mouse-func))
507     string))
508
509 (defun gnus-agent-toggle-plugged (set-to)
510   "Toggle whether Gnus is unplugged or not."
511   (interactive (list (not gnus-plugged)))
512   (cond ((eq set-to gnus-plugged)
513          nil)
514         (set-to
515          (setq gnus-plugged set-to)
516          (gnus-run-hooks 'gnus-agent-plugged-hook)
517          (setcar (cdr gnus-agent-mode-status)
518                  (gnus-agent-make-mode-line-string " Plugged"
519                                                    'mouse-2
520                                                    'gnus-agent-toggle-plugged))
521          (gnus-agent-go-online gnus-agent-go-online)
522          (gnus-agent-possibly-synchronize-flags))
523         (t
524          (gnus-agent-close-connections)
525          (setq gnus-plugged set-to)
526          (gnus-run-hooks 'gnus-agent-unplugged-hook)
527          (setcar (cdr gnus-agent-mode-status)
528                  (gnus-agent-make-mode-line-string " Unplugged"
529                                                    'mouse-2
530                                                    'gnus-agent-toggle-plugged))))
531   (force-mode-line-update)
532   (set-buffer-modified-p t))
533
534 (defmacro gnus-agent-while-plugged (&rest body)
535   `(let ((original-gnus-plugged gnus-plugged))
536     (unwind-protect
537         (progn (gnus-agent-toggle-plugged t)
538                ,@body)
539       (gnus-agent-toggle-plugged original-gnus-plugged))))
540
541 (put 'gnus-agent-while-plugged 'lisp-indent-function 0)
542 (put 'gnus-agent-while-plugged 'edebug-form-spec '(body))
543
544 (defun gnus-agent-close-connections ()
545   "Close all methods covered by the Gnus agent."
546   (let ((methods gnus-agent-covered-methods))
547     (while methods
548       (gnus-close-server (pop methods)))))
549
550 ;;;###autoload
551 (defun gnus-unplugged ()
552   "Start Gnus unplugged."
553   (interactive)
554   (setq gnus-plugged nil)
555   (gnus))
556
557 ;;;###autoload
558 (defun gnus-plugged ()
559   "Start Gnus plugged."
560   (interactive)
561   (setq gnus-plugged t)
562   (gnus))
563
564 ;;;###autoload
565 (defun gnus-slave-unplugged (&optional arg)
566   "Read news as a slave unplugged."
567   (interactive "P")
568   (setq gnus-plugged nil)
569   (gnus arg nil 'slave))
570
571 ;;;###autoload
572 (defun gnus-agentize ()
573   "Allow Gnus to be an offline newsreader.
574 The normal usage of this command is to put the following as the
575 last form in your `.gnus.el' file:
576
577 \(gnus-agentize)
578
579 This will modify the `gnus-setup-news-hook', and
580 `message-send-mail-real-function' variables, and install the Gnus agent
581 minor mode in all Gnus buffers."
582   (interactive)
583   (gnus-open-agent)
584   (add-hook 'gnus-setup-news-hook 'gnus-agent-queue-setup)
585   (unless gnus-agent-send-mail-function
586     (setq gnus-agent-send-mail-function
587           (or message-send-mail-real-function
588                                          message-send-mail-function)
589           message-send-mail-real-function 'gnus-agent-send-mail))
590
591   (unless gnus-agent-covered-methods
592     (mapcar
593      (lambda (server)
594        (if (memq (car (gnus-server-to-method server)) 
595                  gnus-agent-auto-agentize-methods)
596            (setq gnus-agent-covered-methods 
597                  (cons (gnus-server-to-method server)
598                        gnus-agent-covered-methods ))))
599      (append (list gnus-select-method) gnus-secondary-select-methods))))
600
601 (defun gnus-agent-queue-setup ()
602   "Make sure the queue group exists."
603   (unless (gnus-gethash "nndraft:queue" gnus-newsrc-hashtb)
604     (gnus-request-create-group "queue" '(nndraft ""))
605     (let ((gnus-level-default-subscribed 1))
606       (gnus-subscribe-group "nndraft:queue" nil '(nndraft "")))
607     (gnus-group-set-parameter
608      "nndraft:queue" 'gnus-dummy '((gnus-draft-mode)))))
609
610 (defun gnus-agent-send-mail ()
611   (if gnus-plugged
612       (funcall gnus-agent-send-mail-function)
613     (goto-char (point-min))
614     (re-search-forward
615      (concat "^" (regexp-quote mail-header-separator) "\n"))
616     (replace-match "\n")
617     (gnus-agent-insert-meta-information 'mail)
618     (gnus-request-accept-article "nndraft:queue" nil t t)))
619
620 (defun gnus-agent-insert-meta-information (type &optional method)
621   "Insert meta-information into the message that says how it's to be posted.
622 TYPE can be either `mail' or `news'.  If the latter, then METHOD can
623 be a select method."
624   (save-excursion
625     (message-remove-header gnus-agent-meta-information-header)
626     (goto-char (point-min))
627     (insert gnus-agent-meta-information-header ": "
628             (symbol-name type) " " (format "%S" method)
629             "\n")
630     (forward-char -1)
631     (while (search-backward "\n" nil t)
632       (replace-match "\\n" t t))))
633
634 (defun gnus-agent-restore-gcc ()
635   "Restore GCC field from saved header."
636   (save-excursion
637     (goto-char (point-min))
638     (while (re-search-forward (concat gnus-agent-gcc-header ":") nil t)
639       (replace-match "Gcc:" 'fixedcase))))
640
641 (defun gnus-agent-any-covered-gcc ()
642   (save-restriction
643     (message-narrow-to-headers)
644     (let* ((gcc (mail-fetch-field "gcc" nil t))
645            (methods (and gcc
646                          (mapcar 'gnus-inews-group-method
647                                  (message-unquote-tokens
648                                   (message-tokenize-header
649                                    gcc " ,")))))
650            covered)
651       (while (and (not covered) methods)
652         (setq covered (gnus-agent-method-p (car methods))
653               methods (cdr methods)))
654       covered)))
655
656 ;;;###autoload
657 (defun gnus-agent-possibly-save-gcc ()
658   "Save GCC if Gnus is unplugged."
659   (when (and (not gnus-plugged) (gnus-agent-any-covered-gcc))
660     (save-excursion
661       (goto-char (point-min))
662       (let ((case-fold-search t))
663         (while (re-search-forward "^gcc:" nil t)
664           (replace-match (concat gnus-agent-gcc-header ":") 'fixedcase))))))
665
666 (defun gnus-agent-possibly-do-gcc ()
667   "Do GCC if Gnus is plugged."
668   (when (or gnus-plugged (not (gnus-agent-any-covered-gcc)))
669     (gnus-inews-do-gcc)))
670
671 ;;;
672 ;;; Group mode commands
673 ;;;
674
675 (defun gnus-agent-fetch-groups (n)
676   "Put all new articles in the current groups into the Agent."
677   (interactive "P")
678   (unless gnus-plugged
679     (error "Groups can't be fetched when Gnus is unplugged"))
680   (gnus-group-iterate n 'gnus-agent-fetch-group))
681
682 (defun gnus-agent-fetch-group (&optional group)
683   "Put all new articles in GROUP into the Agent."
684   (interactive (list (gnus-group-group-name)))
685   (setq group (or group gnus-newsgroup-name))
686   (unless group
687     (error "No group on the current line"))
688
689   (gnus-agent-while-plugged
690     (let ((gnus-command-method (gnus-find-method-for-group group)))
691       (gnus-agent-with-fetch
692         (gnus-agent-fetch-group-1 group gnus-command-method)
693         (gnus-message 5 "Fetching %s...done" group)))))
694
695 (defun gnus-agent-add-group (category arg)
696   "Add the current group to an agent category."
697   (interactive
698    (list
699     (intern
700      (completing-read
701       "Add to category: "
702       (mapcar (lambda (cat) (list (symbol-name (car cat))))
703               gnus-category-alist)
704       nil t))
705     current-prefix-arg))
706   (let ((cat (assq category gnus-category-alist))
707         c groups)
708     (gnus-group-iterate arg
709       (lambda (group)
710         (when (gnus-agent-cat-groups (setq c (gnus-group-category group)))
711           (setf (gnus-agent-cat-groups c)
712                 (delete group (gnus-agent-cat-groups c))))
713         (push group groups)))
714     (setf (gnus-agent-cat-groups cat)
715           (nconc (gnus-agent-cat-groups cat) groups))
716     (gnus-category-write)))
717
718 (defun gnus-agent-remove-group (arg)
719   "Remove the current group from its agent category, if any."
720   (interactive "P")
721   (let (c)
722     (gnus-group-iterate arg
723       (lambda (group)
724         (when (gnus-agent-cat-groups (setq c (gnus-group-category group)))
725           (setf (gnus-agent-cat-groups c)
726                 (delete group (gnus-agent-cat-groups c))))))
727     (gnus-category-write)))
728
729 (defun gnus-agent-synchronize-flags ()
730   "Synchronize unplugged flags with servers."
731   (interactive)
732   (save-excursion
733     (dolist (gnus-command-method gnus-agent-covered-methods)
734       (when (file-exists-p (gnus-agent-lib-file "flags"))
735         (gnus-agent-synchronize-flags-server gnus-command-method)))))
736
737 (defun gnus-agent-possibly-synchronize-flags ()
738   "Synchronize flags according to `gnus-agent-synchronize-flags'."
739   (interactive)
740   (save-excursion
741     (dolist (gnus-command-method gnus-agent-covered-methods)
742       (when (file-exists-p (gnus-agent-lib-file "flags"))
743         (gnus-agent-possibly-synchronize-flags-server gnus-command-method)))))
744
745 (defun gnus-agent-synchronize-flags-server (method)
746   "Synchronize flags set when unplugged for server."
747   (let ((gnus-command-method method))
748     (when (file-exists-p (gnus-agent-lib-file "flags"))
749       (set-buffer (get-buffer-create " *Gnus Agent flag synchronize*"))
750       (erase-buffer)
751       (nnheader-insert-file-contents (gnus-agent-lib-file "flags"))
752       (if (null (gnus-check-server gnus-command-method))
753           (gnus-message 1 "Couldn't open server %s" (nth 1 gnus-command-method))
754         (while (not (eobp))
755           (if (null (eval (read (current-buffer))))
756               (progn (forward-line)
757                      (kill-line -1))
758             (write-file (gnus-agent-lib-file "flags"))
759             (error "Couldn't set flags from file %s"
760                    (gnus-agent-lib-file "flags"))))
761         (delete-file (gnus-agent-lib-file "flags")))
762       (kill-buffer nil))))
763
764 (defun gnus-agent-possibly-synchronize-flags-server (method)
765   "Synchronize flags for server according to `gnus-agent-synchronize-flags'."
766   (when (or (and gnus-agent-synchronize-flags
767                  (not (eq gnus-agent-synchronize-flags 'ask)))
768             (and (eq gnus-agent-synchronize-flags 'ask)
769                  (gnus-y-or-n-p (format "Synchronize flags on server `%s'? "
770                                         (cadr method)))))
771     (gnus-agent-synchronize-flags-server method)))
772
773 ;;;
774 ;;; Server mode commands
775 ;;;
776
777 (defun gnus-agent-add-server (server)
778   "Enroll SERVER in the agent program."
779   (interactive (list (gnus-server-server-name)))
780   (unless server
781     (error "No server on the current line"))
782   (let ((method (gnus-server-get-method nil (gnus-server-server-name))))
783     (when (gnus-agent-method-p method)
784       (error "Server already in the agent program"))
785     (push method gnus-agent-covered-methods)
786     (gnus-server-update-server server)
787     (gnus-agent-write-servers)
788     (gnus-message 1 "Entered %s into the Agent" server)))
789
790 (defun gnus-agent-remove-server (server)
791   "Remove SERVER from the agent program."
792   (interactive (list (gnus-server-server-name)))
793   (unless server
794     (error "No server on the current line"))
795   (let ((method (gnus-server-get-method nil (gnus-server-server-name))))
796     (unless (gnus-agent-method-p method)
797       (error "Server not in the agent program"))
798     (setq gnus-agent-covered-methods
799           (delete method gnus-agent-covered-methods))
800     (gnus-server-update-server server)
801     (gnus-agent-write-servers)
802     (gnus-message 1 "Removed %s from the agent" server)))
803
804 (defun gnus-agent-read-servers ()
805   "Read the alist of covered servers."
806   (mapcar (lambda (m)
807             (let ((method (gnus-server-get-method
808                            nil
809                            (or m "native"))))
810               (if method
811                   (unless (member method gnus-agent-covered-methods)
812                     (push method gnus-agent-covered-methods))
813                 (gnus-message 1 "Ignoring disappeared server `%s'" m)
814                 (sit-for 1))))
815           (gnus-agent-read-file
816            (nnheader-concat gnus-agent-directory "lib/servers"))))
817
818 (defun gnus-agent-write-servers ()
819   "Write the alist of covered servers."
820   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
821   (let ((coding-system-for-write nnheader-file-coding-system)
822         (output-coding-system nnheader-file-coding-system)
823         (file-name-coding-system nnmail-pathname-coding-system)
824         (pathname-coding-system nnmail-pathname-coding-system))
825     (with-temp-file (nnheader-concat gnus-agent-directory "lib/servers")
826       (prin1 (mapcar 'gnus-method-simplify gnus-agent-covered-methods)
827              (current-buffer)))))
828
829 ;;;
830 ;;; Summary commands
831 ;;;
832
833 (defun gnus-agent-mark-article (n &optional unmark)
834   "Mark the next N articles as downloadable.
835 If N is negative, mark backward instead.  If UNMARK is non-nil, remove
836 the mark instead.  The difference between N and the actual number of
837 articles marked is returned."
838   (interactive "p")
839   (let ((backward (< n 0))
840         (n (abs n)))
841     (while (and
842             (> n 0)
843             (progn
844               (gnus-summary-set-agent-mark
845                (gnus-summary-article-number) unmark)
846               (zerop (gnus-summary-next-subject (if backward -1 1) nil t))))
847       (setq n (1- n)))
848     (when (/= 0 n)
849       (gnus-message 7 "No more articles"))
850     (gnus-summary-recenter)
851     (gnus-summary-position-point)
852     n))
853
854 (defun gnus-agent-unmark-article (n)
855   "Remove the downloadable mark from the next N articles.
856 If N is negative, unmark backward instead.  The difference between N and
857 the actual number of articles unmarked is returned."
858   (interactive "p")
859   (gnus-agent-mark-article n t))
860
861 (defun gnus-agent-toggle-mark (n)
862   "Toggle the downloadable mark from the next N articles.
863 If N is negative, toggle backward instead.  The difference between N and
864 the actual number of articles toggled is returned."
865   (interactive "p")
866   (gnus-agent-mark-article n 'toggle))
867
868 (defun gnus-summary-set-agent-mark (article &optional unmark)
869   "Mark ARTICLE as downloadable.  If UNMARK is nil, article is marked.
870 When UNMARK is t, the article is unmarked.  For any other value, the
871 article's mark is toggled."
872   (let ((unmark (cond ((eq nil unmark)
873                        nil)
874                       ((eq t unmark)
875                        t)
876                       (t
877                        (memq article gnus-newsgroup-downloadable)))))
878     (when (gnus-summary-goto-subject article nil t)
879       (gnus-summary-update-mark
880        (if unmark
881            (progn
882              (setq gnus-newsgroup-downloadable
883                    (delq article gnus-newsgroup-downloadable))
884              (gnus-article-mark article))
885          (progn
886            (setq gnus-newsgroup-downloadable
887                  (gnus-add-to-sorted-list gnus-newsgroup-downloadable article))
888            gnus-downloadable-mark)
889          )
890        'unread))))
891
892 (defun gnus-agent-get-undownloaded-list ()
893   "Construct list of articles that have not been downloaded."
894   (let ((gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name)))
895     (when (set (make-local-variable 'gnus-newsgroup-agentized)
896                (gnus-agent-method-p gnus-command-method))
897       (let* ((alist (gnus-agent-load-alist gnus-newsgroup-name))
898              (headers (sort (mapcar (lambda (h)
899                                       (mail-header-number h))
900                                     gnus-newsgroup-headers) '<))
901              (undownloaded (list nil))
902              (tail-undownloaded undownloaded)
903              (unfetched (list nil))
904              (tail-unfetched unfetched))
905         (while (and alist headers)
906           (let ((a (caar alist))
907                 (h (car headers)))
908             (cond ((< a h)
909                    ;; Ignore IDs in the alist that are not being
910                    ;; displayed in the summary.
911                    (pop alist))
912                   ((> a h)
913                    ;; Headers that are not in the alist should be
914                    ;; fictious (see nnagent-retrieve-headers); they
915                    ;; imply that this article isn't in the agent.
916                    (gnus-agent-append-to-list tail-undownloaded h)
917                    (gnus-agent-append-to-list tail-unfetched    h)
918                    (pop headers)) 
919                   ((cdar alist)
920                    (pop alist)
921                    (pop headers)
922                    nil                  ; ignore already downloaded
923                    )
924                   (t
925                    (pop alist)
926                    (pop headers)
927                    (gnus-agent-append-to-list tail-undownloaded a)))))
928
929         (while headers
930           (let ((num (pop headers)))
931             (gnus-agent-append-to-list tail-undownloaded num)
932             (gnus-agent-append-to-list tail-unfetched    num)))
933
934         (setq gnus-newsgroup-undownloaded (cdr undownloaded)
935               gnus-newsgroup-unfetched    (cdr unfetched))))))
936
937 (defun gnus-agent-catchup ()
938   "Mark as read all unhandled articles.
939 An article is unhandled if it is neither cached, nor downloaded, nor
940 downloadable."
941   (interactive)
942   (save-excursion
943     (let ((articles gnus-newsgroup-undownloaded))
944       (when (or gnus-newsgroup-downloadable
945                 gnus-newsgroup-cached)
946         (setq articles (gnus-sorted-ndifference
947                         (gnus-sorted-ndifference
948                          (gnus-copy-sequence articles)
949                          gnus-newsgroup-downloadable)
950                         gnus-newsgroup-cached)))
951
952       (while articles
953         (gnus-summary-mark-article
954          (pop articles) gnus-catchup-mark)))
955     (gnus-summary-position-point)))
956
957 (defun gnus-agent-summary-fetch-series ()
958   (interactive)
959   (when gnus-newsgroup-processable
960     (setq gnus-newsgroup-downloadable
961           (let* ((dl gnus-newsgroup-downloadable)
962                  (gnus-newsgroup-downloadable
963                   (sort (gnus-copy-sequence gnus-newsgroup-processable) '<))
964                  (fetched-articles (gnus-agent-summary-fetch-group)))
965             ;; The preceeding call to (gnus-agent-summary-fetch-group)
966             ;; updated gnus-newsgroup-downloadable to remove each
967             ;; article successfully fetched.
968
969             ;; For each article that I processed, remove its
970             ;; processable mark IF the article is no longer
971             ;; downloadable (i.e. it's already downloaded)
972             (dolist (article gnus-newsgroup-processable)
973               (unless (memq article gnus-newsgroup-downloadable)
974                 (gnus-summary-remove-process-mark article)))
975             (gnus-sorted-ndifference dl fetched-articles)))))
976
977 (defun gnus-agent-summary-fetch-group (&optional all)
978   "Fetch the downloadable articles in the group.
979 Optional arg ALL, if non-nil, means to fetch all articles."
980   (interactive "P")
981   (let ((articles
982          (if all gnus-newsgroup-articles
983            gnus-newsgroup-downloadable))
984         (gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name))
985         fetched-articles)
986     (gnus-agent-while-plugged
987       (unless articles
988         (error "No articles to download"))
989       (gnus-agent-with-fetch
990         (setq gnus-newsgroup-undownloaded
991               (gnus-sorted-ndifference
992                gnus-newsgroup-undownloaded
993                (setq fetched-articles
994                      (gnus-agent-fetch-articles
995                       gnus-newsgroup-name articles)))))
996       (save-excursion
997         (dolist (article articles)
998           (let ((was-marked-downloadable 
999                  (memq article gnus-newsgroup-downloadable)))
1000             (cond (gnus-agent-mark-unread-after-downloaded
1001                    (setq gnus-newsgroup-downloadable
1002                          (delq article gnus-newsgroup-downloadable))
1003
1004                    ;; The downloadable mark is implemented as a
1005                    ;; type of read mark.  Therefore, marking the
1006                    ;; article as unread is sufficient to clear
1007                    ;; its downloadable flag.  
1008                    (gnus-summary-mark-article article gnus-unread-mark))
1009                   (was-marked-downloadable
1010                    (gnus-summary-set-agent-mark article t)))
1011             (when (gnus-summary-goto-subject article nil t)
1012               (gnus-summary-update-download-mark article))))))
1013     fetched-articles))
1014
1015 (defun gnus-agent-fetch-selected-article ()
1016   "Fetch the current article as it is selected.
1017 This can be added to `gnus-select-article-hook' or
1018 `gnus-mark-article-hook'."
1019   (let ((gnus-command-method gnus-current-select-method))
1020     (when (and gnus-plugged (gnus-agent-method-p gnus-command-method))
1021       (when (gnus-agent-fetch-articles
1022              gnus-newsgroup-name
1023              (list gnus-current-article))
1024         (setq gnus-newsgroup-undownloaded
1025               (delq gnus-current-article gnus-newsgroup-undownloaded))
1026         (gnus-summary-update-article-line
1027          gnus-current-article
1028          (gnus-summary-article-header gnus-current-article))))))
1029
1030 ;;;
1031 ;;; Internal functions
1032 ;;;
1033
1034 (defun gnus-agent-save-active (method)
1035   (gnus-agent-save-active-1 method 'gnus-active-to-gnus-format))
1036
1037 (defun gnus-agent-save-active-1 (method function)
1038   (when (gnus-agent-method-p method)
1039     (let* ((gnus-command-method method)
1040            (new (gnus-make-hashtable (count-lines (point-min) (point-max))))
1041            (file (gnus-agent-lib-file "active")))
1042       (funcall function nil new)
1043       (gnus-agent-write-active file new)
1044       (erase-buffer)
1045       (nnheader-insert-file-contents file))))
1046
1047 (defun gnus-agent-write-active (file new)
1048   (let ((orig (gnus-make-hashtable (count-lines (point-min) (point-max))))
1049         (file (gnus-agent-lib-file "active"))
1050         elem osym)
1051     (when (file-exists-p file)
1052       (with-temp-buffer
1053         (nnheader-insert-file-contents file)
1054         (gnus-active-to-gnus-format nil orig))
1055       (mapatoms
1056        (lambda (sym)
1057          (when (and sym (boundp sym))
1058            (if (and (boundp (setq osym (intern (symbol-name sym) orig)))
1059                     (setq elem (symbol-value osym)))
1060                (progn
1061                  (if (and (integerp (car (symbol-value sym)))
1062                           (> (car elem) (car (symbol-value sym))))
1063                      (setcar elem (car (symbol-value sym))))
1064                  (if (integerp (cdr (symbol-value sym)))
1065                      (setcdr elem (cdr (symbol-value sym)))))
1066              (set (intern (symbol-name sym) orig) (symbol-value sym)))))
1067        new))
1068     (gnus-make-directory (file-name-directory file))
1069     (let ((nnmail-active-file-coding-system gnus-agent-file-coding-system))
1070       ;; The hashtable contains real names of groups,  no more prefix
1071       ;; removing, so set `full' to `t'.
1072       (gnus-write-active-file file orig t))))
1073
1074 (defun gnus-agent-save-groups (method)
1075   (gnus-agent-save-active-1 method 'gnus-groups-to-gnus-format))
1076
1077 (defun gnus-agent-save-group-info (method group active)
1078   (when (gnus-agent-method-p method)
1079     (let* ((gnus-command-method method)
1080            (coding-system-for-write nnheader-file-coding-system)
1081            (output-coding-system nnheader-file-coding-system)
1082            (file-name-coding-system nnmail-pathname-coding-system)
1083            (pathname-coding-system nnmail-pathname-coding-system)
1084            (file (gnus-agent-lib-file "active"))
1085            oactive-min)
1086       (gnus-make-directory (file-name-directory file))
1087       (with-temp-file file
1088         ;; Emacs got problem to match non-ASCII group in multibyte buffer.
1089         (set-buffer-multibyte nil)
1090         (when (file-exists-p file)
1091           (nnheader-insert-file-contents file))
1092         (goto-char (point-min))
1093         (when (re-search-forward
1094                (concat "^" (regexp-quote group) " ") nil t)
1095           (save-excursion
1096             (read (current-buffer))                      ;; max
1097             (setq oactive-min (read (current-buffer))))  ;; min
1098           (gnus-delete-line))
1099         (insert (format "%S %d %d y\n" (intern group)
1100                         (cdr active)
1101                         (or oactive-min (car active))))
1102         (goto-char (point-max))
1103         (while (search-backward "\\." nil t)
1104           (delete-char 1))))))
1105
1106 (defun gnus-agent-group-path (group)
1107   "Translate GROUP into a file name."
1108   (if nnmail-use-long-file-names
1109       (gnus-group-real-name group)
1110     (nnheader-translate-file-chars
1111      (nnheader-replace-chars-in-string
1112       (nnheader-replace-duplicate-chars-in-string
1113        (nnheader-replace-chars-in-string
1114         (gnus-group-real-name group)
1115         ?/ ?_)
1116        ?. ?_)
1117       ?. ?/))))
1118
1119 (defun gnus-agent-get-function (method)
1120   (if (gnus-online method)
1121       (car method)
1122     (require 'nnagent)
1123     'nnagent))
1124
1125 ;;; History functions
1126
1127 (defun gnus-agent-history-buffer ()
1128   (cdr (assoc (gnus-agent-method) gnus-agent-history-buffers)))
1129
1130 (defun gnus-agent-open-history ()
1131   (save-excursion
1132     (push (cons (gnus-agent-method)
1133                 (set-buffer (gnus-get-buffer-create
1134                              (format " *Gnus agent %s history*"
1135                                      (gnus-agent-method)))))
1136           gnus-agent-history-buffers)
1137     (set-buffer-multibyte nil) ;; everything is binary
1138     (erase-buffer)
1139     (insert "\n")
1140     (let ((file (gnus-agent-lib-file "history")))
1141       (when (file-exists-p file)
1142         (nnheader-insert-file-contents file))
1143       (set (make-local-variable 'gnus-agent-file-name) file))))
1144
1145 (defun gnus-agent-close-history ()
1146   (when (gnus-buffer-live-p gnus-agent-current-history)
1147     (kill-buffer gnus-agent-current-history)
1148     (setq gnus-agent-history-buffers
1149           (delq (assoc (gnus-agent-method) gnus-agent-history-buffers)
1150                 gnus-agent-history-buffers))))
1151
1152 ;;;
1153 ;;; Fetching
1154 ;;;
1155
1156 (defun gnus-agent-fetch-articles (group articles)
1157   "Fetch ARTICLES from GROUP and put them into the Agent."
1158   (when articles
1159     (gnus-agent-load-alist group)
1160     (let* ((alist   gnus-agent-article-alist)
1161            (headers (if (< (length articles) 2) nil gnus-newsgroup-headers))
1162            (selected-sets (list nil))
1163            (current-set-size 0)
1164            article
1165            header-number)
1166       ;; Check each article
1167       (while (setq article (pop articles))
1168         ;; Skip alist entries preceeding this article
1169         (while (> article (or (caar alist) (1+ article)))
1170           (setq alist (cdr alist)))
1171
1172         ;; Prune off articles that we have already fetched.
1173         (unless (and (eq article (caar alist))
1174                      (cdar alist))
1175           ;; Skip headers preceeding this article
1176           (while (> article 
1177                     (setq header-number
1178                           (let* ((header (car headers)))
1179                             (if header
1180                                 (mail-header-number header)
1181                               (1+ article)))))
1182             (setq headers (cdr headers)))
1183
1184           ;; Add this article to the current set
1185           (setcar selected-sets (cons article (car selected-sets)))
1186
1187           ;; Update the set size, when the set is too large start a
1188           ;; new one.  I do this after adding the article as I want at
1189           ;; least one article in each set.
1190           (when (< gnus-agent-max-fetch-size
1191                    (setq current-set-size
1192                          (+ current-set-size
1193                             (if (= header-number article)
1194                                 (let ((char-size (mail-header-chars
1195                                                   (car headers))))
1196                                   (if (<= char-size 0)
1197                                       ;; The char size was missing/invalid,
1198                                       ;; assume a worst-case situation of
1199                                       ;; 65 char/line.  If the line count
1200                                       ;; is missing, arbitrarily assume a
1201                                       ;; size of 1000 characters.
1202                                     (max (* 65 (mail-header-lines
1203                                                 (car headers)))
1204                                          1000)
1205                                     char-size))
1206                               0))))
1207             (setcar selected-sets (nreverse (car selected-sets)))
1208             (setq selected-sets (cons nil selected-sets)
1209                   current-set-size 0))))
1210
1211       (when (or (cdr selected-sets) (car selected-sets))
1212         (let* ((fetched-articles (list nil))
1213                (tail-fetched-articles fetched-articles)
1214                (dir (concat
1215                      (gnus-agent-directory)
1216                      (gnus-agent-group-path group) "/"))
1217                (date (time-to-days (current-time)))
1218                (case-fold-search t)
1219                pos crosses id)
1220
1221           (setcar selected-sets (nreverse (car selected-sets)))
1222           (setq selected-sets (nreverse selected-sets))
1223
1224           (gnus-make-directory dir)
1225           (gnus-message 7 "Fetching articles for %s..." group)
1226
1227           (unwind-protect
1228               (while (setq articles (pop selected-sets))
1229                 ;; Fetch the articles from the backend.
1230                 (if (gnus-check-backend-function 'retrieve-articles group)
1231                     (setq pos (gnus-retrieve-articles articles group))
1232                   (with-temp-buffer
1233                     (let (article)
1234                       (while (setq article (pop articles))
1235                         (gnus-message 10 "Fetching article %s for %s..."
1236                                       article group)
1237                         (when (or
1238                                (gnus-backlog-request-article group article
1239                                                              nntp-server-buffer)
1240                                (gnus-request-article article group))
1241                           (goto-char (point-max))
1242                           (push (cons article (point)) pos)
1243                           (insert-buffer-substring nntp-server-buffer)))
1244                       (copy-to-buffer
1245                        nntp-server-buffer (point-min) (point-max))
1246                       (setq pos (nreverse pos)))))
1247                 ;; Then save these articles into the Agent.
1248                 (save-excursion
1249                   (set-buffer nntp-server-buffer)
1250                   (while pos
1251                     (narrow-to-region (cdar pos) (or (cdadr pos) (point-max)))
1252                     (goto-char (point-min))
1253                     (unless (eobp) ;; Don't save empty articles.
1254                       (when (search-forward "\n\n" nil t)
1255                         (when (search-backward "\nXrefs: " nil t)
1256                           ;; Handle cross posting.
1257                           (goto-char (match-end 0)) ; move to end of header name
1258                           (skip-chars-forward "^ ") ; skip server name
1259                           (skip-chars-forward " ")
1260                           (setq crosses nil)
1261                           (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) *")
1262                             (push (cons (buffer-substring (match-beginning 1)
1263                                                           (match-end 1))
1264                                         (string-to-int
1265                                          (buffer-substring (match-beginning 2)
1266                                                            (match-end 2))))
1267                                   crosses)
1268                             (goto-char (match-end 0)))
1269                           (gnus-agent-crosspost crosses (caar pos) date)))
1270                       (goto-char (point-min))
1271                       (if (not (re-search-forward
1272                                 "^Message-ID: *<\\([^>\n]+\\)>" nil t))
1273                           (setq id "No-Message-ID-in-article")
1274                         (setq id (buffer-substring
1275                                   (match-beginning 1) (match-end 1))))
1276                       (write-region-as-coding-system
1277                        gnus-agent-file-coding-system (point-min) (point-max)
1278                        (concat dir (number-to-string (caar pos))) nil 'silent)
1279
1280                       (gnus-agent-append-to-list
1281                        tail-fetched-articles (caar pos)))
1282                     (widen)
1283                     (pop pos))))
1284
1285             (gnus-agent-save-alist group (cdr fetched-articles) date)
1286             (gnus-message 7 nil))
1287           (cdr fetched-articles))))))
1288
1289 (defun gnus-agent-crosspost (crosses article &optional date)
1290   (setq date (or date t))
1291
1292   (let (gnus-agent-article-alist group alist beg end)
1293     (save-excursion
1294       (set-buffer gnus-agent-overview-buffer)
1295       (when (nnheader-find-nov-line article)
1296         (forward-word 1)
1297         (setq beg (point))
1298         (setq end (progn (forward-line 1) (point)))))
1299     (while crosses
1300       (setq group (caar crosses))
1301       (unless (setq alist (assoc group gnus-agent-group-alist))
1302         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
1303               gnus-agent-group-alist))
1304       (setcdr alist (cons (cons (cdar crosses) date) (cdr alist)))
1305       (save-excursion
1306         (set-buffer (gnus-get-buffer-create (format " *Gnus agent overview %s*"
1307                                                     group)))
1308         (when (= (point-max) (point-min))
1309           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
1310           (ignore-errors
1311             (nnheader-insert-file-contents
1312              (gnus-agent-article-name ".overview" group))))
1313         (nnheader-find-nov-line (string-to-number (cdar crosses)))
1314         (insert (string-to-number (cdar crosses)))
1315         (insert-buffer-substring gnus-agent-overview-buffer beg end)
1316         (gnus-agent-check-overview-buffer))
1317       (pop crosses))))
1318
1319 (defun gnus-agent-backup-overview-buffer ()
1320   (when gnus-newsgroup-name
1321     (let ((root (gnus-agent-article-name ".overview" gnus-newsgroup-name))
1322           (cnt 0)
1323           name)
1324       (while (file-exists-p
1325               (setq name (concat root "~"
1326                                  (int-to-string (setq cnt (1+ cnt))) "~"))))
1327       (write-region (point-min) (point-max) name nil 'no-msg)
1328       (gnus-message 1 "Created backup copy of overview in %s." name)))
1329   t)
1330
1331 (defun gnus-agent-check-overview-buffer (&optional buffer)
1332   "Check the overview file given for sanity.
1333 In particular, checks that the file is sorted by article number
1334 and that there are no duplicates."
1335   (let ((prev-num -1)
1336         (backed-up nil))
1337     (save-excursion
1338       (when buffer
1339         (set-buffer buffer))
1340       (save-restriction
1341         (widen)
1342         (goto-char (point-min))
1343
1344         (while (< (point) (point-max))
1345           (let ((p (point))
1346                 (cur (condition-case nil
1347                          (read (current-buffer))
1348                        (error nil))))
1349             (cond
1350              ((or (not (integerp cur))
1351                   (not (eq (char-after) ?\t)))
1352               (or backed-up
1353                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1354               (gnus-message 1
1355                             "Overview buffer contains garbage '%s'."
1356                             (buffer-substring
1357                              p (gnus-point-at-eol))))
1358              ((= cur prev-num)
1359               (or backed-up
1360                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1361               (gnus-message 1
1362                             "Duplicate overview line for %d" cur)
1363               (delete-region (point) (progn (forward-line 1) (point))))
1364              ((< cur prev-num)
1365               (or backed-up
1366                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1367               (gnus-message 1 "Overview buffer not sorted!")
1368               (sort-numeric-fields 1 (point-min) (point-max))
1369               (goto-char (point-min))
1370               (setq prev-num -1))
1371              (t
1372               (setq prev-num cur)))
1373             (forward-line 1)))))))
1374
1375 (defun gnus-agent-flush-cache ()
1376   (save-excursion
1377     (while gnus-agent-buffer-alist
1378       (set-buffer (cdar gnus-agent-buffer-alist))
1379       (write-region-as-coding-system
1380        gnus-agent-file-coding-system
1381        (point-min) (point-max)
1382        (gnus-agent-article-name ".overview"
1383                                 (caar gnus-agent-buffer-alist))
1384        nil 'silent)
1385       (pop gnus-agent-buffer-alist))
1386     (while gnus-agent-group-alist
1387       (with-temp-file (gnus-agent-article-name
1388                        ".agentview" (caar gnus-agent-group-alist))
1389         (princ (cdar gnus-agent-group-alist))
1390         (insert "\n")
1391         (princ 1 (current-buffer))
1392         (insert "\n"))
1393       (pop gnus-agent-group-alist))))
1394
1395 (defun gnus-agent-find-parameter (group symbol)
1396   "Search for GROUPs SYMBOL in the group's parameters, the group's
1397 topic parameters, the group's category, or the customizable
1398 variables.  Returns the first non-nil value found."
1399   (or (gnus-group-find-parameter group symbol t)
1400       (gnus-group-parameter-value (cdr (gnus-group-category group)) symbol t)
1401       (symbol-value
1402        (cdr
1403         (assq symbol
1404          '((agent-short-article . gnus-agent-short-article)
1405            (agent-long-article . gnus-agent-long-article)
1406            (agent-low-score . gnus-agent-low-score)
1407            (agent-high-score . gnus-agent-high-score)
1408            (agent-days-until-old . gnus-agent-expire-days)
1409            (agent-enable-expiration
1410             . gnus-agent-enable-expiration)))))))
1411
1412 (defun gnus-agent-fetch-headers (group &optional force)
1413   "Fetch interesting headers into the agent.  The group's overview
1414 file will be updated to include the headers while a list of available
1415 article numbers will be returned."
1416   (let* ((fetch-all (and gnus-agent-consider-all-articles
1417                          ;; Do not fetch all headers if the predicate
1418                          ;; implies that we only consider unread articles.
1419                          (not (gnus-predicate-implies-unread
1420                                (gnus-agent-find-parameter group
1421                                                           'agent-predicate)))))
1422          (articles (if fetch-all
1423                        (gnus-uncompress-range (gnus-active group))
1424                      (gnus-list-of-unread-articles group)))
1425          (gnus-decode-encoded-word-function 'identity)
1426          (file (gnus-agent-article-name ".overview" group)))
1427     ;; Check whether the number of articles is not too large.
1428     (when (and (integerp gnus-agent-large-newsgroup)
1429                (> gnus-agent-large-newsgroup 0))
1430       (setq articles (nthcdr (max (- (length articles)
1431                                      gnus-agent-large-newsgroup)
1432                                   0)
1433                              articles)))
1434     (unless fetch-all
1435       ;; Add articles with marks to the list of article headers we want to
1436       ;; fetch.  Don't fetch articles solely on the basis of a recent or seen
1437       ;; mark, but do fetch recent or seen articles if they have other, more
1438       ;; interesting marks.  (We have to fetch articles with boring marks
1439       ;; because otherwise the agent will remove their marks.)
1440       (dolist (arts (gnus-info-marks (gnus-get-info group)))
1441         (unless (memq (car arts) '(seen recent killed cache))
1442           (setq articles (gnus-range-add articles (cdr arts)))))
1443       (setq articles (sort (gnus-uncompress-sequence articles) '<)))
1444
1445     ;; At this point, I have the list of articles to consider for
1446     ;; fetching.  This is the list that I'll return to my caller. Some
1447     ;; of these articles may have already been fetched.  That's OK as
1448     ;; the fetch article code will filter those out.  Internally, I'll
1449     ;; filter this list to just those articles whose headers need to
1450     ;; be fetched.
1451     (let ((articles articles))
1452       ;; Remove known articles.
1453       (when (and (or gnus-agent-cache
1454                      (not gnus-plugged))
1455                  (gnus-agent-load-alist group))
1456         ;; Remove articles marked as downloaded.
1457         (if fetch-all
1458             ;; I want to fetch all headers in the active range.
1459             ;; Therefore, exclude only those headers that are in the
1460             ;; article alist.
1461             ;; NOTE: This is probably NOT what I want to do after
1462             ;; agent expiration in this group.
1463             (setq articles (gnus-agent-uncached-articles articles group))
1464
1465           ;; I want to only fetch those headers that have never been
1466           ;; fetched.  Therefore, exclude all headers that are, or
1467           ;; WERE, in the article alist.
1468           (let ((low (1+ (caar (last gnus-agent-article-alist))))
1469                 (high (cdr (gnus-active group))))
1470             ;; Low can be greater than High when the same group is
1471             ;; fetched twice in the same session {The first fetch will
1472             ;; fill the article alist such that (last
1473             ;; gnus-agent-article-alist) equals (cdr (gnus-active
1474             ;; group))}.  The addition of one(the 1+ above) then
1475             ;; forces Low to be greater than High.  When this happens,
1476             ;; gnus-list-range-intersection returns nil which
1477             ;; indicates that no headers need to be fetched. -- Kevin
1478             (setq articles (gnus-list-range-intersection
1479                             articles (list (cons low high)))))))
1480
1481       (gnus-message
1482        10 "gnus-agent-fetch-headers: undownloaded articles are '%s'"
1483        (gnus-compress-sequence articles t))
1484
1485       (save-excursion
1486         (set-buffer nntp-server-buffer)
1487
1488         (if articles
1489             (progn
1490               (gnus-message 7 "Fetching headers for %s..." group)
1491
1492               ;; Fetch them.
1493               (gnus-make-directory (nnheader-translate-file-chars
1494                                     (file-name-directory file) t))
1495
1496               (unless (eq 'nov (gnus-retrieve-headers articles group))
1497                 (nnvirtual-convert-headers))
1498               (gnus-agent-check-overview-buffer)
1499               ;; Move these headers to the overview buffer so that
1500               ;; gnus-agent-braid-nov can merge them with the contents
1501               ;; of FILE.
1502               (copy-to-buffer
1503                gnus-agent-overview-buffer (point-min) (point-max))
1504               (when (file-exists-p file)
1505                 (gnus-agent-braid-nov group articles file))
1506               (gnus-agent-check-overview-buffer)
1507               (write-region-as-coding-system
1508                gnus-agent-file-coding-system
1509                (point-min) (point-max) file nil 'silent)
1510               (gnus-agent-save-alist group articles nil)
1511               articles)
1512           (ignore-errors
1513             (erase-buffer)
1514             (nnheader-insert-file-contents file)))))
1515     articles))
1516
1517 (defsubst gnus-agent-copy-nov-line (article)
1518   (let (art b e)
1519     (set-buffer gnus-agent-overview-buffer)
1520     (while (and (not (eobp))
1521                 (< (setq art (read (current-buffer))) article))
1522       (forward-line 1))
1523     (beginning-of-line)
1524     (if (or (eobp)
1525             (not (eq article art)))
1526         (set-buffer nntp-server-buffer)
1527       (setq b (point))
1528       (setq e (progn (forward-line 1) (point)))
1529       (set-buffer nntp-server-buffer)
1530       (insert-buffer-substring gnus-agent-overview-buffer b e))))
1531
1532 (defun gnus-agent-braid-nov (group articles file)
1533   "Merge agent overview data with given file.
1534 Takes headers for ARTICLES from `gnus-agent-overview-buffer' and the given
1535 FILE and places the combined headers into `nntp-server-buffer'."
1536   (let (start last)
1537     (set-buffer gnus-agent-overview-buffer)
1538     (goto-char (point-min))
1539     (set-buffer nntp-server-buffer)
1540     (erase-buffer)
1541     (nnheader-insert-file-contents file)
1542     (goto-char (point-max))
1543     (forward-line -1)
1544     (unless (looking-at "[0-9]+\t")
1545       ;; Remove corrupted lines
1546       (gnus-message
1547        1 "Overview %s is corrupted. Removing corrupted lines..." file)
1548       (goto-char (point-min))
1549       (while (not (eobp))
1550         (if (looking-at "[0-9]+\t")
1551             (forward-line 1)
1552           (delete-region (point) (progn (forward-line 1) (point)))))
1553       (forward-line -1))
1554     (unless (or (= (point-min) (point-max))
1555                 (< (setq last (read (current-buffer))) (car articles)))
1556       ;; We do it the hard way.
1557       (when (nnheader-find-nov-line (car articles))
1558         ;; Replacing existing NOV entry
1559         (delete-region (point) (progn (forward-line 1) (point))))
1560       (gnus-agent-copy-nov-line (pop articles))
1561
1562       (ignore-errors
1563         (while articles
1564           (while (let ((art (read (current-buffer))))
1565                    (cond ((< art (car articles))
1566                           (forward-line 1)
1567                           t)
1568                          ((= art (car articles))
1569                           (beginning-of-line)
1570                           (delete-region
1571                            (point) (progn (forward-line 1) (point)))
1572                           nil)
1573                          (t
1574                           (beginning-of-line)
1575                           nil))))
1576
1577           (gnus-agent-copy-nov-line (pop articles)))))
1578
1579     ;; Copy the rest lines
1580     (set-buffer nntp-server-buffer)
1581     (goto-char (point-max))
1582     (when articles
1583       (when last
1584         (set-buffer gnus-agent-overview-buffer)
1585         (ignore-errors
1586           (while (<= (read (current-buffer)) last)
1587             (forward-line 1)))
1588         (beginning-of-line)
1589         (setq start (point))
1590         (set-buffer nntp-server-buffer))
1591       (insert-buffer-substring gnus-agent-overview-buffer start))))
1592
1593 ;; Keeps the compiler from warning about the free variable in
1594 ;; gnus-agent-read-agentview.
1595 (eval-when-compile
1596   (defvar gnus-agent-read-agentview))
1597
1598 (defun gnus-agent-load-alist (group)
1599   "Load the article-state alist for GROUP."
1600   ;; Bind free variable that's used in `gnus-agent-read-agentview'.
1601   (let ((gnus-agent-read-agentview group))
1602     (setq gnus-agent-article-alist
1603           (gnus-cache-file-contents
1604            (gnus-agent-article-name ".agentview" group)
1605            'gnus-agent-file-loading-cache
1606            'gnus-agent-read-agentview))))
1607
1608 ;; Save format may be either 1 or 2.  Two is the new, compressed
1609 ;; format that is still being tested.  Format 1 is uncompressed but
1610 ;; known to be reliable.
1611 (defconst gnus-agent-article-alist-save-format 2)
1612
1613 (defun gnus-agent-read-agentview (file)
1614   "Load FILE and do a `read' there."
1615   (with-temp-buffer
1616     (ignore-errors
1617       (nnheader-insert-file-contents file)
1618       (goto-char (point-min))
1619       (let ((alist (read (current-buffer)))
1620             (version (condition-case nil (read (current-buffer))
1621                        (end-of-file 0)))
1622             changed-version)
1623
1624         (cond
1625          ((= version 0)
1626           (let ((inhibit-quit t)
1627                 entry)
1628             (gnus-agent-open-history)
1629             (set-buffer (gnus-agent-history-buffer))
1630             (goto-char (point-min))
1631             (while (not (eobp))
1632               (if (and (looking-at
1633                         "[^\t\n]+\t\\([0-9]+\\)\t\\([^ \n]+\\) \\([0-9]+\\)")
1634                        (string= (match-string 2)
1635                                 gnus-agent-read-agentview)
1636                        (setq entry (assoc (string-to-number (match-string 3)) alist)))
1637                   (setcdr entry (string-to-number (match-string 1))))
1638               (forward-line 1))
1639             (gnus-agent-close-history)
1640             (setq changed-version t)))
1641          ((= version 1)
1642           (setq changed-version (not (= 1 gnus-agent-article-alist-save-format))))
1643          ((= version 2)
1644           (let (uncomp)
1645             (mapcar
1646              (lambda (comp-list)
1647                (let ((state (car comp-list))
1648                      (sequence (gnus-uncompress-sequence
1649                                 (cdr comp-list))))
1650                  (mapcar (lambda (article-id)
1651                            (setq uncomp (cons (cons article-id state) uncomp)))
1652                          sequence)))
1653              alist)
1654             (setq alist (sort uncomp
1655                               (lambda (first second)
1656                                 (< (car first) (car second))))))))
1657         (when changed-version
1658           (let ((gnus-agent-article-alist alist))
1659             (gnus-agent-save-alist gnus-agent-read-agentview)))
1660         alist))))
1661
1662 (defun gnus-agent-save-alist (group &optional articles state dir)
1663   "Save the article-state alist for GROUP."
1664   (let* ((file-name-coding-system nnmail-pathname-coding-system)
1665          (pathname-coding-system nnmail-pathname-coding-system)
1666          (prev (cons nil gnus-agent-article-alist))
1667          (all prev)
1668          print-level print-length item article)
1669     (while (setq article (pop articles))
1670       (while (and (cdr prev)
1671                   (< (caadr prev) article))
1672         (setq prev (cdr prev)))
1673       (cond
1674        ((not (cdr prev))
1675         (setcdr prev (list (cons article state))))
1676        ((> (caadr prev) article)
1677         (setcdr prev (cons (cons article state) (cdr prev))))
1678        ((= (caadr prev) article)
1679         (setcdr (cadr prev) state)))
1680       (setq prev (cdr prev)))
1681     (setq gnus-agent-article-alist (cdr all))
1682     (if dir
1683         (gnus-make-directory dir)
1684       (gnus-make-directory (gnus-agent-article-name "" group)))
1685     (with-temp-file (if dir
1686                         (expand-file-name ".agentview" dir)
1687                       (gnus-agent-article-name ".agentview" group))
1688       (cond ((eq gnus-agent-article-alist-save-format 1)
1689              (princ gnus-agent-article-alist (current-buffer)))
1690             ((eq gnus-agent-article-alist-save-format 2)
1691              (let ((compressed nil))
1692                (mapcar (lambda (pair)
1693                          (let* ((article-id (car pair))
1694                                 (day-of-download (cdr pair))
1695                                 (comp-list (assq day-of-download compressed)))
1696                            (if comp-list
1697                                (setcdr comp-list
1698                                        (cons article-id (cdr comp-list)))
1699                              (setq compressed
1700                                    (cons (list day-of-download article-id)
1701                                          compressed)))
1702                            nil)) gnus-agent-article-alist)
1703                (mapcar (lambda (comp-list)
1704                          (setcdr comp-list
1705                                  (gnus-compress-sequence
1706                                   (nreverse (cdr comp-list)))))
1707                        compressed)
1708                (princ compressed (current-buffer)))))
1709       (insert "\n")
1710       (princ gnus-agent-article-alist-save-format (current-buffer))
1711       (insert "\n"))))
1712
1713 (defun gnus-agent-article-name (article group)
1714   (expand-file-name article
1715                     (file-name-as-directory
1716                      (expand-file-name (gnus-agent-group-path group)
1717                                        (gnus-agent-directory)))))
1718
1719 (defun gnus-agent-batch-confirmation (msg)
1720   "Show error message and return t."
1721   (gnus-message 1 msg)
1722   t)
1723
1724 ;;;###autoload
1725 (defun gnus-agent-batch-fetch ()
1726   "Start Gnus and fetch session."
1727   (interactive)
1728   (gnus)
1729   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1730     (gnus-agent-fetch-session))
1731   (gnus-group-exit))
1732
1733 (defun gnus-agent-fetch-session ()
1734   "Fetch all articles and headers that are eligible for fetching."
1735   (interactive)
1736   (unless gnus-agent-covered-methods
1737     (error "No servers are covered by the Gnus agent"))
1738   (unless gnus-plugged
1739     (error "Can't fetch articles while Gnus is unplugged"))
1740   (let ((methods gnus-agent-covered-methods)
1741         groups group gnus-command-method)
1742     (save-excursion
1743       (while methods
1744         (condition-case err
1745             (progn
1746               (setq gnus-command-method (car methods))
1747               (when (and (or (gnus-server-opened gnus-command-method)
1748                              (gnus-open-server gnus-command-method))
1749                          (gnus-online gnus-command-method))
1750                 (setq groups (gnus-groups-from-server (car methods)))
1751                 (gnus-agent-with-fetch
1752                  (while (setq group (pop groups))
1753                    (when (<= (gnus-group-level group)
1754                              gnus-agent-handle-level)
1755                      (gnus-agent-fetch-group-1
1756                       group gnus-command-method))))))
1757           (error
1758            (unless (funcall gnus-agent-confirmation-function
1759                             (format "Error %s.  Continue? "
1760                                     (error-message-string err)))
1761              (error "Cannot fetch articles into the Gnus agent")))
1762           (quit
1763            (unless (funcall gnus-agent-confirmation-function
1764                             (format
1765                              "Quit fetching session %s.  Continue? "
1766                              (error-message-string err)))
1767              (signal 'quit
1768                      "Cannot fetch articles into the Gnus agent"))))
1769         (pop methods))
1770       (run-hooks 'gnus-agent-fetch-hook)
1771       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
1772
1773 (defun gnus-agent-fetch-group-1 (group method)
1774   "Fetch GROUP."
1775   (let ((gnus-command-method method)
1776         (gnus-newsgroup-name group)
1777         (gnus-newsgroup-dependencies gnus-newsgroup-dependencies)
1778         (gnus-newsgroup-headers gnus-newsgroup-headers)
1779         (gnus-newsgroup-scored gnus-newsgroup-scored)
1780         (gnus-use-cache gnus-use-cache)
1781         (gnus-summary-expunge-below gnus-summary-expunge-below)
1782         (gnus-summary-mark-below gnus-summary-mark-below)
1783         (gnus-orphan-score gnus-orphan-score)
1784         ;; Maybe some other gnus-summary local variables should also
1785         ;; be put here.
1786
1787         gnus-headers
1788         gnus-score
1789         articles arts
1790         category predicate info marks score-param
1791         )
1792     (unless (gnus-check-group group)
1793       (error "Can't open server for %s" group))
1794
1795     ;; Fetch headers.
1796     (when (or gnus-newsgroup-active
1797               (gnus-active group)
1798               (gnus-activate-group group))
1799       (let ((marked-articles gnus-newsgroup-downloadable))
1800         ;; Identify the articles marked for download
1801         (unless gnus-newsgroup-active
1802           ;; The variable gnus-newsgroup-active was selected as I need
1803           ;; a gnus-summary local variable that is NOT bound to any
1804           ;; value (its global value should default to nil).
1805           (dolist (mark gnus-agent-download-marks)
1806             (let ((arts (cdr (assq mark (gnus-info-marks
1807                                          (setq info (gnus-get-info group)))))))
1808               (when arts
1809                 (setq marked-articles (nconc (gnus-uncompress-range arts)
1810                                              marked-articles))
1811                 ))))
1812         (setq marked-articles (sort marked-articles '<))
1813
1814         ;; Fetch any new articles from the server
1815         (setq articles (gnus-agent-fetch-headers group))
1816
1817         ;; Merge new articles with marked
1818         (setq articles (sort (append marked-articles articles) '<))
1819
1820         (when articles
1821           ;; Parse them and see which articles we want to fetch.
1822           (setq gnus-newsgroup-dependencies
1823                 (or gnus-newsgroup-dependencies
1824                     (make-vector (length articles) 0)))
1825           (setq gnus-newsgroup-headers
1826                 (or gnus-newsgroup-headers
1827                     (gnus-get-newsgroup-headers-xover articles nil nil
1828                                                       group)))
1829           ;; `gnus-agent-overview-buffer' may be killed for
1830           ;; timeout reason.  If so, recreate it.
1831           (gnus-agent-create-buffer)
1832
1833           ;; Figure out how to select articles in this group
1834           (setq category (gnus-group-category group))
1835
1836           (setq predicate
1837                 (gnus-get-predicate
1838                  (gnus-agent-find-parameter group 'agent-predicate)))
1839
1840           ;; If the selection predicate requires scoring, score each header
1841           (unless (memq predicate '(gnus-agent-true gnus-agent-false))
1842             (let ((score-param
1843                    (gnus-agent-find-parameter group 'agent-score)))
1844               ;; Translate score-param into real one
1845               (cond
1846                ((not score-param))
1847                ((eq score-param 'file)
1848                 (setq score-param (gnus-all-score-files group)))
1849                ((stringp (car score-param)))
1850                (t
1851                 (setq score-param (list (list score-param)))))
1852               (when score-param
1853                 (gnus-score-headers score-param))))
1854
1855           (unless (and (eq predicate 'gnus-agent-false)
1856                        (not marked-articles))
1857             (let ((arts (list nil)))
1858               (let ((arts-tail arts)
1859                     (alist (gnus-agent-load-alist group))
1860                     (marked-articles marked-articles)
1861                     (gnus-newsgroup-headers gnus-newsgroup-headers))
1862                 (while (setq gnus-headers (pop gnus-newsgroup-headers))
1863                   (let ((num (mail-header-number gnus-headers)))
1864                     ;; Determine if this article is already in the cache
1865                     (while (and alist
1866                                 (> num (caar alist)))
1867                       (setq alist (cdr alist)))
1868
1869                     (unless (and (eq num (caar alist))
1870                                  (cdar alist))
1871
1872                       ;; Determine if this article was marked for download.
1873                       (while (and marked-articles
1874                                   (> num (car marked-articles)))
1875                         (setq marked-articles
1876                               (cdr marked-articles)))
1877
1878                       ;; When this article is marked, or selected by the
1879                       ;; predicate, add it to the download list
1880                       (when (or (eq num (car marked-articles))
1881                                 (let ((gnus-score
1882                                        (or (cdr
1883                                             (assq num gnus-newsgroup-scored))
1884                                            gnus-summary-default-score))
1885                                       (gnus-agent-long-article
1886                                        (gnus-agent-find-parameter
1887                                         group 'agent-long-article))
1888                                       (gnus-agent-low-score
1889                                        (gnus-agent-find-parameter
1890                                         group 'agent-low-score))
1891                                       (gnus-agent-high-score
1892                                        (gnus-agent-find-parameter
1893                                         group 'agent-high-score))
1894                                       (gnus-agent-expire-days
1895                                        (gnus-agent-find-parameter
1896                                         group 'agent-days-until-old)))
1897                                   (funcall predicate)))
1898                         (gnus-agent-append-to-list arts-tail num))))))
1899
1900               (let (fetched-articles)
1901                 ;; Fetch all selected articles
1902                 (setq gnus-newsgroup-undownloaded
1903                       (gnus-sorted-ndifference
1904                        gnus-newsgroup-undownloaded
1905                        (setq fetched-articles
1906                              (if (cdr arts)
1907                                  (gnus-agent-fetch-articles group (cdr arts))
1908                                nil))))
1909
1910                 (let ((unfetched-articles
1911                        (gnus-sorted-ndifference (cdr arts) fetched-articles)))
1912                   (if gnus-newsgroup-active
1913                       ;; Update the summary buffer
1914                       (progn
1915                         (dolist (article marked-articles)
1916                           (gnus-summary-set-agent-mark article t))
1917                         (dolist (article fetched-articles)
1918                           (if gnus-agent-mark-unread-after-downloaded
1919                               (gnus-summary-mark-article
1920                                article gnus-unread-mark))
1921                           (when (gnus-summary-goto-subject article nil t)
1922                             (gnus-summary-update-download-mark article)))
1923                         (dolist (article unfetched-articles)
1924                           (gnus-summary-mark-article
1925                            article gnus-canceled-mark)))
1926
1927                     ;; Update the group buffer.
1928
1929                     ;; When some, or all, of the marked articles came
1930                     ;; from the download mark.  Remove that mark.  I
1931                     ;; didn't do this earlier as I only want to remove
1932                     ;; the marks after the fetch is completed.
1933
1934                     (dolist (mark gnus-agent-download-marks)
1935                       (when (eq mark 'download)
1936                         (let ((marked-arts
1937                                (assq mark (gnus-info-marks
1938                                            (setq info (gnus-get-info group))))))
1939                           (when (cdr marked-arts)
1940                             (setq marks
1941                                   (delq marked-arts (gnus-info-marks info)))
1942                             (gnus-info-set-marks info marks)))))
1943                     (let ((read (gnus-info-read
1944                                  (or info (setq info (gnus-get-info group))))))
1945                       (gnus-info-set-read
1946                        info (gnus-add-to-range read unfetched-articles)))
1947
1948                     (gnus-group-update-group group t)
1949                     (sit-for 0)
1950
1951                     (gnus-dribble-enter
1952                      (concat "(gnus-group-set-info '"
1953                              (gnus-prin1-to-string info)
1954                              ")"))))))))))))
1955
1956 ;;;
1957 ;;; Agent Category Mode
1958 ;;;
1959
1960 (defvar gnus-category-mode-hook nil
1961   "Hook run in `gnus-category-mode' buffers.")
1962
1963 (defvar gnus-category-line-format "     %(%20c%): %g\n"
1964   "Format of category lines.
1965
1966 Valid specifiers include:
1967 %c  Topic name (string)
1968 %g  The number of groups in the topic (integer)
1969
1970 General format specifiers can also be used.  See Info node
1971 `(gnus)Formatting Variables'.")
1972
1973 (defvar gnus-category-mode-line-format "Gnus: %%b"
1974   "The format specification for the category mode line.")
1975
1976 (defvar gnus-agent-short-article 100
1977   "Articles that have fewer lines than this are short.")
1978
1979 (defvar gnus-agent-long-article 200
1980   "Articles that have more lines than this are long.")
1981
1982 (defvar gnus-agent-low-score 0
1983   "Articles that have a score lower than this have a low score.")
1984
1985 (defvar gnus-agent-high-score 0
1986   "Articles that have a score higher than this have a high score.")
1987
1988
1989 ;;; Internal variables.
1990
1991 (defvar gnus-category-buffer "*Agent Category*")
1992
1993 (defvar gnus-category-line-format-alist
1994   `((?c gnus-tmp-name ?s)
1995     (?g gnus-tmp-groups ?d)))
1996
1997 (defvar gnus-category-mode-line-format-alist
1998   `((?u user-defined ?s)))
1999
2000 (defvar gnus-category-line-format-spec nil)
2001 (defvar gnus-category-mode-line-format-spec nil)
2002
2003 (defvar gnus-category-mode-map nil)
2004 (put 'gnus-category-mode 'mode-class 'special)
2005
2006 (unless gnus-category-mode-map
2007   (setq gnus-category-mode-map (make-sparse-keymap))
2008   (suppress-keymap gnus-category-mode-map)
2009
2010   (gnus-define-keys gnus-category-mode-map
2011     "q" gnus-category-exit
2012     "k" gnus-category-kill
2013     "c" gnus-category-copy
2014     "a" gnus-category-add
2015     "e" gnus-agent-customize-category
2016     "p" gnus-category-edit-predicate
2017     "g" gnus-category-edit-groups
2018     "s" gnus-category-edit-score
2019     "l" gnus-category-list
2020
2021     "\C-c\C-i" gnus-info-find-node
2022     "\C-c\C-b" gnus-bug))
2023
2024 (defvar gnus-category-menu-hook nil
2025   "*Hook run after the creation of the menu.")
2026
2027 (defun gnus-category-make-menu-bar ()
2028   (gnus-turn-off-edit-menu 'category)
2029   (unless (boundp 'gnus-category-menu)
2030     (easy-menu-define
2031      gnus-category-menu gnus-category-mode-map ""
2032      '("Categories"
2033        ["Add" gnus-category-add t]
2034        ["Kill" gnus-category-kill t]
2035        ["Copy" gnus-category-copy t]
2036        ["Edit category" gnus-agent-customize-category t]
2037        ["Edit predicate" gnus-category-edit-predicate t]
2038        ["Edit score" gnus-category-edit-score t]
2039        ["Edit groups" gnus-category-edit-groups t]
2040        ["Exit" gnus-category-exit t]))
2041
2042     (gnus-run-hooks 'gnus-category-menu-hook)))
2043
2044 (defun gnus-category-mode ()
2045   "Major mode for listing and editing agent categories.
2046
2047 All normal editing commands are switched off.
2048 \\<gnus-category-mode-map>
2049 For more in-depth information on this mode, read the manual
2050 \(`\\[gnus-info-find-node]').
2051
2052 The following commands are available:
2053
2054 \\{gnus-category-mode-map}"
2055   (interactive)
2056   (when (gnus-visual-p 'category-menu 'menu)
2057     (gnus-category-make-menu-bar))
2058   (kill-all-local-variables)
2059   (gnus-simplify-mode-line)
2060   (setq major-mode 'gnus-category-mode)
2061   (setq mode-name "Category")
2062   (gnus-set-default-directory)
2063   (setq mode-line-process nil)
2064   (use-local-map gnus-category-mode-map)
2065   (buffer-disable-undo)
2066   (setq truncate-lines t)
2067   (setq buffer-read-only t)
2068   (gnus-run-hooks 'gnus-category-mode-hook))
2069
2070 (defalias 'gnus-category-position-point 'gnus-goto-colon)
2071
2072 (defun gnus-category-insert-line (category)
2073   (let* ((gnus-tmp-name (format "%s" (car category)))
2074          (gnus-tmp-groups (length (gnus-agent-cat-groups category))))
2075     (beginning-of-line)
2076     (gnus-add-text-properties
2077      (point)
2078      (prog1 (1+ (point))
2079        ;; Insert the text.
2080        (eval gnus-category-line-format-spec))
2081      (list 'gnus-category gnus-tmp-name))))
2082
2083 (defun gnus-enter-category-buffer ()
2084   "Go to the Category buffer."
2085   (interactive)
2086   (gnus-category-setup-buffer)
2087   (gnus-configure-windows 'category)
2088   (gnus-category-prepare))
2089
2090 (defun gnus-category-setup-buffer ()
2091   (unless (get-buffer gnus-category-buffer)
2092     (save-excursion
2093       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
2094       (gnus-category-mode))))
2095
2096 (defun gnus-category-prepare ()
2097   (gnus-set-format 'category-mode)
2098   (gnus-set-format 'category t)
2099   (let ((alist gnus-category-alist)
2100         (buffer-read-only nil))
2101     (erase-buffer)
2102     (while alist
2103       (gnus-category-insert-line (pop alist)))
2104     (goto-char (point-min))
2105     (gnus-category-position-point)))
2106
2107 (defun gnus-category-name ()
2108   (or (intern (get-text-property (gnus-point-at-bol) 'gnus-category))
2109       (error "No category on the current line")))
2110
2111 (defun gnus-category-read ()
2112   "Read the category alist."
2113   (setq gnus-category-alist
2114         (or
2115          (with-temp-buffer
2116            (ignore-errors
2117             (nnheader-insert-file-contents (nnheader-concat gnus-agent-directory "lib/categories"))
2118             (goto-char (point-min))
2119             ;; This code isn't temp, it will be needed so long as
2120             ;; anyone may be migrating from an older version.
2121
2122             ;; Once we're certain that people will not revert to an
2123             ;; earlier version, we can take out the old-list code in
2124             ;; gnus-category-write.
2125             (let* ((old-list (read (current-buffer)))
2126                    (new-list (ignore-errors (read (current-buffer)))))
2127               (if new-list
2128                   new-list
2129                 ;; Convert from a positional list to an alist.
2130                 (mapcar
2131                  (lambda (c)
2132                    (setcdr c
2133                            (mapcar*
2134                             (lambda (valu symb)
2135                               (cons symb valu))
2136                             (cdr c)
2137                             '(agent-predicate agent-score-file agent-groups)))
2138                    c)
2139                  old-list)))))
2140          (list (gnus-agent-cat-make 'default)))))
2141
2142 (defun gnus-category-write ()
2143   "Write the category alist."
2144   (setq gnus-category-predicate-cache nil
2145         gnus-category-group-cache nil)
2146   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
2147   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
2148     ;; This prin1 is temporary.  It exists so that people can revert
2149     ;; to an earlier version of gnus-agent.
2150     (prin1 (mapcar (lambda (c)
2151               (list (car c)
2152                     (cdr (assoc 'agent-predicate c))
2153                     (cdr (assoc 'agent-score-file c))
2154                     (cdr (assoc 'agent-groups c))))
2155                    gnus-category-alist)
2156            (current-buffer))
2157     (newline)
2158     (prin1 gnus-category-alist (current-buffer))))
2159
2160 (defun gnus-category-edit-predicate (category)
2161   "Edit the predicate for CATEGORY."
2162   (interactive (list (gnus-category-name)))
2163   (let ((info (assq category gnus-category-alist)))
2164     (gnus-edit-form
2165      (gnus-agent-cat-predicate info)
2166      (format "Editing the select predicate for category %s" category)
2167      `(lambda (predicate)
2168         ;; Avoid run-time execution of setf form
2169         ;; (setf (gnus-agent-cat-predicate (assq ',category gnus-category-alist))
2170         ;;       predicate)
2171         ;; use its expansion instead:
2172         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2173                                      'agent-predicate predicate)
2174
2175         (gnus-category-write)
2176         (gnus-category-list)))))
2177
2178 (defun gnus-category-edit-score (category)
2179   "Edit the score expression for CATEGORY."
2180   (interactive (list (gnus-category-name)))
2181   (let ((info (assq category gnus-category-alist)))
2182     (gnus-edit-form
2183      (gnus-agent-cat-score-file info)
2184      (format "Editing the score expression for category %s" category)
2185      `(lambda (score-file)
2186         ;; Avoid run-time execution of setf form
2187         ;; (setf (gnus-agent-cat-score-file (assq ',category gnus-category-alist))
2188         ;;       score-file)
2189         ;; use its expansion instead:
2190         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2191                                      'agent-score-file score-file)
2192
2193         (gnus-category-write)
2194         (gnus-category-list)))))
2195
2196 (defun gnus-category-edit-groups (category)
2197   "Edit the group list for CATEGORY."
2198   (interactive (list (gnus-category-name)))
2199   (let ((info (assq category gnus-category-alist)))
2200     (gnus-edit-form
2201      (gnus-agent-cat-groups info)
2202      (format "Editing the group list for category %s" category)
2203      `(lambda (groups)
2204         ;; Avoid run-time execution of setf form
2205         ;; (setf (gnus-agent-cat-groups (assq ',category gnus-category-alist))
2206         ;;       groups)
2207         ;; use its expansion instead:
2208         (gnus-agent-set-cat-groups (assq ',category gnus-category-alist)
2209                                    groups)
2210
2211         (gnus-category-write)
2212         (gnus-category-list)))))
2213
2214 (defun gnus-category-kill (category)
2215   "Kill the current category."
2216   (interactive (list (gnus-category-name)))
2217   (let ((info (assq category gnus-category-alist))
2218         (buffer-read-only nil))
2219     (gnus-delete-line)
2220     (setq gnus-category-alist (delq info gnus-category-alist))
2221     (gnus-category-write)))
2222
2223 (defun gnus-category-copy (category to)
2224   "Copy the current category."
2225   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
2226   (let ((info (assq category gnus-category-alist)))
2227     (push (let ((newcat (gnus-copy-sequence info)))
2228             (setf (gnus-agent-cat-name newcat) to)
2229             (setf (gnus-agent-cat-groups newcat) nil)
2230             newcat)
2231           gnus-category-alist)
2232     (gnus-category-write)
2233     (gnus-category-list)))
2234
2235 (defun gnus-category-add (category)
2236   "Create a new category."
2237   (interactive "SCategory name: ")
2238   (when (assq category gnus-category-alist)
2239     (error "Category %s already exists" category))
2240   (push (gnus-agent-cat-make category)
2241         gnus-category-alist)
2242   (gnus-category-write)
2243   (gnus-category-list))
2244
2245 (defun gnus-category-list ()
2246   "List all categories."
2247   (interactive)
2248   (gnus-category-prepare))
2249
2250 (defun gnus-category-exit ()
2251   "Return to the group buffer."
2252   (interactive)
2253   (kill-buffer (current-buffer))
2254   (gnus-configure-windows 'group t))
2255
2256 ;; To avoid having 8-bit characters in the source file.
2257 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
2258
2259 (defvar gnus-category-predicate-alist
2260   '((spam . gnus-agent-spam-p)
2261     (short . gnus-agent-short-p)
2262     (long . gnus-agent-long-p)
2263     (low . gnus-agent-low-scored-p)
2264     (high . gnus-agent-high-scored-p)
2265     (read . gnus-agent-read-p)
2266     (true . gnus-agent-true)
2267     (false . gnus-agent-false))
2268   "Mapping from short score predicate symbols to predicate functions.")
2269
2270 (defun gnus-agent-spam-p ()
2271   "Say whether an article is spam or not."
2272   (unless gnus-agent-spam-hashtb
2273     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
2274   (if (not (equal (mail-header-references gnus-headers) ""))
2275       nil
2276     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
2277       (prog1
2278           (gnus-gethash string gnus-agent-spam-hashtb)
2279         (gnus-sethash string t gnus-agent-spam-hashtb)))))
2280
2281 (defun gnus-agent-short-p ()
2282   "Say whether an article is short or not."
2283   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
2284
2285 (defun gnus-agent-long-p ()
2286   "Say whether an article is long or not."
2287   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
2288
2289 (defun gnus-agent-low-scored-p ()
2290   "Say whether an article has a low score or not."
2291   (< gnus-score gnus-agent-low-score))
2292
2293 (defun gnus-agent-high-scored-p ()
2294   "Say whether an article has a high score or not."
2295   (> gnus-score gnus-agent-high-score))
2296
2297 (defun gnus-agent-read-p ()
2298   "Say whether an article is read or not."
2299   (gnus-member-of-range (mail-header-number gnus-headers)
2300                         (gnus-info-read (gnus-get-info gnus-newsgroup-name))))
2301
2302 (defun gnus-category-make-function (predicate)
2303   "Make a function from PREDICATE."
2304   (let ((func (gnus-category-make-function-1 predicate)))
2305     (if (and (= (length func) 1)
2306              (symbolp (car func)))
2307         (car func)
2308       (gnus-byte-compile `(lambda () ,func)))))
2309
2310 (defun gnus-agent-true ()
2311   "Return t."
2312   t)
2313
2314 (defun gnus-agent-false ()
2315   "Return nil."
2316   nil)
2317
2318 (defun gnus-category-make-function-1 (predicate)
2319   "Make a function from PREDICATE."
2320   (cond
2321    ;; Functions are just returned as is.
2322    ((or (symbolp predicate)
2323         (gnus-functionp predicate))
2324     `(,(or (cdr (assq predicate gnus-category-predicate-alist))
2325            predicate)))
2326    ;; More complex predicate.
2327    ((consp predicate)
2328     `(,(cond
2329         ((memq (car predicate) '(& and))
2330          'and)
2331         ((memq (car predicate) '(| or))
2332          'or)
2333         ((memq (car predicate) gnus-category-not)
2334          'not))
2335       ,@(mapcar 'gnus-category-make-function-1 (cdr predicate))))
2336    (t
2337     (error "Unknown predicate type: %s" predicate))))
2338
2339 (defun gnus-get-predicate (predicate)
2340   "Return the function implementing PREDICATE."
2341   (or (cdr (assoc predicate gnus-category-predicate-cache))
2342       (let ((func (gnus-category-make-function predicate)))
2343         (setq gnus-category-predicate-cache
2344               (nconc gnus-category-predicate-cache
2345                      (list (cons predicate func))))
2346         func)))
2347
2348 (defun gnus-predicate-implies-unread (predicate)
2349   "Say whether PREDICATE implies unread articles only.
2350 It is okay to miss some cases, but there must be no false positives.
2351 That is, if this function returns true, then indeed the predicate must
2352 return only unread articles."
2353   (gnus-function-implies-unread-1 (gnus-category-make-function predicate)))
2354
2355 (defun gnus-function-implies-unread-1 (function)
2356   (cond ((eq function (symbol-function 'gnus-agent-read-p))
2357          nil)
2358         ((not function)
2359          nil)
2360         ((symbolp function)
2361          'ignore)
2362         ((memq (car function) '(or and not))
2363          (apply (car function)
2364                 (mapcar 'gnus-function-implies-unread-1 (cdr function))))
2365         (t
2366          (error "Unknown function: %s" function))))
2367
2368 (defun gnus-group-category (group)
2369   "Return the category GROUP belongs to."
2370   (unless gnus-category-group-cache
2371     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
2372     (let ((cs gnus-category-alist)
2373           groups cat)
2374       (while (setq cat (pop cs))
2375         (setq groups (gnus-agent-cat-groups cat))
2376         (while groups
2377           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
2378   (or (gnus-gethash group gnus-category-group-cache)
2379       (assq 'default gnus-category-alist)))
2380
2381 (defun gnus-agent-expire-group (group &optional articles force)
2382   "Expire all old articles in GROUP.
2383 If you want to force expiring of certain articles, this function can
2384 take ARTICLES, and FORCE parameters as well.
2385
2386 The articles on which the expiration process runs are selected as follows:
2387   if ARTICLES is null, all read and unmarked articles.
2388   if ARTICLES is t, all articles.
2389   if ARTICLES is a list, just those articles.
2390 FORCE is equivalent to setting the expiration predicates to true."
2391   (interactive
2392    (list (let ((def (or (gnus-group-group-name)
2393                         gnus-newsgroup-name)))
2394            (let ((select (read-string (if def
2395                                           (concat "Group Name ("
2396                                                   def "): ")
2397                                         "Group Name: "))))
2398              (if (and (equal "" select)
2399                       def)
2400                  def
2401                select)))))
2402
2403   (if (not group)
2404       (gnus-agent-expire articles group force)
2405     (if (or (not (eq articles t))
2406             (yes-or-no-p
2407              (concat "Are you sure that you want to "
2408                      "expire all articles in " group ".")))
2409         (let ((gnus-command-method (gnus-find-method-for-group group))
2410               (overview (gnus-get-buffer-create " *expire overview*"))
2411               orig)
2412           (unwind-protect
2413               (when (file-exists-p (gnus-agent-lib-file "active"))
2414                 (with-temp-buffer
2415                   (nnheader-insert-file-contents
2416                    (gnus-agent-lib-file "active"))
2417                   (gnus-active-to-gnus-format
2418                    gnus-command-method
2419                    (setq orig (gnus-make-hashtable
2420                                (count-lines (point-min) (point-max))))))
2421                 (save-excursion
2422                   (gnus-agent-expire-group-1
2423                    group overview (gnus-gethash-safe group orig)
2424                    articles force)))
2425             (kill-buffer overview))))
2426     (gnus-message 4 "Expiry...done")))
2427
2428 (defun gnus-agent-expire-group-1 (group overview active articles force)
2429   ;; Internal function - requires caller to have set
2430   ;; gnus-command-method, initialized overview buffer, and to have
2431   ;; provided a non-nil active
2432   (interactive)
2433
2434   (if (eq 'DISABLE (gnus-agent-find-parameter group 'agent-enable-expiration))
2435       (gnus-message 5 "Expiry skipping over %s" group)
2436     (gnus-message 5 "Expiring articles in %s" group)
2437     (gnus-agent-load-alist group)
2438     (let* ((info (gnus-get-info group))
2439            (alist gnus-agent-article-alist)
2440            (dir (concat
2441                  (gnus-agent-directory)
2442                  (gnus-agent-group-path group)
2443                  "/"))
2444            (day (- (time-to-days (current-time))
2445                    (gnus-agent-find-parameter group 'agent-days-until-old)))
2446            (specials (if (and alist
2447                               (not force))
2448                          ;; This could be a bit of a problem.  I need to
2449                          ;; keep the last article to avoid refetching
2450                          ;; headers when using nntp in the backend.  At
2451                          ;; the same time, if someone uses a backend
2452                          ;; that supports article moving then I may have
2453                          ;; to remove the last article to complete the
2454                          ;; move.  Right now, I'm going to assume that
2455                          ;; FORCE overrides specials.
2456                          (list (caar (last alist)))))
2457            (unreads ;; Articles that are excluded from the
2458             ;; expiration process
2459             (cond (gnus-agent-expire-all
2460                    ;; All articles are marked read by global decree
2461                    nil)
2462                   ((eq articles t)
2463                    ;; All articles are marked read by function
2464                    ;; parameter
2465                    nil)
2466                   ((not articles)
2467                    ;; Unread articles are marked protected from
2468                    ;; expiration Don't call
2469                    ;; gnus-list-of-unread-articles as it returns
2470                    ;; articles that have not been fetched into the
2471                    ;; agent.
2472                    (ignore-errors
2473                     (gnus-agent-unread-articles group)))
2474                   (t
2475                    ;; All articles EXCEPT those named by the caller
2476                    ;; are protected from expiration
2477                    (gnus-sorted-difference
2478                     (gnus-uncompress-range
2479                      (cons (caar alist)
2480                            (caar (last alist))))
2481                     (sort articles '<)))))
2482            (marked ;; More articles that are exluded from the
2483             ;; expiration process
2484             (cond (gnus-agent-expire-all
2485                    ;; All articles are unmarked by global decree
2486                    nil)
2487                   ((eq articles t)
2488                    ;; All articles are unmarked by function
2489                    ;; parameter
2490                    nil)
2491                   (articles
2492                    ;; All articles may as well be unmarked as the
2493                    ;; unreads list already names the articles we are
2494                    ;; going to keep
2495                    nil)
2496                   (t
2497                    ;; Ticked and/or dormant articles are excluded
2498                    ;; from expiration
2499                    (nconc
2500                     (gnus-uncompress-range
2501                      (cdr (assq 'tick (gnus-info-marks info))))
2502                     (gnus-uncompress-range
2503                      (cdr (assq 'dormant
2504                                 (gnus-info-marks info))))))))
2505            (nov-file (concat dir ".overview"))
2506            (cnt 0)
2507            (completed -1)
2508            dlist
2509            type)
2510
2511       ;; The normal article alist contains elements that look like
2512       ;; (article# .  fetch_date) I need to combine other
2513       ;; information with this list.  For example, a flag indicating
2514       ;; that a particular article MUST BE KEPT.  To do this, I'm
2515       ;; going to transform the elements to look like (article#
2516       ;; fetch_date keep_flag NOV_entry_marker) Later, I'll reverse
2517       ;; the process to generate the expired article alist.
2518
2519       ;; Convert the alist elements to (article# fetch_date nil
2520       ;; nil).
2521       (setq dlist (mapcar (lambda (e)
2522                             (list (car e) (cdr e) nil nil)) alist))
2523
2524       ;; Convert the keep lists to elements that look like (article#
2525       ;; nil keep_flag nil) then append it to the expanded dlist
2526       ;; These statements are sorted by ascending precidence of the
2527       ;; keep_flag.
2528       (setq dlist (nconc dlist
2529                          (mapcar (lambda (e)
2530                                    (list e nil 'unread  nil))
2531                                  unreads)))
2532       (setq dlist (nconc dlist
2533                          (mapcar (lambda (e)
2534                                    (list e nil 'marked  nil))
2535                                  marked)))
2536       (setq dlist (nconc dlist
2537                          (mapcar (lambda (e)
2538                                    (list e nil 'special nil))
2539                                  specials)))
2540
2541       (set-buffer overview)
2542       (erase-buffer)
2543       (when (file-exists-p nov-file)
2544         (gnus-message 7 "gnus-agent-expire: Loading overview...")
2545         (nnheader-insert-file-contents nov-file)
2546         (goto-char (point-min))
2547
2548         (let (p)
2549           (while (< (setq p (point)) (point-max))
2550             (condition-case nil
2551                 ;; If I successfully read an integer (the plus zero
2552                 ;; ensures a numeric type), prepend a marker entry
2553                 ;; to the list
2554                 (push (list (+ 0 (read (current-buffer))) nil nil
2555                             (set-marker (make-marker) p))
2556                       dlist)
2557               (error
2558                (gnus-message 1 "gnus-agent-expire: read error \
2559 occurred when reading expression at %s in %s.  Skipping to next \
2560 line." (point) nov-file)))
2561             ;; Whether I succeeded, or failed, it doesn't matter.
2562             ;; Move to the next line then try again.
2563             (forward-line 1)))
2564         (gnus-message
2565          7 "gnus-agent-expire: Loading overview... Done"))
2566       (set-buffer-modified-p nil)
2567
2568       ;; At this point, all of the information is in dlist.  The
2569       ;; only problem is that much of it is spread across multiple
2570       ;; entries.  Sort then MERGE!!
2571       (gnus-message 7 "gnus-agent-expire: Sorting entries... ")
2572       ;; If two entries have the same article-number then sort by
2573       ;; ascending keep_flag.
2574       (let ((special 0)
2575             (marked 1)
2576             (unread 2))
2577         (setq dlist
2578               (sort dlist
2579                     (lambda (a b)
2580                       (cond ((< (nth 0 a) (nth 0 b))
2581                              t)
2582                             ((> (nth 0 a) (nth 0 b))
2583                              nil)
2584                             (t
2585                              (let ((a (or (symbol-value (nth 2 a))
2586                                           3))
2587                                    (b (or (symbol-value (nth 2 b))
2588                                           3)))
2589                                (<= a b))))))))
2590       (gnus-message 7 "gnus-agent-expire: Sorting entries... Done")
2591       (gnus-message 7 "gnus-agent-expire: Merging entries... ")
2592       (let ((dlist dlist))
2593         (while (cdr dlist)              ; I'm not at the end-of-list
2594           (if (eq (caar dlist) (caadr dlist))
2595               (let ((first (cdr (car dlist)))
2596                     (secnd (cdr (cadr dlist))))
2597                 (setcar first (or (car first)
2598                                   (car secnd))) ; fetch_date
2599                 (setq first (cdr first)
2600                       secnd (cdr secnd))
2601                 (setcar first (or (car first)
2602                                   (car secnd))) ; Keep_flag
2603                 (setq first (cdr first)
2604                       secnd (cdr secnd))
2605                 (setcar first (or (car first)
2606                                   (car secnd))) ; NOV_entry_marker
2607
2608                 (setcdr dlist (cddr dlist)))
2609             (setq dlist (cdr dlist)))))
2610       (gnus-message 7 "gnus-agent-expire: Merging entries... Done")
2611
2612       (let* ((len (float (length dlist)))
2613              (alist (list nil))
2614              (tail-alist alist))
2615         (while dlist
2616           (let ((new-completed (truncate (* 100.0
2617                                             (/ (setq cnt (1+ cnt))
2618                                                len)))))
2619             (when (> new-completed completed)
2620               (setq completed new-completed)
2621               (gnus-message 9 "%3d%% completed..."  completed)))
2622           (let* ((entry          (car dlist))
2623                  (article-number (nth 0 entry))
2624                  (fetch-date     (nth 1 entry))
2625                  (keep           (nth 2 entry))
2626                  (marker         (nth 3 entry)))
2627
2628             (cond
2629              ;; Kept articles are unread, marked, or special.
2630              (keep
2631               (gnus-message 10
2632                             "gnus-agent-expire: Article %d: Kept %s article."
2633                             article-number keep)
2634               (when fetch-date
2635                 (unless (file-exists-p
2636                          (concat dir (number-to-string
2637                                       article-number)))
2638                   (setf (nth 1 entry) nil)
2639                   (gnus-message 3 "gnus-agent-expire cleared \
2640 download flag on article %d as the cached article file is missing."
2641                                 (caar dlist)))
2642                 (unless marker
2643                   (gnus-message 1 "gnus-agent-expire detected a \
2644 missing NOV entry.  Run gnus-agent-regenerate-group to restore it.")))
2645               (gnus-agent-append-to-list
2646                tail-alist
2647                (cons article-number fetch-date)))
2648
2649              ;; The following articles are READ, UNMARKED, and
2650              ;; ORDINARY.  See if they can be EXPIRED!!!
2651              ((setq type
2652                     (cond
2653                      ((not (integerp fetch-date))
2654                       'read) ;; never fetched article (may expire
2655                      ;; right now)
2656                      ((not (file-exists-p
2657                             (concat dir (number-to-string
2658                                          article-number))))
2659                       (setf (nth 1 entry) nil)
2660                       'externally-expired) ;; Can't find the cached
2661                      ;; article.  Handle case
2662                      ;; as though this article
2663                      ;; was never fetched.
2664
2665                      ;; We now have the arrival day, so we see
2666                      ;; whether it's old enough to be expired.
2667                      ((< fetch-date day)
2668                       'expired)
2669                      (force
2670                       'forced)))
2671
2672               ;; I found some reason to expire this entry.
2673
2674               (let ((actions nil))
2675                 (when (memq type '(forced expired))
2676                   (ignore-errors        ; Just being paranoid.
2677                    (delete-file (concat dir (number-to-string
2678                                              article-number)))
2679                    (push "expired cached article" actions))
2680                   (setf (nth 1 entry) nil)
2681                   )
2682
2683                 (when marker
2684                   (push "NOV entry removed" actions)
2685                   (goto-char marker)
2686                   (gnus-delete-line))
2687
2688                 ;; If considering all articles is set, I can only
2689                 ;; expire article IDs that are no longer in the
2690                 ;; active range.
2691                 (if (and gnus-agent-consider-all-articles
2692                          (>= article-number (car active)))
2693                     ;; I have to keep this ID in the alist
2694                     (gnus-agent-append-to-list
2695                      tail-alist (cons article-number fetch-date))
2696                   (push (format "Removed %s article number from \
2697 article alist" type) actions))
2698
2699                 (gnus-message 7 "gnus-agent-expire: Article %d: %s"
2700                               article-number
2701                               (mapconcat 'identity actions ", "))))
2702              (t
2703               (gnus-message
2704                10 "gnus-agent-expire: Article %d: Article kept as \
2705 expiration tests failed." article-number)
2706               (gnus-agent-append-to-list
2707                tail-alist (cons article-number fetch-date)))
2708              )
2709
2710             ;; Clean up markers as I want to recycle this buffer
2711             ;; over several groups.
2712             (when marker
2713               (set-marker marker nil))
2714
2715             (setq dlist (cdr dlist))))
2716
2717         (setq alist (cdr alist))
2718
2719         (let ((inhibit-quit t))
2720           (unless (equal alist gnus-agent-article-alist)
2721             (setq gnus-agent-article-alist alist)
2722             (gnus-agent-save-alist group))
2723
2724           (when (buffer-modified-p)
2725             (gnus-make-directory dir)
2726             (write-region-as-coding-system gnus-agent-file-coding-system
2727                                            (point-min) (point-max) nov-file
2728                                            nil 'silent)
2729             ;; clear the modified flag as that I'm not confused by
2730             ;; its status on the next pass through this routine.
2731             (set-buffer-modified-p nil))
2732
2733           (when (eq articles t)
2734             (gnus-summary-update-info)))))))
2735
2736 (defun gnus-agent-expire (&optional articles group force)
2737   "Expire all old articles.
2738 If you want to force expiring of certain articles, this function can
2739 take ARTICLES, GROUP and FORCE parameters as well.
2740
2741 The articles on which the expiration process runs are selected as follows:
2742   if ARTICLES is null, all read and unmarked articles.
2743   if ARTICLES is t, all articles.
2744   if ARTICLES is a list, just those articles.
2745 Setting GROUP will limit expiration to that group.
2746 FORCE is equivalent to setting the expiration predicates to true."
2747   (interactive)
2748   
2749   (if group
2750       (gnus-agent-expire-group group articles force)
2751     (if (or (not (eq articles t))
2752             (yes-or-no-p "Are you sure that you want to expire all \
2753 articles in every agentized group."))
2754         (let ((methods gnus-agent-covered-methods)
2755               gnus-command-method overview orig)
2756           (setq overview (gnus-get-buffer-create " *expire overview*"))
2757           (unwind-protect
2758               (while (setq gnus-command-method (pop methods))
2759                 (when (file-exists-p (gnus-agent-lib-file "active"))
2760                   (with-temp-buffer
2761                     (nnheader-insert-file-contents
2762                      (gnus-agent-lib-file "active"))
2763                     (gnus-active-to-gnus-format
2764                      gnus-command-method
2765                      (setq orig (gnus-make-hashtable
2766                                  (count-lines (point-min) (point-max))))))
2767                   (dolist (expiring-group (gnus-groups-from-server
2768                                            gnus-command-method))
2769                     (let* ((active
2770                             (gnus-gethash-safe expiring-group orig)))
2771                                         
2772                       (when active
2773                         (save-excursion
2774                           (gnus-agent-expire-group-1
2775                            expiring-group overview active articles force)))))))
2776             (kill-buffer overview))
2777           (gnus-message 4 "Expiry...done")))))
2778
2779 ;;;###autoload
2780 (defun gnus-agent-batch ()
2781   "Start Gnus, send queue and fetch session."
2782   (interactive)
2783   (let ((init-file-user "")
2784         (gnus-always-read-dribble-file t))
2785     (gnus))
2786   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
2787     (gnus-group-send-queue)
2788     (gnus-agent-fetch-session)))
2789
2790 (defun gnus-agent-unread-articles (group)
2791   (let* ((read (gnus-info-read (gnus-get-info group)))
2792          (known (gnus-agent-load-alist group))
2793          (unread (list nil))
2794          (tail-unread unread))
2795     (while (and known read)
2796       (let ((candidate (car (pop known))))
2797         (while (let* ((range (car read))
2798                       (min   (if (numberp range) range (car range)))
2799                       (max   (if (numberp range) range (cdr range))))
2800                  (cond ((or (not min)
2801                             (< candidate min))
2802                         (gnus-agent-append-to-list tail-unread candidate)
2803                         nil)
2804                        ((> candidate max)
2805                         (pop read)))))))
2806     (while known
2807       (gnus-agent-append-to-list tail-unread (car (pop known))))
2808     (cdr unread)))
2809
2810 (defun gnus-agent-uncached-articles (articles group &optional cached-header)
2811   "Restrict ARTICLES to numbers already fetched.
2812 Returns a sublist of ARTICLES that excludes thos article ids in GROUP
2813 that have already been fetched.
2814 If CACHED-HEADER is nil, articles are only excluded if the article itself
2815 has been fetched."
2816
2817   ;; Logically equivalent to: (gnus-sorted-difference articles (mapcar
2818   ;; 'car gnus-agent-article-alist))
2819
2820   ;; Functionally, I don't need to construct a temp list using mapcar.
2821
2822   (if (and (or gnus-agent-cache (not gnus-plugged))
2823            (gnus-agent-load-alist group))
2824     (let* ((ref gnus-agent-article-alist)
2825            (arts articles)
2826            (uncached (list nil))
2827            (tail-uncached uncached))
2828       (while (and ref arts)
2829         (let ((v1 (car arts))
2830               (v2 (caar ref)))
2831           (cond ((< v1 v2) ; v1 does not appear in the reference list
2832                  (gnus-agent-append-to-list tail-uncached v1)
2833                  (pop arts))
2834                 ((= v1 v2)
2835                  (unless (or cached-header (cdar ref)) ; v1 is already cached
2836                    (gnus-agent-append-to-list tail-uncached v1))
2837                  (pop arts)
2838                  (pop ref))
2839                 (t ; reference article (v2) preceeds the list being filtered
2840                  (pop ref)))))
2841       (while arts
2842         (gnus-agent-append-to-list tail-uncached (pop arts)))
2843       (cdr uncached))
2844     ;; if gnus-agent-load-alist fails, no articles are cached.
2845     articles))
2846
2847 (defun gnus-agent-retrieve-headers (articles group &optional fetch-old)
2848   (save-excursion
2849     (gnus-agent-create-buffer)
2850     (let ((gnus-decode-encoded-word-function 'identity)
2851           (file (gnus-agent-article-name ".overview" group))
2852           cached-articles uncached-articles)
2853       (gnus-make-directory (nnheader-translate-file-chars
2854                             (file-name-directory file) t))
2855
2856       ;; Populate temp buffer with known headers
2857       (when (file-exists-p file)
2858         (with-current-buffer gnus-agent-overview-buffer
2859           (erase-buffer)
2860           (let ((nnheader-file-coding-system
2861                  gnus-agent-file-coding-system))
2862             (nnheader-insert-nov-file file (car articles)))))
2863
2864       (if (setq uncached-articles (gnus-agent-uncached-articles articles group
2865                                                                 t))
2866           (progn
2867             ;; Populate nntp-server-buffer with uncached headers
2868             (set-buffer nntp-server-buffer)
2869             (erase-buffer)
2870             (cond ((not (eq 'nov (let (gnus-agent) ; Turn off agent
2871                                    (gnus-retrieve-headers
2872                                     uncached-articles group fetch-old))))
2873                    (nnvirtual-convert-headers))
2874                   ((eq 'nntp (car gnus-current-select-method))
2875                    ;; The author of gnus-get-newsgroup-headers-xover
2876                    ;; reports that the XOVER command is commonly
2877                    ;; unreliable. The problem is that recently
2878                    ;; posted articles may not be entered into the
2879                    ;; NOV database in time to respond to my XOVER
2880                    ;; query.
2881                    ;;
2882                    ;; I'm going to use his assumption that the NOV
2883                    ;; database is updated in order of ascending
2884                    ;; article ID.  Therefore, a response containing
2885                    ;; article ID N implies that all articles from 1
2886                    ;; to N-1 are up-to-date.  Therefore, missing
2887                    ;; articles in that range have expired.
2888
2889                    (set-buffer nntp-server-buffer)
2890                    (let* ((fetched-articles (list nil))
2891                           (tail-fetched-articles fetched-articles)
2892                           (min (cond ((numberp fetch-old)
2893                                       (max 1 (- (car articles) fetch-old)))
2894                                      (fetch-old
2895                                       1)
2896                                      (t
2897                                       (car articles))))
2898                           (max (car (last articles))))
2899
2900                      ;; Get the list of articles that were fetched
2901                      (goto-char (point-min))
2902                      (let ((pm (point-max)))
2903                        (while (< (point) pm)
2904                          (when (looking-at "[0-9]+\t")
2905                            (gnus-agent-append-to-list
2906                             tail-fetched-articles
2907                             (read (current-buffer))))
2908                          (forward-line 1)))
2909
2910                      ;; Clip this list to the headers that will
2911                      ;; actually be returned
2912                      (setq fetched-articles (gnus-list-range-intersection
2913                                              (cdr fetched-articles)
2914                                              (cons min max)))
2915
2916                      ;; Clip the uncached articles list to exclude
2917                      ;; IDs after the last FETCHED header.  The
2918                      ;; excluded IDs may be fetchable using HEAD.
2919                      (if (car tail-fetched-articles)
2920                          (setq uncached-articles
2921                                (gnus-list-range-intersection
2922                                 uncached-articles
2923                                 (cons (car uncached-articles)
2924                                       (car tail-fetched-articles)))))
2925
2926                      ;; Create the list of articles that were
2927                      ;; "successfully" fetched.  Success, in this
2928                      ;; case, means that the ID should not be
2929                      ;; fetched again.  In the case of an expired
2930                      ;; article, the header will not be fetched.
2931                      (setq uncached-articles
2932                            (gnus-sorted-nunion fetched-articles
2933                                                uncached-articles))
2934                      )))
2935
2936             ;; Erase the temp buffer
2937             (set-buffer gnus-agent-overview-buffer)
2938             (erase-buffer)
2939
2940             ;; Copy the nntp-server-buffer to the temp buffer
2941             (set-buffer nntp-server-buffer)
2942             (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
2943
2944             ;; Merge the temp buffer with the known headers (found on
2945             ;; disk in FILE) into the nntp-server-buffer
2946             (when (and uncached-articles (file-exists-p file))
2947               (gnus-agent-braid-nov group uncached-articles file))
2948
2949             ;; Save the new set of known headers to FILE
2950             (set-buffer nntp-server-buffer)
2951             (gnus-agent-check-overview-buffer)
2952             (write-region-as-coding-system
2953              gnus-agent-file-coding-system
2954              (point-min) (point-max) file nil 'silent)
2955
2956             ;; Update the group's article alist to include the newly
2957             ;; fetched articles.
2958             (gnus-agent-load-alist group)
2959             (gnus-agent-save-alist group uncached-articles nil)
2960             )
2961
2962         ;; Copy the temp buffer to the nntp-server-buffer
2963         (set-buffer nntp-server-buffer)
2964         (erase-buffer)
2965         (insert-buffer-substring gnus-agent-overview-buffer)))
2966
2967     (if (and fetch-old
2968              (not (numberp fetch-old)))
2969         t                               ; Don't remove anything.
2970       (nnheader-nov-delete-outside-range
2971        (if fetch-old (max 1 (- (car articles) fetch-old))
2972          (car articles))
2973        (car (last articles)))
2974       t)
2975
2976     'nov))
2977
2978 (defun gnus-agent-request-article (article group)
2979   "Retrieve ARTICLE in GROUP from the agent cache."
2980   (when (and gnus-agent
2981              (or gnus-agent-cache
2982                  (not gnus-plugged))
2983              (numberp article))
2984     (let* ((gnus-command-method (gnus-find-method-for-group group))
2985            (file (concat
2986                   (gnus-agent-directory)
2987                   (gnus-agent-group-path group) "/"
2988                   (number-to-string article)))
2989            (buffer-read-only nil))
2990       (when (and (file-exists-p file)
2991                  (> (nth 7 (file-attributes file)) 0))
2992         (erase-buffer)
2993         (gnus-kill-all-overlays)
2994         (insert-file-contents-as-coding-system gnus-cache-coding-system file)
2995         t))))
2996
2997 (defun gnus-agent-regenerate-group (group &optional reread)
2998   "Regenerate GROUP.
2999 If REREAD is t, all articles in the .overview are marked as unread.
3000 If REREAD is not nil, downloaded articles are marked as unread."
3001   (interactive
3002    (list (let ((def (or (gnus-group-group-name)
3003                         gnus-newsgroup-name)))
3004            (let ((select (read-string (if def
3005                                           (concat "Group Name ("
3006                                                   def "): ")
3007                                         "Group Name: "))))
3008              (if (and (equal "" select)
3009                       def)
3010                  def
3011                select)))
3012          (intern-soft
3013           (read-string
3014            "Reread (nil)? (t=>all, nil=>none, some=>all downloaded): "))))
3015   (gnus-message 5 "Regenerating in %s" group)
3016   (let* ((gnus-command-method (or gnus-command-method
3017                                   (gnus-find-method-for-group group)))
3018          (file (gnus-agent-article-name ".overview" group))
3019          (dir (file-name-directory file))
3020          point
3021          (downloaded (if (file-exists-p dir)
3022                          (sort (mapcar (lambda (name) (string-to-int name))
3023                                        (directory-files dir nil "^[0-9]+$" t))
3024                                '>)
3025                        (progn (gnus-make-directory dir) nil)))
3026          dl nov-arts
3027          alist header
3028          regenerated)
3029
3030     (mm-with-unibyte-buffer
3031      (if (file-exists-p file)
3032          (let ((nnheader-file-coding-system
3033                 gnus-agent-file-coding-system))
3034            (nnheader-insert-file-contents file)))
3035      (set-buffer-modified-p nil)
3036
3037      ;; Load the article IDs found in the overview file.  As a
3038      ;; side-effect, validate the file contents.
3039      (let ((load t))
3040        (while load
3041          (setq load nil)
3042          (goto-char (point-min))
3043          (while (< (point) (point-max))
3044            (cond ((and (looking-at "[0-9]+\t")
3045                        (<= (- (match-end 0) (match-beginning 0)) 9))
3046                   (push (read (current-buffer)) nov-arts)
3047                   (forward-line 1)
3048                   (let ((l1 (car nov-arts))
3049                         (l2 (cadr nov-arts)))
3050                     (cond ((not l2)
3051                            nil)
3052                           ((< l1 l2)
3053                            (gnus-message 3 "gnus-agent-regenerate-group: NOV\
3054  entries are NOT in ascending order.")
3055                            ;; Don't sort now as I haven't verified
3056                            ;; that every line begins with a number
3057                            (setq load t))
3058                           ((= l1 l2)
3059                            (forward-line -1)
3060                            (gnus-message 4 "gnus-agent-regenerate-group: NOV\
3061  entries contained duplicate of article %s.      Duplicate deleted." l1)
3062                            (gnus-delete-line)
3063                            (pop nov-arts)))))
3064                  (t
3065                   (gnus-message 1 "gnus-agent-regenerate-group: NOV\
3066  entries contained line that did not begin with an article number.  Deleted\
3067  line.")
3068                   (gnus-delete-line))))
3069          (if load
3070              (progn
3071                (gnus-message 5 "gnus-agent-regenerate-group: Sorting NOV\
3072  entries into ascending order.")
3073                (sort-numeric-fields 1 (point-min) (point-max))
3074                     (setq nov-arts nil)))))
3075      (gnus-agent-check-overview-buffer)
3076
3077      ;; Construct a new article alist whose nodes match every header
3078      ;; in the .overview file.  As a side-effect, missing headers are
3079      ;; reconstructed from the downloaded article file.
3080      (while (or downloaded nov-arts)
3081        (cond ((and downloaded
3082                    (or (not nov-arts)
3083                        (> (car downloaded) (car nov-arts))))
3084               ;; This entry is missing from the overview file
3085               (gnus-message 3 "Regenerating NOV %s %d..." group
3086                             (car downloaded))
3087               (let ((file (concat dir (number-to-string (car downloaded)))))
3088                 (mm-with-unibyte-buffer
3089                  (nnheader-insert-file-contents file)
3090                  (nnheader-remove-body)
3091                  (setq header (nnheader-parse-naked-head)))
3092                 (mail-header-set-number header (car downloaded))
3093                 (if nov-arts
3094                     (let ((key (concat "^" (int-to-string (car nov-arts))
3095                                        "\t")))
3096                       (or (re-search-backward key nil t)
3097                           (re-search-forward key))
3098                       (forward-line 1))
3099                   (goto-char (point-min)))
3100                 (nnheader-insert-nov header))
3101               (setq nov-arts (cons (car downloaded) nov-arts)))
3102              ((eq (car downloaded) (car nov-arts))
3103               ;; This entry in the overview has been downloaded
3104               (push (cons (car downloaded)
3105                           (time-to-days
3106                            (nth 5 (file-attributes
3107                                    (concat dir (number-to-string
3108                                                 (car downloaded))))))) alist)
3109               (pop downloaded)
3110               (pop nov-arts))
3111              (t
3112               ;; This entry in the overview has not been downloaded
3113               (push (cons (car nov-arts) nil) alist)
3114               (pop nov-arts))))
3115
3116      ;; When gnus-agent-consider-all-articles is set,
3117      ;; gnus-agent-regenerate-group should NOT remove article IDs from
3118      ;; the alist.  Those IDs serve as markers to indicate that an
3119      ;; attempt has been made to fetch that article's header.
3120
3121      ;; When gnus-agent-consider-all-articles is NOT set,
3122      ;; gnus-agent-regenerate-group can remove the article ID of every
3123      ;; article (with the exception of the last ID in the list - it's
3124      ;; special) that no longer appears in the overview.  In this
3125      ;; situtation, the last article ID in the list implies that it,
3126      ;; and every article ID preceeding it, have been fetched from the
3127      ;; server.
3128      (if gnus-agent-consider-all-articles
3129          ;; Restore all article IDs that were not found in the overview file.
3130          (let* ((n (cons nil alist))
3131                 (merged n)
3132                 (o (gnus-agent-load-alist group)))
3133            (while o
3134              (let ((nID (caadr n))
3135                    (oID (caar o)))
3136                (cond ((not nID)
3137                       (setq n (setcdr n (list (list oID))))
3138                       (pop o))
3139                      ((< oID nID)
3140                       (setcdr n (cons (list oID) (cdr n)))
3141                       (pop o))
3142                      ((= oID nID)
3143                       (pop o)
3144                       (pop n))
3145                      (t
3146                       (pop n)))))
3147            (setq alist (cdr merged)))
3148        ;; Restore the last article ID if it is not already in the new alist
3149        (let ((n (last alist))
3150              (o (last (gnus-agent-load-alist group))))
3151          (cond ((not o)
3152                 nil)
3153                ((not n)
3154                 (push (cons (caar o) nil) alist))
3155                ((< (caar n) (caar o))
3156                 (setcdr n (list (car o)))))))
3157
3158      (let ((inhibit-quit t))
3159      (if (setq regenerated (buffer-modified-p))
3160          (write-region-as-coding-system
3161           gnus-agent-file-coding-system
3162           (point-min) (point-max) file nil 'silent))
3163
3164     (setq regenerated (or regenerated
3165                           (and reread gnus-agent-article-alist)
3166                           (not (equal alist gnus-agent-article-alist)))
3167           )
3168
3169     (setq gnus-agent-article-alist alist)
3170
3171     (when regenerated
3172          (gnus-agent-save-alist group)))
3173      )
3174
3175     (when (and reread gnus-agent-article-alist)
3176       (gnus-make-ascending-articles-unread
3177        group
3178        (delq nil (mapcar (function (lambda (c)
3179                                      (cond ((eq reread t)
3180                                             (car c))
3181                                            ((cdr c)
3182                                             (car c)))))
3183                          gnus-agent-article-alist)))
3184
3185       (when (gnus-buffer-live-p gnus-group-buffer)
3186         (gnus-group-update-group group t)
3187         (sit-for 0))
3188       )
3189
3190     (gnus-message 5 nil)
3191     regenerated))
3192
3193 ;;;###autoload
3194 (defun gnus-agent-regenerate (&optional clean reread)
3195   "Regenerate all agent covered files.
3196 If CLEAN, don't read existing active files."
3197   (interactive "P")
3198   (let (regenerated)
3199     (gnus-message 4 "Regenerating Gnus agent files...")
3200     (dolist (gnus-command-method gnus-agent-covered-methods)
3201       (let ((active-file (gnus-agent-lib-file "active"))
3202             active-hashtb active-changed
3203             point)
3204         (gnus-make-directory (file-name-directory active-file))
3205         (if clean
3206             (setq active-hashtb (gnus-make-hashtable 1000))
3207           (mm-with-unibyte-buffer
3208            (if (file-exists-p active-file)
3209                (let ((nnheader-file-coding-system
3210                       gnus-agent-file-coding-system))
3211                  (nnheader-insert-file-contents active-file))
3212              (setq active-changed t))
3213            (gnus-active-to-gnus-format
3214             nil (setq active-hashtb
3215                       (gnus-make-hashtable
3216                        (count-lines (point-min) (point-max)))))))
3217         (dolist (group (gnus-groups-from-server gnus-command-method))
3218           (setq regenerated (or (gnus-agent-regenerate-group group reread)
3219                                 regenerated))
3220           (let ((min (or (caar gnus-agent-article-alist) 1))
3221                 (max (or (caar (last gnus-agent-article-alist)) 0))
3222                 (active (gnus-gethash-safe (gnus-group-real-name group)
3223                                            active-hashtb))
3224                 (read (gnus-info-read (gnus-get-info group))))
3225             (if (not active)
3226                 (progn
3227                   (setq active (cons min max)
3228                         active-changed t)
3229                   (gnus-sethash group active active-hashtb))
3230               (when (> (car active) min)
3231                 (setcar active min)
3232                 (setq active-changed t))
3233               (when (< (cdr active) max)
3234                 (setcdr active max)
3235                 (setq active-changed t)))))
3236         (when active-changed
3237           (setq regenerated t)
3238           (gnus-message 4 "Regenerate %s" active-file)
3239           (let ((nnmail-active-file-coding-system
3240                  gnus-agent-file-coding-system))
3241             (gnus-write-active-file active-file active-hashtb)))))
3242     (gnus-message 4 "Regenerating Gnus agent files...done")
3243     regenerated))
3244
3245 (defun gnus-agent-go-online (&optional force)
3246   "Switch servers into online status."
3247   (interactive (list t))
3248   (dolist (server gnus-opened-servers)
3249     (when (eq (nth 1 server) 'offline)
3250       (if (if (eq force 'ask)
3251               (gnus-y-or-n-p
3252                (format "Switch %s:%s into online status? "
3253                        (caar server) (cadar server)))
3254             force)
3255           (setcar (nthcdr 1 server) 'close)))))
3256
3257 (defun gnus-agent-toggle-group-plugged (group)
3258   "Toggle the status of the server of the current group."
3259   (interactive (list (gnus-group-group-name)))
3260   (let* ((method (gnus-find-method-for-group group))
3261          (status (cadr (assoc method gnus-opened-servers))))
3262     (if (eq status 'offline)
3263         (gnus-server-set-status method 'closed)
3264       (gnus-close-server method)
3265       (gnus-server-set-status method 'offline))
3266     (message "Turn %s:%s from %s to %s." (car method) (cadr method)
3267              (if (eq status 'offline) 'offline 'online)
3268              (if (eq status 'offline) 'online 'offline))))
3269
3270 (defun gnus-agent-group-covered-p (group)
3271   (member (gnus-group-method group)
3272           gnus-agent-covered-methods))
3273
3274 (add-hook 'gnus-group-prepare-hook
3275           (lambda ()
3276             'gnus-agent-do-once
3277
3278             (when (listp gnus-agent-expire-days)
3279               (beep)
3280               (beep)
3281               (gnus-message 1 "WARNING: gnus-agent-expire-days no longer\
3282  supports being set to a list.")(sleep-for 3)
3283               (gnus-message 1 "Change your configuration to set it to an\
3284  integer.")(sleep-for 3)
3285               (gnus-message 1 "I am now setting group parameters on each\
3286  group to match the configuration that the list offered.")
3287
3288               (save-excursion
3289                 (let ((groups (gnus-group-listed-groups)))
3290                   (while groups
3291                     (let* ((group (pop groups))
3292                            (days gnus-agent-expire-days)
3293                            (day (catch 'found
3294                                   (while days
3295                                     (when (eq 0 (string-match
3296                                                  (caar days)
3297                                                  group))
3298                                       (throw 'found (cadar days)))
3299                                     (pop days))
3300                                   nil)))
3301                       (when day
3302                         (gnus-group-set-parameter group 'agent-days-until-old
3303                                                   day))))))
3304
3305               (let ((h gnus-group-prepare-hook))
3306                 (while h
3307                   (let ((func (pop h)))
3308                     (when (and (listp func)
3309                                (eq (cadr (caddr func)) 'gnus-agent-do-once))
3310                       (remove-hook 'gnus-group-prepare-hook func)
3311                       (setq h nil)))))
3312
3313               (gnus-message 1 "I have finished setting group parameters on\
3314  each group. You may now customize your groups and/or topics to control the\
3315  agent."))))
3316
3317 (provide 'gnus-agent)
3318
3319 ;;; gnus-agent.el ends here