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