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