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