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