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