297c6540347eaacd20e6711e0f1d23386fc4fc0f
[gnus] / lisp / gnus-agent.el
1 ;;; gnus-agent.el --- unplugged support for Gnus
2
3 ;; Copyright (C) 1997-2012 Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; This file is part of GNU Emacs.
7
8 ;; GNU Emacs is free software: you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
12
13 ;; GNU Emacs is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 ;; GNU General Public License for more details.
17
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
20
21 ;;; Commentary:
22
23 ;;; Code:
24
25 (require 'gnus)
26 (require 'gnus-cache)
27 (require 'nnmail)
28 (require 'nnvirtual)
29 (require 'gnus-sum)
30 (require 'gnus-score)
31 (require 'gnus-srvr)
32 (require 'gnus-util)
33 (eval-when-compile
34   (if (featurep 'xemacs)
35       (require 'itimer)
36     (require 'timer))
37   (require 'cl))
38
39 (autoload 'gnus-server-update-server "gnus-srvr")
40 (autoload 'gnus-agent-customize-category "gnus-cus")
41
42 (defcustom gnus-agent-directory (nnheader-concat gnus-directory "agent/")
43   "Where the Gnus agent will store its files."
44   :group 'gnus-agent
45   :type 'directory)
46
47 (defcustom gnus-agent-plugged-hook nil
48   "Hook run when plugging into the network."
49   :group 'gnus-agent
50   :type 'hook)
51
52 (defcustom gnus-agent-unplugged-hook nil
53   "Hook run when unplugging from the network."
54   :group 'gnus-agent
55   :type 'hook)
56
57 (defcustom gnus-agent-fetched-hook nil
58   "Hook run when finished fetching articles."
59   :version "22.1"
60   :group 'gnus-agent
61   :type 'hook)
62
63 (defcustom gnus-agent-handle-level gnus-level-subscribed
64   "Groups on levels higher than this variable will be ignored by the Agent."
65   :group 'gnus-agent
66   :type 'integer)
67
68 (defcustom gnus-agent-expire-days 7
69   "Read articles older than this will be expired.
70 If you wish to disable Agent expiring, see `gnus-agent-enable-expiration'."
71   :group 'gnus-agent
72   :type '(number :tag "days"))
73
74 (defcustom gnus-agent-expire-all nil
75   "If non-nil, also expire unread, ticked and dormant articles.
76 If nil, only read articles will be expired."
77   :group 'gnus-agent
78   :type 'boolean)
79
80 (defcustom gnus-agent-group-mode-hook nil
81   "Hook run in Agent group minor modes."
82   :group 'gnus-agent
83   :type 'hook)
84
85 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
86 (when (featurep 'xemacs)
87   (add-hook 'gnus-agent-group-mode-hook 'gnus-xmas-agent-group-menu-add))
88
89 (defcustom gnus-agent-summary-mode-hook nil
90   "Hook run in Agent summary minor modes."
91   :group 'gnus-agent
92   :type 'hook)
93
94 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
95 (when (featurep 'xemacs)
96   (add-hook 'gnus-agent-summary-mode-hook 'gnus-xmas-agent-summary-menu-add))
97
98 (defcustom gnus-agent-server-mode-hook nil
99   "Hook run in Agent summary minor modes."
100   :group 'gnus-agent
101   :type 'hook)
102
103 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
104 (when (featurep 'xemacs)
105   (add-hook 'gnus-agent-server-mode-hook 'gnus-xmas-agent-server-menu-add))
106
107 (defcustom gnus-agent-confirmation-function 'y-or-n-p
108   "Function to confirm when error happens."
109   :version "21.1"
110   :group 'gnus-agent
111   :type 'function)
112
113 (defcustom gnus-agent-synchronize-flags nil
114   "Indicate if flags are synchronized when you plug in.
115 If this is `ask' the hook will query the user."
116   ;; If the default switches to something else than nil, then the function
117   ;; should be fixed not be exceedingly slow.  See 2005-09-20 ChangeLog entry.
118   :version "21.1"
119   :type '(choice (const :tag "Always" t)
120                  (const :tag "Never" nil)
121                  (const :tag "Ask" ask))
122   :group 'gnus-agent)
123
124 (defcustom gnus-agent-go-online 'ask
125   "Indicate if offline servers go online when you plug in.
126 If this is `ask' the hook will query the user."
127   :version "21.3"
128   :type '(choice (const :tag "Always" t)
129                  (const :tag "Never" nil)
130                  (const :tag "Ask" ask))
131   :group 'gnus-agent)
132
133 (defcustom gnus-agent-mark-unread-after-downloaded t
134   "Indicate whether to mark articles unread after downloaded."
135   :version "21.1"
136   :type 'boolean
137   :group 'gnus-agent)
138
139 (defcustom gnus-agent-download-marks '(download)
140   "Marks for downloading."
141   :version "21.1"
142   :type '(repeat (symbol :tag "Mark"))
143   :group 'gnus-agent)
144
145 (defcustom gnus-agent-consider-all-articles nil
146   "When non-nil, the agent will let the agent predicate decide
147 whether articles need to be downloaded or not, for all articles.  When
148 nil, the default, the agent will only let the predicate decide
149 whether unread articles are downloaded or not.  If you enable this,
150 groups with large active ranges may open slower and you may also want
151 to look into the agent expiry settings to block the expiration of
152 read articles as they would just be downloaded again."
153   :version "22.1"
154   :type 'boolean
155   :group 'gnus-agent)
156
157 (defcustom gnus-agent-max-fetch-size 10000000 ;; 10 Mb
158   "Chunk size for `gnus-agent-fetch-session'.
159 The function will split its article fetches into chunks smaller than
160 this limit."
161   :version "22.1"
162   :group 'gnus-agent
163   :type 'integer)
164
165 (defcustom gnus-agent-enable-expiration 'ENABLE
166   "The default expiration state for each group.
167 When set to ENABLE, the default, `gnus-agent-expire' will expire old
168 contents from a group's local storage.  This value may be overridden
169 to disable expiration in specific categories, topics, and groups.  Of
170 course, you could change gnus-agent-enable-expiration to DISABLE then
171 enable expiration per categories, topics, and groups."
172   :version "22.1"
173   :group 'gnus-agent
174   :type '(radio (const :format "Enable " ENABLE)
175                 (const :format "Disable " DISABLE)))
176
177 (defcustom gnus-agent-expire-unagentized-dirs t
178   "*Whether expiration should expire in unagentized directories.
179 Have gnus-agent-expire scan the directories under
180 \(gnus-agent-directory) for groups that are no longer agentized.
181 When found, offer to remove them."
182   :version "22.1"
183   :type 'boolean
184   :group 'gnus-agent)
185
186 (defcustom gnus-agent-auto-agentize-methods nil
187   "Initially, all servers from these methods are agentized.
188 The user may remove or add servers using the Server buffer.
189 See Info nodes `(gnus)Server Buffer', `(gnus)Agent Variables'."
190   :version "22.1"
191   :type '(repeat symbol)
192   :group 'gnus-agent)
193
194 (defcustom gnus-agent-queue-mail t
195   "Whether and when outgoing mail should be queued by the agent.
196 When `always', always queue outgoing mail.  When nil, never
197 queue.  Otherwise, queue if and only if unplugged."
198   :version "22.1"
199   :group 'gnus-agent
200   :type '(radio (const :format "Always" always)
201                 (const :format "Never" nil)
202                 (const :format "When unplugged" t)))
203
204 (defcustom gnus-agent-prompt-send-queue nil
205   "If non-nil, `gnus-group-send-queue' will prompt if called when unplugged."
206   :version "22.1"
207   :group 'gnus-agent
208   :type 'boolean)
209
210 (defcustom gnus-agent-article-alist-save-format 1
211   "Indicates whether to use compression(2), versus no
212 compression(1), when writing agentview files.  The compressed
213 files do save space but load times are 6-7 times higher.  A group
214 must be opened then closed for the agentview to be updated using
215 the new format."
216   ;; Wouldn't symbols instead numbers be nicer?  --rsteib
217   :version "22.1"
218   :group 'gnus-agent
219   :type '(radio (const :format "Compressed" 2)
220                 (const :format "Uncompressed" 1)))
221
222 ;;; Internal variables
223
224 (defvar gnus-agent-history-buffers nil)
225 (defvar gnus-agent-buffer-alist nil)
226 (defvar gnus-agent-article-alist nil
227   "An assoc list identifying the articles whose headers have been fetched.
228 If successfully fetched, these headers will be stored in the group's overview
229 file.  The key of each assoc pair is the article ID, the value of each assoc
230 pair is a flag indicating whether the identified article has been downloaded
231 \(gnus-agent-fetch-articles sets the value to the day of the download).
232 NOTES:
233 1) The last element of this list can not be expired as some
234    routines (for example, get-agent-fetch-headers) use the last
235    value to track which articles have had their headers retrieved.
236 2) The function `gnus-agent-regenerate' may destructively modify the value.")
237 (defvar gnus-agent-group-alist nil)
238 (defvar gnus-category-alist nil)
239 (defvar gnus-agent-current-history nil)
240 (defvar gnus-agent-overview-buffer nil)
241 (defvar gnus-category-predicate-cache nil)
242 (defvar gnus-category-group-cache nil)
243 (defvar gnus-agent-spam-hashtb nil)
244 (defvar gnus-agent-file-name nil)
245 (defvar gnus-agent-file-coding-system 'raw-text)
246 (defvar gnus-agent-file-loading-cache nil)
247 (defvar gnus-agent-total-fetched-hashtb nil)
248 (defvar gnus-agent-inhibit-update-total-fetched-for nil)
249 (defvar gnus-agent-need-update-total-fetched-for nil)
250
251 ;; Dynamic variables
252 (defvar gnus-headers)
253 (defvar gnus-score)
254
255 ;; Added to support XEmacs
256 (eval-and-compile
257   (unless (fboundp 'directory-files-and-attributes)
258     (defun directory-files-and-attributes (directory
259                                            &optional full match nosort)
260       (let (result)
261         (dolist (file (directory-files directory full match nosort))
262           (push (cons file (file-attributes file)) result))
263         (nreverse result)))))
264
265 ;;;
266 ;;; Setup
267 ;;;
268
269 (defun gnus-open-agent ()
270   (setq gnus-agent t)
271   (gnus-agent-read-servers)
272   (gnus-category-read)
273   (gnus-agent-create-buffer)
274   (add-hook 'gnus-group-mode-hook 'gnus-agent-mode)
275   (add-hook 'gnus-summary-mode-hook 'gnus-agent-mode)
276   (add-hook 'gnus-server-mode-hook 'gnus-agent-mode))
277
278 (defun gnus-agent-create-buffer ()
279   (if (gnus-buffer-live-p gnus-agent-overview-buffer)
280       t
281     (setq gnus-agent-overview-buffer
282           (gnus-get-buffer-create " *Gnus agent overview*"))
283     (with-current-buffer gnus-agent-overview-buffer
284       (mm-enable-multibyte))
285     nil))
286
287 (gnus-add-shutdown 'gnus-close-agent 'gnus)
288
289 (defun gnus-close-agent ()
290   (setq gnus-category-predicate-cache nil
291         gnus-category-group-cache nil
292         gnus-agent-spam-hashtb nil)
293   (gnus-kill-buffer gnus-agent-overview-buffer))
294
295 ;;;
296 ;;; Utility functions
297 ;;;
298
299 (defmacro gnus-agent-with-refreshed-group (group &rest body)
300   "Performs the body then updates the group's line in the group
301 buffer.  Automatically blocks multiple updates due to recursion."
302 `(prog1 (let ((gnus-agent-inhibit-update-total-fetched-for t)) ,@body)
303      (when (and gnus-agent-need-update-total-fetched-for
304                 (not gnus-agent-inhibit-update-total-fetched-for))
305         (with-current-buffer gnus-group-buffer
306           (setq gnus-agent-need-update-total-fetched-for nil)
307           (gnus-group-update-group ,group t)))))
308
309 (defun gnus-agent-read-file (file)
310   "Load FILE and do a `read' there."
311   (with-temp-buffer
312     (ignore-errors
313       (nnheader-insert-file-contents file)
314       (goto-char (point-min))
315       (read (current-buffer)))))
316
317 (defsubst gnus-agent-method ()
318   (concat (symbol-name (car gnus-command-method)) "/"
319           (if (equal (cadr gnus-command-method) "")
320               "unnamed"
321             (cadr gnus-command-method))))
322
323 (defsubst gnus-agent-directory ()
324   "The name of the Gnus agent directory."
325   (nnheader-concat gnus-agent-directory
326                    (nnheader-translate-file-chars (gnus-agent-method)) "/"))
327
328 (defun gnus-agent-lib-file (file)
329   "The full name of the Gnus agent library FILE."
330   (expand-file-name file
331                     (file-name-as-directory
332                      (expand-file-name "agent.lib" (gnus-agent-directory)))))
333
334 (defun gnus-agent-cat-set-property (category property value)
335   (if value
336       (setcdr (or (assq property category)
337               (let ((cell (cons property nil)))
338                     (setcdr category (cons cell (cdr category)))
339                     cell)) value)
340     (let ((category category))
341       (while (cond ((eq property (caadr category))
342                     (setcdr category (cddr category))
343                     nil)
344                    (t
345                     (setq category (cdr category)))))))
346   category)
347
348 (eval-when-compile
349   (defmacro gnus-agent-cat-defaccessor (name prop-name)
350     "Define accessor and setter methods for manipulating a list of the form
351 \(NAME (PROPERTY1 VALUE1) ... (PROPERTY_N VALUE_N)).
352 Given the call (gnus-agent-cat-defaccessor func PROPERTY1), the list may be
353 manipulated as follows:
354   (func LIST): Returns VALUE1
355   (setf (func LIST) NEW_VALUE1): Replaces VALUE1 with NEW_VALUE1."
356     `(progn (defmacro ,name (category)
357               (list '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 (eq major-mode '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                        (format "Synchronize flags on server `%s'? "
872                                (cadr method))))))
873     (gnus-agent-synchronize-flags-server method)))
874
875 ;;;###autoload
876 (defun gnus-agent-rename-group (old-group new-group)
877   "Rename fully-qualified OLD-GROUP as NEW-GROUP.
878 Always updates the agent, even when disabled, as the old agent
879 files would corrupt gnus when the agent was next enabled.
880 Depends upon the caller to determine whether group renaming is
881 supported."
882   (let* ((old-command-method (gnus-find-method-for-group old-group))
883          (old-path           (directory-file-name
884                               (let (gnus-command-method old-command-method)
885                                 (gnus-agent-group-pathname old-group))))
886          (new-command-method (gnus-find-method-for-group new-group))
887          (new-path           (directory-file-name
888                               (let (gnus-command-method new-command-method)
889                                 (gnus-agent-group-pathname new-group))))
890          (file-name-coding-system nnmail-pathname-coding-system))
891     (gnus-rename-file old-path new-path t)
892
893     (let* ((old-real-group (gnus-group-real-name old-group))
894            (new-real-group (gnus-group-real-name new-group))
895            (old-active (gnus-agent-get-group-info old-command-method old-real-group)))
896       (gnus-agent-save-group-info old-command-method old-real-group nil)
897       (gnus-agent-save-group-info new-command-method new-real-group old-active)
898
899       (let ((old-local (gnus-agent-get-local old-group
900                                              old-real-group old-command-method)))
901         (gnus-agent-set-local old-group
902                               nil nil
903                               old-real-group old-command-method)
904         (gnus-agent-set-local new-group
905                               (car old-local) (cdr old-local)
906                               new-real-group new-command-method)))))
907
908 ;;;###autoload
909 (defun gnus-agent-delete-group (group)
910   "Delete fully-qualified GROUP.
911 Always updates the agent, even when disabled, as the old agent
912 files would corrupt gnus when the agent was next enabled.
913 Depends upon the caller to determine whether group deletion is
914 supported."
915   (let* ((command-method (gnus-find-method-for-group group))
916          (path           (directory-file-name
917                           (let (gnus-command-method command-method)
918                             (gnus-agent-group-pathname group))))
919          (file-name-coding-system nnmail-pathname-coding-system))
920     (gnus-delete-directory path)
921
922     (let* ((real-group (gnus-group-real-name group)))
923       (gnus-agent-save-group-info command-method real-group nil)
924
925       (let ((local (gnus-agent-get-local group
926                                          real-group command-method)))
927         (gnus-agent-set-local group
928                               nil nil
929                               real-group command-method)))))
930
931 ;;;
932 ;;; Server mode commands
933 ;;;
934
935 (defun gnus-agent-add-server ()
936   "Enroll SERVER in the agent program."
937   (interactive)
938   (let* ((server       (gnus-server-server-name))
939          (named-server (gnus-server-named-server))
940          (method       (and server
941                             (gnus-server-get-method nil server))))
942     (unless server
943       (error "No server on the current line"))
944
945     (when (gnus-agent-method-p method)
946       (error "Server already in the agent program"))
947
948     (push named-server gnus-agent-covered-methods)
949
950     (setq gnus-agent-method-p-cache nil)
951     (gnus-server-update-server server)
952     (gnus-agent-write-servers)
953     (gnus-message 1 "Entered %s into the Agent" server)))
954
955 (defun gnus-agent-remove-server ()
956   "Remove SERVER from the agent program."
957   (interactive)
958   (let* ((server       (gnus-server-server-name))
959          (named-server (gnus-server-named-server)))
960     (unless server
961       (error "No server on the current line"))
962
963     (unless (member named-server gnus-agent-covered-methods)
964       (error "Server not in the agent program"))
965
966     (setq gnus-agent-covered-methods
967           (delete named-server gnus-agent-covered-methods)
968           gnus-agent-method-p-cache nil)
969
970     (gnus-server-update-server server)
971     (gnus-agent-write-servers)
972     (gnus-message 1 "Removed %s from the agent" server)))
973
974 (defun gnus-agent-read-servers ()
975   "Read the alist of covered servers."
976   (setq gnus-agent-covered-methods
977         (gnus-agent-read-file
978          (nnheader-concat gnus-agent-directory "lib/servers"))
979         gnus-agent-method-p-cache nil)
980
981   ;; I am called so early in start-up that I can not validate server
982   ;; names.  When that is the case, I skip the validation.  That is
983   ;; alright as the gnus startup code calls the validate methods
984   ;; directly.
985   (if gnus-server-alist
986       (gnus-agent-read-servers-validate)))
987
988 (defun gnus-agent-read-servers-validate ()
989   (mapcar (lambda (server-or-method)
990             (let* ((server (if (stringp server-or-method)
991                                server-or-method
992                              (gnus-method-to-server server-or-method)))
993                    (method (gnus-server-to-method server)))
994               (if method
995                   (unless (member server gnus-agent-covered-methods)
996                     (push server gnus-agent-covered-methods)
997                     (setq gnus-agent-method-p-cache nil))
998                 (gnus-message 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 id
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                       (if (not (re-search-forward
1607                                 "^Message-ID: *<\\([^>\n]+\\)>" nil t))
1608                           (setq id "No-Message-ID-in-article")
1609                         (setq id (buffer-substring
1610                                   (match-beginning 1) (match-end 1))))
1611                       (let ((coding-system-for-write
1612                              gnus-agent-file-coding-system))
1613                         (write-region (point-min) (point-max)
1614                                       (concat dir (number-to-string (caar pos)))
1615                                       nil 'silent))
1616
1617                       (gnus-agent-append-to-list
1618                        tail-fetched-articles (caar pos)))
1619                     (widen)
1620                     (setq pos (cdr pos)))))
1621
1622             (gnus-agent-save-alist group (cdr fetched-articles) date)
1623             (gnus-agent-update-files-total-fetched-for group (cdr fetched-articles))
1624
1625             (gnus-message 7 ""))
1626           (cdr fetched-articles))))))
1627
1628 (defun gnus-agent-unfetch-articles (group articles)
1629   "Delete ARTICLES that were fetched from GROUP into the agent."
1630   (when articles
1631     (gnus-agent-with-refreshed-group
1632      group
1633      (gnus-agent-load-alist group)
1634      (let* ((alist (cons nil gnus-agent-article-alist))
1635             (articles (sort articles #'<))
1636             (next-possibility alist)
1637             (delete-this (pop articles)))
1638        (while (and (cdr next-possibility) delete-this)
1639          (let ((have-this (caar (cdr next-possibility))))
1640            (cond
1641             ((< delete-this have-this)
1642              (setq delete-this (pop articles)))
1643             ((= delete-this have-this)
1644              (let ((timestamp (cdar (cdr next-possibility))))
1645                (when timestamp
1646                  (let* ((file-name (concat (gnus-agent-group-pathname group)
1647                                            (number-to-string have-this)))
1648                         (size-file
1649                          (float (or (and gnus-agent-total-fetched-hashtb
1650                                          (nth 7 (file-attributes file-name)))
1651                                     0)))
1652                         (file-name-coding-system
1653                          nnmail-pathname-coding-system))
1654                    (delete-file file-name)
1655                    (gnus-agent-update-files-total-fetched-for
1656                     group (- size-file)))))
1657
1658              (setcdr next-possibility (cddr next-possibility)))
1659             (t
1660              (setq next-possibility (cdr next-possibility))))))
1661        (setq gnus-agent-article-alist (cdr alist))
1662        (gnus-agent-save-alist group)))))
1663
1664 (defun gnus-agent-crosspost (crosses article &optional date)
1665   (setq date (or date t))
1666
1667   (let (gnus-agent-article-alist group alist beg end)
1668     (with-current-buffer gnus-agent-overview-buffer
1669       (when (nnheader-find-nov-line article)
1670         (forward-word 1)
1671         (setq beg (point))
1672         (setq end (progn (forward-line 1) (point)))))
1673     (while crosses
1674       (setq group (caar crosses))
1675       (unless (setq alist (assoc group gnus-agent-group-alist))
1676         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
1677               gnus-agent-group-alist))
1678       (setcdr alist (cons (cons (cdar crosses) date) (cdr alist)))
1679       (with-current-buffer (gnus-get-buffer-create
1680                             (format " *Gnus agent overview %s*"group))
1681         (when (= (point-max) (point-min))
1682           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
1683           (ignore-errors
1684            (let ((file-name-coding-system nnmail-pathname-coding-system))
1685              (nnheader-insert-file-contents
1686               (gnus-agent-article-name ".overview" group)))))
1687         (nnheader-find-nov-line (string-to-number (cdar crosses)))
1688         (insert (string-to-number (cdar crosses)))
1689         (insert-buffer-substring gnus-agent-overview-buffer beg end)
1690         (gnus-agent-check-overview-buffer))
1691       (setq crosses (cdr crosses)))))
1692
1693 (defun gnus-agent-backup-overview-buffer ()
1694   (when gnus-newsgroup-name
1695     (let ((root (gnus-agent-article-name ".overview" gnus-newsgroup-name))
1696           (cnt 0)
1697           name
1698           (file-name-coding-system nnmail-pathname-coding-system))
1699       (while (file-exists-p
1700               (setq name (concat root "~"
1701                                  (int-to-string (setq cnt (1+ cnt))) "~"))))
1702       (write-region (point-min) (point-max) name nil 'no-msg)
1703       (gnus-message 1 "Created backup copy of overview in %s." name)))
1704   t)
1705
1706 (defun gnus-agent-check-overview-buffer (&optional buffer)
1707   "Check the overview file given for sanity.
1708 In particular, checks that the file is sorted by article number
1709 and that there are no duplicates."
1710   (let ((prev-num -1)
1711         (backed-up nil))
1712     (save-excursion
1713       (when buffer
1714         (set-buffer buffer))
1715       (save-restriction
1716         (widen)
1717         (goto-char (point-min))
1718
1719         (while (< (point) (point-max))
1720           (let ((p (point))
1721                 (cur (condition-case nil
1722                          (read (current-buffer))
1723                        (error nil))))
1724             (cond
1725              ((or (not (integerp cur))
1726                   (not (eq (char-after) ?\t)))
1727               (or backed-up
1728                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1729               (gnus-message 1
1730                             "Overview buffer contains garbage '%s'."
1731                             (buffer-substring
1732                              p (point-at-eol))))
1733              ((= cur prev-num)
1734               (or backed-up
1735                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1736               (gnus-message 1
1737                             "Duplicate overview line for %d" cur)
1738               (delete-region p (progn (forward-line 1) (point))))
1739              ((< cur prev-num)
1740               (or backed-up
1741                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1742               (gnus-message 1 "Overview buffer not sorted!")
1743               (sort-numeric-fields 1 (point-min) (point-max))
1744               (goto-char (point-min))
1745               (setq prev-num -1))
1746              (t
1747               (setq prev-num cur)))
1748             (forward-line 1)))))))
1749
1750 (defun gnus-agent-flush-server (&optional server-or-method)
1751   "Flush all agent index files for every subscribed group within
1752   the given SERVER-OR-METHOD.  When called with nil, the current
1753   value of gnus-command-method identifies the server."
1754   (let* ((gnus-command-method (if server-or-method
1755                                   (gnus-server-to-method server-or-method)
1756                                 gnus-command-method))
1757          (alist gnus-newsrc-alist))
1758     (while alist
1759       (let ((entry (pop alist)))
1760         (when (gnus-methods-equal-p gnus-command-method (gnus-info-method entry))
1761           (gnus-agent-flush-group (gnus-info-group entry)))))))
1762
1763 (defun gnus-agent-flush-group (group)
1764   "Flush the agent's index files such that the GROUP no longer
1765 appears to have any local content.  The actual content, the
1766 article files, may then be deleted using gnus-agent-expire-group.
1767 If flushing was a mistake, the gnus-agent-regenerate-group method
1768 provides an undo mechanism by reconstructing the index files from
1769 the article files."
1770   (interactive (list (gnus-agent-read-group)))
1771
1772   (let* ((gnus-command-method (or gnus-command-method
1773                                   (gnus-find-method-for-group group)))
1774          (overview (gnus-agent-article-name ".overview" group))
1775          (agentview (gnus-agent-article-name ".agentview" group))
1776          (file-name-coding-system nnmail-pathname-coding-system))
1777
1778     (if (file-exists-p overview)
1779         (delete-file overview))
1780     (if (file-exists-p agentview)
1781         (delete-file agentview))
1782
1783     (gnus-agent-update-view-total-fetched-for group nil gnus-command-method)
1784     (gnus-agent-update-view-total-fetched-for group t   gnus-command-method)
1785
1786     ;(gnus-agent-set-local group nil nil)
1787     ;(gnus-agent-save-local t)
1788     (gnus-agent-save-group-info nil group nil)))
1789
1790 (defun gnus-agent-flush-cache ()
1791   "Flush the agent's index files such that the group no longer
1792 appears to have any local content.  The actual content, the
1793 article files, is then deleted using gnus-agent-expire-group. The
1794 gnus-agent-regenerate-group method provides an undo mechanism by
1795 reconstructing the index files from the article files."
1796   (interactive)
1797   (save-excursion
1798     (let ((file-name-coding-system nnmail-pathname-coding-system))
1799       (while gnus-agent-buffer-alist
1800         (set-buffer (cdar gnus-agent-buffer-alist))
1801         (let ((coding-system-for-write gnus-agent-file-coding-system))
1802           (write-region (point-min) (point-max)
1803                         (gnus-agent-article-name ".overview"
1804                                                  (caar gnus-agent-buffer-alist))
1805                         nil 'silent))
1806         (setq gnus-agent-buffer-alist (cdr gnus-agent-buffer-alist)))
1807       (while gnus-agent-group-alist
1808         (with-temp-file (gnus-agent-article-name
1809                          ".agentview" (caar gnus-agent-group-alist))
1810           (princ (cdar gnus-agent-group-alist))
1811           (insert "\n")
1812           (princ 1 (current-buffer))
1813           (insert "\n"))
1814         (setq gnus-agent-group-alist (cdr gnus-agent-group-alist))))))
1815
1816 ;;;###autoload
1817 (defun gnus-agent-find-parameter (group symbol)
1818   "Search for GROUPs SYMBOL in the group's parameters, the group's
1819 topic parameters, the group's category, or the customizable
1820 variables.  Returns the first non-nil value found."
1821   (or (gnus-group-find-parameter group symbol t)
1822       (gnus-group-parameter-value (cdr (gnus-group-category group)) symbol t)
1823       (symbol-value
1824        (cdr
1825         (assq symbol
1826               '((agent-short-article . gnus-agent-short-article)
1827                 (agent-long-article . gnus-agent-long-article)
1828                 (agent-low-score . gnus-agent-low-score)
1829                 (agent-high-score . gnus-agent-high-score)
1830                 (agent-days-until-old . gnus-agent-expire-days)
1831                 (agent-enable-expiration
1832                  . gnus-agent-enable-expiration)
1833                 (agent-predicate . gnus-agent-predicate)))))))
1834
1835 (defun gnus-agent-fetch-headers (group &optional force)
1836   "Fetch interesting headers into the agent.  The group's overview
1837 file will be updated to include the headers while a list of available
1838 article numbers will be returned."
1839   (let* ((fetch-all (and gnus-agent-consider-all-articles
1840                          ;; Do not fetch all headers if the predicate
1841                          ;; implies that we only consider unread articles.
1842                          (not (gnus-predicate-implies-unread
1843                                (gnus-agent-find-parameter group
1844                                                           'agent-predicate)))))
1845          (articles (if fetch-all
1846                        (if gnus-newsgroup-maximum-articles
1847                            (let ((active (gnus-active group)))
1848                              (gnus-uncompress-range
1849                               (cons (max (car active)
1850                                          (- (cdr active)
1851                                             gnus-newsgroup-maximum-articles
1852                                             -1))
1853                                     (cdr active))))
1854                          (gnus-uncompress-range (gnus-active group)))
1855                      (gnus-list-of-unread-articles group)))
1856          (gnus-decode-encoded-word-function 'identity)
1857          (gnus-decode-encoded-address-function 'identity)
1858          (file (gnus-agent-article-name ".overview" group))
1859          (file-name-coding-system nnmail-pathname-coding-system))
1860
1861     (unless fetch-all
1862       ;; Add articles with marks to the list of article headers we want to
1863       ;; fetch.  Don't fetch articles solely on the basis of a recent or seen
1864       ;; mark, but do fetch recent or seen articles if they have other, more
1865       ;; interesting marks.  (We have to fetch articles with boring marks
1866       ;; because otherwise the agent will remove their marks.)
1867       (dolist (arts (gnus-info-marks (gnus-get-info group)))
1868         (unless (memq (car arts) '(seen recent killed cache))
1869           (setq articles (gnus-range-add articles (cdr arts)))))
1870       (setq articles (sort (gnus-uncompress-sequence articles) '<)))
1871
1872     ;; At this point, I have the list of articles to consider for
1873     ;; fetching.  This is the list that I'll return to my caller. Some
1874     ;; of these articles may have already been fetched.  That's OK as
1875     ;; the fetch article code will filter those out.  Internally, I'll
1876     ;; filter this list to just those articles whose headers need to
1877     ;; be fetched.
1878     (let ((articles articles))
1879       ;; Remove known articles.
1880       (when (and (or gnus-agent-cache
1881                      (not gnus-plugged))
1882                  (gnus-agent-load-alist group))
1883         ;; Remove articles marked as downloaded.
1884         (if fetch-all
1885             ;; I want to fetch all headers in the active range.
1886             ;; Therefore, exclude only those headers that are in the
1887             ;; article alist.
1888             ;; NOTE: This is probably NOT what I want to do after
1889             ;; agent expiration in this group.
1890             (setq articles (gnus-agent-uncached-articles articles group))
1891
1892           ;; I want to only fetch those headers that have never been
1893           ;; fetched.  Therefore, exclude all headers that are, or
1894           ;; WERE, in the article alist.
1895           (let ((low (1+ (caar (last gnus-agent-article-alist))))
1896                 (high (cdr (gnus-active group))))
1897             ;; Low can be greater than High when the same group is
1898             ;; fetched twice in the same session {The first fetch will
1899             ;; fill the article alist such that (last
1900             ;; gnus-agent-article-alist) equals (cdr (gnus-active
1901             ;; group))}.  The addition of one(the 1+ above) then
1902             ;; forces Low to be greater than High.  When this happens,
1903             ;; gnus-list-range-intersection returns nil which
1904             ;; indicates that no headers need to be fetched. -- Kevin
1905             (setq articles (gnus-list-range-intersection
1906                             articles (list (cons low high)))))))
1907
1908       (when articles
1909         (gnus-message
1910          10 "gnus-agent-fetch-headers: undownloaded articles are '%s'"
1911          (gnus-compress-sequence articles t)))
1912
1913       (with-current-buffer nntp-server-buffer
1914         (if articles
1915             (progn
1916               (gnus-message 8 "Fetching headers for %s..."
1917                             (gnus-agent-decoded-group-name group))
1918
1919               ;; Fetch them.
1920               (gnus-make-directory (nnheader-translate-file-chars
1921                                     (file-name-directory file) t))
1922
1923               (unless (eq 'nov (gnus-retrieve-headers articles group))
1924                 (nnvirtual-convert-headers))
1925               (gnus-agent-check-overview-buffer)
1926               ;; Move these headers to the overview buffer so that
1927               ;; gnus-agent-braid-nov can merge them with the contents
1928               ;; of FILE.
1929               (copy-to-buffer
1930                gnus-agent-overview-buffer (point-min) (point-max))
1931               ;; NOTE: Call g-a-brand-nov even when the file does not
1932               ;; exist.  As a minimum, it will validate the article
1933               ;; numbers already in the buffer.
1934               (gnus-agent-braid-nov group articles file)
1935               (let ((coding-system-for-write
1936                      gnus-agent-file-coding-system))
1937                 (gnus-agent-check-overview-buffer)
1938                 (write-region (point-min) (point-max) file nil 'silent))
1939               (gnus-agent-update-view-total-fetched-for group t)
1940               (gnus-agent-save-alist group articles nil)
1941               articles)
1942           (ignore-errors
1943             (erase-buffer)
1944             (nnheader-insert-file-contents file)))))
1945     articles))
1946
1947 (defsubst gnus-agent-read-article-number ()
1948   "Reads the article number at point.  Returns nil when a valid article number can not be read."
1949
1950   ;; It is unfortunate but the read function quietly overflows
1951   ;; integer.  As a result, I have to use string operations to test
1952   ;; for overflow BEFORE calling read.
1953   (when (looking-at "[0-9]+\t")
1954     (let ((len (- (match-end 0) (match-beginning 0))))
1955       (cond ((< len 9)
1956              (read (current-buffer)))
1957             ((= len 9)
1958              ;; Many 9 digit base-10 numbers can be represented in a 27-bit int
1959              ;; Back convert from int to string to ensure that this is one of them.
1960              (let* ((str1 (buffer-substring (match-beginning 0) (1- (match-end 0))))
1961                     (num (read (current-buffer)))
1962                     (str2 (int-to-string num)))
1963                (when (equal str1 str2)
1964                  num)))))))
1965
1966 (defsubst gnus-agent-copy-nov-line (article)
1967   "Copy the indicated ARTICLE from the overview buffer to the nntp server buffer."
1968   (let (art b e)
1969     (set-buffer gnus-agent-overview-buffer)
1970     (while (and (not (eobp))
1971                 (or (not (setq art (gnus-agent-read-article-number)))
1972                     (< art article)))
1973       (forward-line 1))
1974     (beginning-of-line)
1975     (if (or (eobp)
1976             (not (eq article art)))
1977         (set-buffer nntp-server-buffer)
1978       (setq b (point))
1979       (setq e (progn (forward-line 1) (point)))
1980       (set-buffer nntp-server-buffer)
1981       (insert-buffer-substring gnus-agent-overview-buffer b e))))
1982
1983 (defun gnus-agent-braid-nov (group articles file)
1984   "Merge agent overview data with given file.
1985 Takes unvalidated headers for ARTICLES from
1986 `gnus-agent-overview-buffer' and validated headers from the given
1987 FILE and places the combined valid headers into
1988 `nntp-server-buffer'.  This function can be used, when file
1989 doesn't exist, to valid the overview buffer."
1990   (let (start last)
1991     (set-buffer gnus-agent-overview-buffer)
1992     (goto-char (point-min))
1993     (set-buffer nntp-server-buffer)
1994     (erase-buffer)
1995     (when (file-exists-p file)
1996       (nnheader-insert-file-contents file))
1997     (goto-char (point-max))
1998     (forward-line -1)
1999
2000     (unless (or (= (point-min) (point-max))
2001                 (< (setq last (read (current-buffer))) (car articles)))
2002       ;; Old and new overlap -- We do it the hard way.
2003       (when (nnheader-find-nov-line (car articles))
2004         ;; Replacing existing NOV entry
2005         (delete-region (point) (progn (forward-line 1) (point))))
2006       (gnus-agent-copy-nov-line (pop articles))
2007
2008       (ignore-errors
2009         (while articles
2010           (while (let ((art (read (current-buffer))))
2011                    (cond ((< art (car articles))
2012                           (forward-line 1)
2013                           t)
2014                          ((= art (car articles))
2015                           (beginning-of-line)
2016                           (delete-region
2017                            (point) (progn (forward-line 1) (point)))
2018                           nil)
2019                          (t
2020                           (beginning-of-line)
2021                           nil))))
2022
2023           (gnus-agent-copy-nov-line (pop articles)))))
2024
2025     (goto-char (point-max))
2026
2027     ;; Append the remaining lines
2028     (when articles
2029       (when last
2030         (set-buffer gnus-agent-overview-buffer)
2031         (setq start (point))
2032         (set-buffer nntp-server-buffer))
2033
2034       (let ((p (point)))
2035         (insert-buffer-substring gnus-agent-overview-buffer start)
2036         (goto-char p))
2037
2038       (setq last (or last -134217728))
2039       (while (catch 'problems
2040                (let (sort art)
2041                  (while (not (eobp))
2042                    (setq art (gnus-agent-read-article-number))
2043                    (cond ((not art)
2044                           ;; Bad art num - delete this line
2045                           (beginning-of-line)
2046                           (delete-region (point) (progn (forward-line 1) (point))))
2047                          ((< art last)
2048                           ;; Art num out of order - enable sort
2049                           (setq sort t)
2050                           (forward-line 1))
2051                          ((= art last)
2052                           ;; Bad repeat of art number - delete this line
2053                           (beginning-of-line)
2054                           (delete-region (point) (progn (forward-line 1) (point))))
2055                          (t
2056                           ;; Good art num
2057                           (setq last art)
2058                           (forward-line 1))))
2059                  (when sort
2060                    ;; something is seriously wrong as we simply shouldn't see out-of-order data.
2061                    ;; First, we'll fix the sort.
2062                    (sort-numeric-fields 1 (point-min) (point-max))
2063
2064                    ;; but now we have to consider that we may have duplicate rows...
2065                    ;; so reset to beginning of file
2066                    (goto-char (point-min))
2067                    (setq last -134217728)
2068
2069                    ;; and throw a code that restarts this scan
2070                    (throw 'problems t))
2071                  nil))))))
2072
2073 ;; Keeps the compiler from warning about the free variable in
2074 ;; gnus-agent-read-agentview.
2075 (defvar gnus-agent-read-agentview)
2076
2077 (defun gnus-agent-load-alist (group)
2078   "Load the article-state alist for GROUP."
2079   ;; Bind free variable that's used in `gnus-agent-read-agentview'.
2080   (let* ((gnus-agent-read-agentview group)
2081          (file-name-coding-system nnmail-pathname-coding-system)
2082          (agentview (gnus-agent-article-name ".agentview" group)))
2083     (setq gnus-agent-article-alist
2084           (and (file-exists-p agentview)
2085                (gnus-cache-file-contents
2086                 agentview
2087                 'gnus-agent-file-loading-cache
2088                 'gnus-agent-read-agentview)))))
2089
2090 (defun gnus-agent-read-agentview (file)
2091   "Load FILE and do a `read' there."
2092   (with-temp-buffer
2093     (condition-case nil
2094         (progn
2095           (nnheader-insert-file-contents file)
2096           (goto-char (point-min))
2097           (let ((alist (read (current-buffer)))
2098                 (version (condition-case nil (read (current-buffer))
2099                            (end-of-file 0)))
2100                 changed-version)
2101
2102             (cond
2103              ((= version 0)
2104               (let ((inhibit-quit t)
2105                     entry)
2106                 (gnus-agent-open-history)
2107                 (set-buffer (gnus-agent-history-buffer))
2108                 (goto-char (point-min))
2109                 (while (not (eobp))
2110                   (if (and (looking-at
2111                             "[^\t\n]+\t\\([0-9]+\\)\t\\([^ \n]+\\) \\([0-9]+\\)")
2112                            (string= (match-string 2)
2113                                     gnus-agent-read-agentview)
2114                            (setq entry (assoc (string-to-number (match-string 3)) alist)))
2115                       (setcdr entry (string-to-number (match-string 1))))
2116                   (forward-line 1))
2117                 (gnus-agent-close-history)
2118                 (setq changed-version t)))
2119              ((= version 1)
2120               (setq changed-version (not (= 1 gnus-agent-article-alist-save-format))))
2121              ((= version 2)
2122               (let (state sequence uncomp)
2123                 (while alist
2124                   (setq state (caar alist)
2125                         sequence (inline (gnus-uncompress-range (cdar alist)))
2126                         alist (cdr alist))
2127                   (while sequence
2128                     (push (cons (pop sequence) state) uncomp)))
2129                 (setq alist (sort uncomp 'car-less-than-car)))
2130               (setq changed-version (not (= 2 gnus-agent-article-alist-save-format)))))
2131             (when changed-version
2132               (let ((gnus-agent-article-alist alist))
2133                 (gnus-agent-save-alist gnus-agent-read-agentview)))
2134             alist))
2135       ((end-of-file file-error)
2136        ;; The agentview file is missing.
2137        (condition-case nil
2138            ;; If the agent directory exists, attempt to perform a brute-force
2139            ;; reconstruction of its contents.
2140            (let* (alist
2141                   (file-name-coding-system nnmail-pathname-coding-system)
2142                   (file-attributes (directory-files-and-attributes
2143                                     (gnus-agent-article-name ""
2144                                                              gnus-agent-read-agentview) nil "^[0-9]+$" t)))
2145              (while file-attributes
2146                (let ((fa (pop file-attributes)))
2147                  (unless (nth 1 fa)
2148                    (push (cons (string-to-number (nth 0 fa)) (time-to-days (nth 5 fa))) alist))))
2149              alist)
2150          (file-error nil))))))
2151
2152 (defun gnus-agent-save-alist (group &optional articles state)
2153   "Save the article-state alist for GROUP."
2154   (let* ((file-name-coding-system nnmail-pathname-coding-system)
2155          (prev (cons nil gnus-agent-article-alist))
2156          (all prev)
2157          print-level print-length item article)
2158     (while (setq article (pop articles))
2159       (while (and (cdr prev)
2160                   (< (caadr prev) article))
2161         (setq prev (cdr prev)))
2162       (cond
2163        ((not (cdr prev))
2164         (setcdr prev (list (cons article state))))
2165        ((> (caadr prev) article)
2166         (setcdr prev (cons (cons article state) (cdr prev))))
2167        ((= (caadr prev) article)
2168         (setcdr (cadr prev) state)))
2169       (setq prev (cdr prev)))
2170     (setq gnus-agent-article-alist (cdr all))
2171
2172     (gnus-agent-set-local group
2173                           (caar gnus-agent-article-alist)
2174                           (caar (last gnus-agent-article-alist)))
2175
2176     (gnus-make-directory (gnus-agent-article-name "" group))
2177     (with-temp-file (gnus-agent-article-name ".agentview" group)
2178       (cond ((eq gnus-agent-article-alist-save-format 1)
2179              (princ gnus-agent-article-alist (current-buffer)))
2180             ((eq gnus-agent-article-alist-save-format 2)
2181              (let ((alist gnus-agent-article-alist)
2182                    article-id day-of-download comp-list compressed)
2183                (while alist
2184                  (setq article-id (caar alist)
2185                        day-of-download (cdar alist)
2186                        comp-list (assq day-of-download compressed)
2187                        alist (cdr alist))
2188                  (if comp-list
2189                      (setcdr comp-list (cons article-id (cdr comp-list)))
2190                    (push (list day-of-download article-id) compressed)))
2191                (setq alist compressed)
2192                (while alist
2193                  (setq comp-list (pop alist))
2194                  (setcdr comp-list
2195                          (gnus-compress-sequence (nreverse (cdr comp-list)))))
2196                (princ compressed (current-buffer)))))
2197       (insert "\n")
2198       (princ gnus-agent-article-alist-save-format (current-buffer))
2199       (insert "\n"))
2200
2201     (gnus-agent-update-view-total-fetched-for group nil)))
2202
2203 (defvar gnus-agent-article-local nil)
2204 (defvar gnus-agent-article-local-times nil)
2205 (defvar gnus-agent-file-loading-local nil)
2206
2207 (defun gnus-agent-load-local (&optional method)
2208   "Load the METHOD'S local file.  The local file contains min/max
2209 article counts for each of the method's subscribed groups."
2210   (let ((gnus-command-method (or method gnus-command-method)))
2211     (when (or (null gnus-agent-article-local-times)
2212               (zerop gnus-agent-article-local-times)
2213               (not (gnus-methods-equal-p
2214                     gnus-command-method
2215                     (symbol-value (intern "+method" gnus-agent-article-local)))))
2216       (setq gnus-agent-article-local
2217             (gnus-cache-file-contents
2218              (gnus-agent-lib-file "local")
2219              'gnus-agent-file-loading-local
2220              'gnus-agent-read-and-cache-local))
2221       (when gnus-agent-article-local-times
2222         (incf gnus-agent-article-local-times)))
2223     gnus-agent-article-local))
2224
2225 (defun gnus-agent-read-and-cache-local (file)
2226   "Load and read FILE then bind its contents to
2227 gnus-agent-article-local.  If that variable had `dirty' (also known as
2228 modified) original contents, they are first saved to their own file."
2229   (if (and gnus-agent-article-local
2230            (symbol-value (intern "+dirty" gnus-agent-article-local)))
2231       (gnus-agent-save-local))
2232   (gnus-agent-read-local file))
2233
2234 (defun gnus-agent-read-local (file)
2235   "Load FILE and do a `read' there."
2236   (let ((my-obarray (gnus-make-hashtable (count-lines (point-min)
2237                                                       (point-max))))
2238         (line 1))
2239     (with-temp-buffer
2240       (condition-case nil
2241           (let ((nnheader-file-coding-system gnus-agent-file-coding-system))
2242             (nnheader-insert-file-contents file))
2243         (file-error))
2244
2245       (goto-char (point-min))
2246       ;; Skip any comments at the beginning of the file (the only place where they may appear)
2247       (while (= (following-char) ?\;)
2248         (forward-line 1)
2249         (setq line (1+ line)))
2250
2251       (while (not (eobp))
2252         (condition-case err
2253             (let (group
2254                   min
2255                   max
2256                   (cur (current-buffer))
2257                   (obarray my-obarray))
2258               (setq group (read cur)
2259                     min (read cur)
2260                     max (read cur))
2261
2262               (when (stringp group)
2263                 (setq group (intern group my-obarray)))
2264
2265               ;; NOTE: The '+ 0' ensure that min and max are both numerics.
2266               (set group (cons (+ 0 min) (+ 0 max))))
2267           (error
2268            (gnus-message 3 "Warning - invalid agent local: %s on line %d: %s"
2269                          file line (error-message-string err))))
2270         (forward-line 1)
2271         (setq line (1+ line))))
2272
2273     (set (intern "+dirty" my-obarray) nil)
2274     (set (intern "+method" my-obarray) gnus-command-method)
2275     my-obarray))
2276
2277 (defun gnus-agent-save-local (&optional force)
2278   "Save gnus-agent-article-local under it method's agent.lib directory."
2279   (let ((my-obarray gnus-agent-article-local))
2280     (when (and my-obarray
2281                (or force (symbol-value (intern "+dirty" my-obarray))))
2282       (let* ((gnus-command-method (symbol-value (intern "+method" my-obarray)))
2283              ;; NOTE: gnus-command-method is used within gnus-agent-lib-file.
2284              (dest (gnus-agent-lib-file "local")))
2285         (gnus-make-directory (gnus-agent-lib-file ""))
2286
2287         (let ((coding-system-for-write gnus-agent-file-coding-system)
2288               (file-name-coding-system nnmail-pathname-coding-system))
2289           (with-temp-file dest
2290             (let ((gnus-command-method (symbol-value (intern "+method" my-obarray)))
2291                   print-level print-length item article
2292                   (standard-output (current-buffer)))
2293               (mapatoms (lambda (symbol)
2294                           (cond ((not (boundp symbol))
2295                                  nil)
2296                                 ((member (symbol-name symbol) '("+dirty" "+method"))
2297                                  nil)
2298                                 (t
2299                                  (let ((range (symbol-value symbol)))
2300                                    (when range
2301                                      (prin1 symbol)
2302                                      (princ " ")
2303                                      (princ (car range))
2304                                      (princ " ")
2305                                      (princ (cdr range))
2306                                      (princ "\n"))))))
2307                         my-obarray))))))))
2308
2309 (defun gnus-agent-get-local (group &optional gmane method)
2310   (let* ((gmane (or gmane (gnus-group-real-name group)))
2311          (gnus-command-method (or method (gnus-find-method-for-group group)))
2312          (local (gnus-agent-load-local))
2313          (symb (intern gmane local))
2314          (minmax (and (boundp symb) (symbol-value symb))))
2315     (unless minmax
2316       ;; Bind these so that gnus-agent-load-alist doesn't change the
2317       ;; current alist (i.e. gnus-agent-article-alist)
2318       (let* ((gnus-agent-article-alist gnus-agent-article-alist)
2319              (gnus-agent-file-loading-cache gnus-agent-file-loading-cache)
2320              (alist (gnus-agent-load-alist group)))
2321         (when alist
2322           (setq minmax
2323                 (cons (caar alist)
2324                       (caar (last alist))))
2325           (gnus-agent-set-local group (car minmax) (cdr minmax)
2326                                 gmane gnus-command-method local))))
2327     minmax))
2328
2329 (defun gnus-agent-set-local (group min max &optional gmane method local)
2330   (let* ((gmane (or gmane (gnus-group-real-name group)))
2331          (gnus-command-method (or method (gnus-find-method-for-group group)))
2332          (local (or local (gnus-agent-load-local)))
2333          (symb (intern gmane local))
2334          (minmax (and (boundp symb) (symbol-value symb))))
2335     (if (cond ((and minmax
2336                     (or (not (eq min (car minmax)))
2337                         (not (eq max (cdr minmax))))
2338                     min
2339                     max)
2340                (setcar minmax min)
2341                (setcdr minmax max)
2342                t)
2343               (minmax
2344                nil)
2345               ((and min max)
2346                (set symb (cons min max))
2347                t)
2348               (t
2349                (unintern symb local)))
2350         (set (intern "+dirty" local) t))))
2351
2352 (defun gnus-agent-article-name (article group)
2353   (expand-file-name article
2354                     (file-name-as-directory
2355                      (gnus-agent-group-pathname group))))
2356
2357 (defun gnus-agent-batch-confirmation (msg)
2358   "Show error message and return t."
2359   (gnus-message 1 "%s" msg)
2360   t)
2361
2362 ;;;###autoload
2363 (defun gnus-agent-batch-fetch ()
2364   "Start Gnus and fetch session."
2365   (interactive)
2366   (gnus)
2367   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
2368     (gnus-agent-fetch-session))
2369   (gnus-group-exit))
2370
2371 (defun gnus-agent-fetch-session ()
2372   "Fetch all articles and headers that are eligible for fetching."
2373   (interactive)
2374   (unless gnus-agent-covered-methods
2375     (error "No servers are covered by the Gnus agent"))
2376   (unless gnus-plugged
2377     (error "Can't fetch articles while Gnus is unplugged"))
2378   (let ((methods (gnus-agent-covered-methods))
2379         groups group gnus-command-method)
2380     (save-excursion
2381       (while methods
2382         (setq gnus-command-method (car methods))
2383         (when (and (or (gnus-server-opened gnus-command-method)
2384                        (gnus-open-server gnus-command-method))
2385                    (gnus-online gnus-command-method))
2386           (setq groups (gnus-groups-from-server (car methods)))
2387           (gnus-agent-with-fetch
2388             (while (setq group (pop groups))
2389               (when (<= (gnus-group-level group)
2390                         gnus-agent-handle-level)
2391                 (if (or debug-on-error debug-on-quit)
2392                     (gnus-agent-fetch-group-1
2393                      group gnus-command-method)
2394                   (condition-case err
2395                       (gnus-agent-fetch-group-1
2396                        group gnus-command-method)
2397                     (error
2398                      (unless (funcall gnus-agent-confirmation-function
2399                                       (format "Error %s while fetching session.  Should gnus continue? "
2400                                               (error-message-string err)))
2401                        (error "Cannot fetch articles into the Gnus agent")))
2402                     (quit
2403                      (gnus-agent-regenerate-group group)
2404                      (unless (funcall gnus-agent-confirmation-function
2405                                       (format
2406                                        "%s while fetching session.  Should gnus continue? "
2407                                        (error-message-string err)))
2408                        (signal 'quit
2409                                "Cannot fetch articles into the Gnus agent")))))))))
2410         (setq methods (cdr methods)))
2411       (gnus-run-hooks 'gnus-agent-fetched-hook)
2412       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
2413
2414 (defun gnus-agent-fetch-group-1 (group method)
2415   "Fetch GROUP."
2416   (let ((gnus-command-method method)
2417         (gnus-newsgroup-name group)
2418         (gnus-newsgroup-dependencies gnus-newsgroup-dependencies)
2419         (gnus-newsgroup-headers gnus-newsgroup-headers)
2420         (gnus-newsgroup-scored gnus-newsgroup-scored)
2421         (gnus-use-cache gnus-use-cache)
2422         (gnus-summary-expunge-below gnus-summary-expunge-below)
2423         (gnus-summary-mark-below gnus-summary-mark-below)
2424         (gnus-orphan-score gnus-orphan-score)
2425         ;; Maybe some other gnus-summary local variables should also
2426         ;; be put here.
2427
2428         gnus-headers
2429         gnus-score
2430         articles arts
2431         category predicate info marks score-param
2432         )
2433     (unless (gnus-check-group group)
2434       (error "Can't open server for %s" group))
2435
2436     ;; Fetch headers.
2437     (when (or gnus-newsgroup-active
2438               (gnus-active group)
2439               (gnus-activate-group group))
2440       (let ((marked-articles gnus-newsgroup-downloadable))
2441         ;; Identify the articles marked for download
2442         (unless gnus-newsgroup-active
2443           ;; The variable gnus-newsgroup-active was selected as I need
2444           ;; a gnus-summary local variable that is NOT bound to any
2445           ;; value (its global value should default to nil).
2446           (dolist (mark gnus-agent-download-marks)
2447             (let ((arts (cdr (assq mark (gnus-info-marks
2448                                          (setq info (gnus-get-info group)))))))
2449               (when arts
2450                 (setq marked-articles (nconc (gnus-uncompress-range arts)
2451                                              marked-articles))
2452                 ))))
2453         (setq marked-articles (sort marked-articles '<))
2454
2455         ;; Fetch any new articles from the server
2456         (setq articles (gnus-agent-fetch-headers group))
2457
2458         ;; Merge new articles with marked
2459         (setq articles (sort (append marked-articles articles) '<))
2460
2461         (when articles
2462           ;; Parse them and see which articles we want to fetch.
2463           (setq gnus-newsgroup-dependencies
2464                 (or gnus-newsgroup-dependencies
2465                     (make-vector (length articles) 0)))
2466           (setq gnus-newsgroup-headers
2467                 (or gnus-newsgroup-headers
2468                     (gnus-get-newsgroup-headers-xover articles nil nil
2469                                                       group)))
2470           ;; `gnus-agent-overview-buffer' may be killed for
2471           ;; timeout reason.  If so, recreate it.
2472           (gnus-agent-create-buffer)
2473
2474           ;; Figure out how to select articles in this group
2475           (setq category (gnus-group-category group))
2476
2477           (setq predicate
2478                 (gnus-get-predicate
2479                  (gnus-agent-find-parameter group 'agent-predicate)))
2480
2481           ;; If the selection predicate requires scoring, score each header
2482           (unless (memq predicate '(gnus-agent-true gnus-agent-false))
2483             (let ((score-param
2484                    (gnus-agent-find-parameter group 'agent-score-file)))
2485               ;; Translate score-param into real one
2486               (cond
2487                ((not score-param))
2488                ((eq score-param 'file)
2489                 (setq score-param (gnus-all-score-files group)))
2490                ((stringp (car score-param)))
2491                (t
2492                 (setq score-param (list (list score-param)))))
2493               (when score-param
2494                 (gnus-score-headers score-param))))
2495
2496           (unless (and (eq predicate 'gnus-agent-false)
2497                        (not marked-articles))
2498             (let ((arts (list nil)))
2499               (let ((arts-tail arts)
2500                     (alist (gnus-agent-load-alist group))
2501                     (marked-articles marked-articles)
2502                     (gnus-newsgroup-headers gnus-newsgroup-headers))
2503                 (while (setq gnus-headers (pop gnus-newsgroup-headers))
2504                   (let ((num (mail-header-number gnus-headers)))
2505                     ;; Determine if this article is already in the cache
2506                     (while (and alist
2507                                 (> num (caar alist)))
2508                       (setq alist (cdr alist)))
2509
2510                     (unless (and (eq num (caar alist))
2511                                  (cdar alist))
2512
2513                       ;; Determine if this article was marked for download.
2514                       (while (and marked-articles
2515                                   (> num (car marked-articles)))
2516                         (setq marked-articles
2517                               (cdr marked-articles)))
2518
2519                       ;; When this article is marked, or selected by the
2520                       ;; predicate, add it to the download list
2521                       (when (or (eq num (car marked-articles))
2522                                 (let ((gnus-score
2523                                        (or (cdr
2524                                             (assq num gnus-newsgroup-scored))
2525                                            gnus-summary-default-score))
2526                                       (gnus-agent-long-article
2527                                        (gnus-agent-find-parameter
2528                                         group 'agent-long-article))
2529                                       (gnus-agent-short-article
2530                                        (gnus-agent-find-parameter
2531                                         group 'agent-short-article))
2532                                       (gnus-agent-low-score
2533                                        (gnus-agent-find-parameter
2534                                         group 'agent-low-score))
2535                                       (gnus-agent-high-score
2536                                        (gnus-agent-find-parameter
2537                                         group 'agent-high-score))
2538                                       (gnus-agent-expire-days
2539                                        (gnus-agent-find-parameter
2540                                         group 'agent-days-until-old)))
2541                                   (funcall predicate)))
2542                         (gnus-agent-append-to-list arts-tail num))))))
2543
2544               (let (fetched-articles)
2545                 ;; Fetch all selected articles
2546                 (setq gnus-newsgroup-undownloaded
2547                       (gnus-sorted-ndifference
2548                        gnus-newsgroup-undownloaded
2549                        (setq fetched-articles
2550                              (if (cdr arts)
2551                                  (gnus-agent-fetch-articles group (cdr arts))
2552                                nil))))
2553
2554                 (let ((unfetched-articles
2555                        (gnus-sorted-ndifference (cdr arts) fetched-articles)))
2556                   (if gnus-newsgroup-active
2557                       ;; Update the summary buffer
2558                       (progn
2559                         (dolist (article marked-articles)
2560                           (gnus-summary-set-agent-mark article t))
2561                         (dolist (article fetched-articles)
2562                           (when gnus-agent-mark-unread-after-downloaded
2563                             (setq gnus-newsgroup-downloadable
2564                                   (delq article gnus-newsgroup-downloadable))
2565                             (gnus-summary-mark-article
2566                              article gnus-unread-mark))
2567                           (when (gnus-summary-goto-subject article nil t)
2568                             (gnus-summary-update-download-mark article)))
2569                         (dolist (article unfetched-articles)
2570                           (gnus-summary-mark-article
2571                            article gnus-canceled-mark)))
2572
2573                     ;; Update the group buffer.
2574
2575                     ;; When some, or all, of the marked articles came
2576                     ;; from the download mark.  Remove that mark.  I
2577                     ;; didn't do this earlier as I only want to remove
2578                     ;; the marks after the fetch is completed.
2579
2580                     (dolist (mark gnus-agent-download-marks)
2581                       (when (eq mark 'download)
2582                         (let ((marked-arts
2583                                (assq mark (gnus-info-marks
2584                                            (setq info (gnus-get-info group))))))
2585                           (when (cdr marked-arts)
2586                             (setq marks
2587                                   (delq marked-arts (gnus-info-marks info)))
2588                             (gnus-info-set-marks info marks)))))
2589                     (let ((read (gnus-info-read
2590                                  (or info (setq info (gnus-get-info group))))))
2591                       (gnus-info-set-read
2592                        info (gnus-add-to-range read unfetched-articles)))
2593
2594                     (gnus-group-update-group group t)
2595                     (sit-for 0)
2596
2597                     (gnus-dribble-enter
2598                      (concat "(gnus-group-set-info '"
2599                              (gnus-prin1-to-string info)
2600                              ")")
2601                      (concat "^(gnus-group-set-info '(\""
2602                              (regexp-quote group) "\""))))))))))))
2603
2604 ;;;
2605 ;;; Agent Category Mode
2606 ;;;
2607
2608 (defvar gnus-category-mode-hook nil
2609   "Hook run in `gnus-category-mode' buffers.")
2610
2611 (defvar gnus-category-line-format "     %(%20c%): %g\n"
2612   "Format of category lines.
2613
2614 Valid specifiers include:
2615 %c  Topic name (string)
2616 %g  The number of groups in the topic (integer)
2617
2618 General format specifiers can also be used.  See Info node
2619 `(gnus)Formatting Variables'.")
2620
2621 (defvar gnus-category-mode-line-format "Gnus: %%b"
2622   "The format specification for the category mode line.")
2623
2624 (defvar gnus-agent-predicate 'false
2625   "The selection predicate used when no other source is available.")
2626
2627 (defvar gnus-agent-short-article 500
2628   "Articles that have fewer lines than this are short.")
2629
2630 (defvar gnus-agent-long-article 1000
2631   "Articles that have more lines than this are long.")
2632
2633 (defvar gnus-agent-low-score 0
2634   "Articles that have a score lower than this have a low score.")
2635
2636 (defvar gnus-agent-high-score 0
2637   "Articles that have a score higher than this have a high score.")
2638
2639
2640 ;;; Internal variables.
2641
2642 (defvar gnus-category-buffer "*Agent Category*")
2643
2644 (defvar gnus-category-line-format-alist
2645   `((?c gnus-tmp-name ?s)
2646     (?g gnus-tmp-groups ?d)))
2647
2648 (defvar gnus-category-mode-line-format-alist
2649   `((?u user-defined ?s)))
2650
2651 (defvar gnus-category-line-format-spec nil)
2652 (defvar gnus-category-mode-line-format-spec nil)
2653
2654 (defvar gnus-category-mode-map nil)
2655 (put 'gnus-category-mode 'mode-class 'special)
2656
2657 (unless gnus-category-mode-map
2658   (setq gnus-category-mode-map (make-sparse-keymap))
2659   (suppress-keymap gnus-category-mode-map)
2660
2661   (gnus-define-keys gnus-category-mode-map
2662     "q" gnus-category-exit
2663     "k" gnus-category-kill
2664     "c" gnus-category-copy
2665     "a" gnus-category-add
2666     "e" gnus-agent-customize-category
2667     "p" gnus-category-edit-predicate
2668     "g" gnus-category-edit-groups
2669     "s" gnus-category-edit-score
2670     "l" gnus-category-list
2671
2672     "\C-c\C-i" gnus-info-find-node
2673     "\C-c\C-b" gnus-bug))
2674
2675 (defvar gnus-category-menu-hook nil
2676   "*Hook run after the creation of the menu.")
2677
2678 (defun gnus-category-make-menu-bar ()
2679   (gnus-turn-off-edit-menu 'category)
2680   (unless (boundp 'gnus-category-menu)
2681     (easy-menu-define
2682      gnus-category-menu gnus-category-mode-map ""
2683      '("Categories"
2684        ["Add" gnus-category-add t]
2685        ["Kill" gnus-category-kill t]
2686        ["Copy" gnus-category-copy t]
2687        ["Edit category" gnus-agent-customize-category t]
2688        ["Edit predicate" gnus-category-edit-predicate t]
2689        ["Edit score" gnus-category-edit-score t]
2690        ["Edit groups" gnus-category-edit-groups t]
2691        ["Exit" gnus-category-exit t]))
2692
2693     (gnus-run-hooks 'gnus-category-menu-hook)))
2694
2695 (defun gnus-category-mode ()
2696   "Major mode for listing and editing agent categories.
2697
2698 All normal editing commands are switched off.
2699 \\<gnus-category-mode-map>
2700 For more in-depth information on this mode, read the manual
2701 \(`\\[gnus-info-find-node]').
2702
2703 The following commands are available:
2704
2705 \\{gnus-category-mode-map}"
2706   (interactive)
2707   (when (gnus-visual-p 'category-menu 'menu)
2708     (gnus-category-make-menu-bar))
2709   (kill-all-local-variables)
2710   (gnus-simplify-mode-line)
2711   (setq major-mode 'gnus-category-mode)
2712   (setq mode-name "Category")
2713   (gnus-set-default-directory)
2714   (setq mode-line-process nil)
2715   (use-local-map gnus-category-mode-map)
2716   (buffer-disable-undo)
2717   (setq truncate-lines t)
2718   (setq buffer-read-only t)
2719   (gnus-run-mode-hooks 'gnus-category-mode-hook))
2720
2721 (defalias 'gnus-category-position-point 'gnus-goto-colon)
2722
2723 (defun gnus-category-insert-line (category)
2724   (let* ((gnus-tmp-name (format "%s" (car category)))
2725          (gnus-tmp-groups (length (gnus-agent-cat-groups category))))
2726     (beginning-of-line)
2727     (gnus-add-text-properties
2728      (point)
2729      (prog1 (1+ (point))
2730        ;; Insert the text.
2731        (eval gnus-category-line-format-spec))
2732      (list 'gnus-category gnus-tmp-name))))
2733
2734 (defun gnus-enter-category-buffer ()
2735   "Go to the Category buffer."
2736   (interactive)
2737   (gnus-category-setup-buffer)
2738   (gnus-configure-windows 'category)
2739   (gnus-category-prepare))
2740
2741 (defun gnus-category-setup-buffer ()
2742   (unless (get-buffer gnus-category-buffer)
2743     (with-current-buffer (gnus-get-buffer-create gnus-category-buffer)
2744       (gnus-category-mode))))
2745
2746 (defun gnus-category-prepare ()
2747   (gnus-set-format 'category-mode)
2748   (gnus-set-format 'category t)
2749   (let ((alist gnus-category-alist)
2750         (buffer-read-only nil))
2751     (erase-buffer)
2752     (while alist
2753       (gnus-category-insert-line (pop alist)))
2754     (goto-char (point-min))
2755     (gnus-category-position-point)))
2756
2757 (defun gnus-category-name ()
2758   (or (intern (get-text-property (point-at-bol) 'gnus-category))
2759       (error "No category on the current line")))
2760
2761 (defun gnus-category-read ()
2762   "Read the category alist."
2763   (setq gnus-category-alist
2764         (or
2765          (with-temp-buffer
2766            (ignore-errors
2767             (nnheader-insert-file-contents (nnheader-concat gnus-agent-directory "lib/categories"))
2768             (goto-char (point-min))
2769             ;; This code isn't temp, it will be needed so long as
2770             ;; anyone may be migrating from an older version.
2771
2772             ;; Once we're certain that people will not revert to an
2773             ;; earlier version, we can take out the old-list code in
2774             ;; gnus-category-write.
2775             (let* ((old-list (read (current-buffer)))
2776                    (new-list (ignore-errors (read (current-buffer)))))
2777               (if new-list
2778                   new-list
2779                 ;; Convert from a positional list to an alist.
2780                 (mapcar
2781                  (lambda (c)
2782                    (setcdr c
2783                            (delq nil
2784                                  (gnus-mapcar
2785                                   (lambda (valu symb)
2786                                     (if valu
2787                                         (cons symb valu)))
2788                                   (cdr c)
2789                                   '(agent-predicate agent-score-file agent-groups))))
2790                    c)
2791                  old-list)))))
2792          (list (gnus-agent-cat-make 'default 'short)))))
2793
2794 (defun gnus-category-write ()
2795   "Write the category alist."
2796   (setq gnus-category-predicate-cache nil
2797         gnus-category-group-cache nil)
2798   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
2799   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
2800     ;; This prin1 is temporary.  It exists so that people can revert
2801     ;; to an earlier version of gnus-agent.
2802     (prin1 (mapcar (lambda (c)
2803               (list (car c)
2804                     (cdr (assoc 'agent-predicate c))
2805                     (cdr (assoc 'agent-score-file c))
2806                     (cdr (assoc 'agent-groups c))))
2807                    gnus-category-alist)
2808            (current-buffer))
2809     (newline)
2810     (prin1 gnus-category-alist (current-buffer))))
2811
2812 (defun gnus-category-edit-predicate (category)
2813   "Edit the predicate for CATEGORY."
2814   (interactive (list (gnus-category-name)))
2815   (let ((info (assq category gnus-category-alist)))
2816     (gnus-edit-form
2817      (gnus-agent-cat-predicate info)
2818      (format "Editing the select predicate for category %s" category)
2819      `(lambda (predicate)
2820         ;; Avoid run-time execution of setf form
2821         ;; (setf (gnus-agent-cat-predicate (assq ',category gnus-category-alist))
2822         ;;       predicate)
2823         ;; use its expansion instead:
2824         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2825                                      'agent-predicate predicate)
2826
2827         (gnus-category-write)
2828         (gnus-category-list)))))
2829
2830 (defun gnus-category-edit-score (category)
2831   "Edit the score expression for CATEGORY."
2832   (interactive (list (gnus-category-name)))
2833   (let ((info (assq category gnus-category-alist)))
2834     (gnus-edit-form
2835      (gnus-agent-cat-score-file info)
2836      (format "Editing the score expression for category %s" category)
2837      `(lambda (score-file)
2838         ;; Avoid run-time execution of setf form
2839         ;; (setf (gnus-agent-cat-score-file (assq ',category gnus-category-alist))
2840         ;;       score-file)
2841         ;; use its expansion instead:
2842         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2843                                      'agent-score-file score-file)
2844
2845         (gnus-category-write)
2846         (gnus-category-list)))))
2847
2848 (defun gnus-category-edit-groups (category)
2849   "Edit the group list for CATEGORY."
2850   (interactive (list (gnus-category-name)))
2851   (let ((info (assq category gnus-category-alist)))
2852     (gnus-edit-form
2853      (gnus-agent-cat-groups info)
2854      (format "Editing the group list for category %s" category)
2855      `(lambda (groups)
2856         ;; Avoid run-time execution of setf form
2857         ;; (setf (gnus-agent-cat-groups (assq ',category gnus-category-alist))
2858         ;;       groups)
2859         ;; use its expansion instead:
2860         (gnus-agent-set-cat-groups (assq ',category gnus-category-alist)
2861                                    groups)
2862
2863         (gnus-category-write)
2864         (gnus-category-list)))))
2865
2866 (defun gnus-category-kill (category)
2867   "Kill the current category."
2868   (interactive (list (gnus-category-name)))
2869   (let ((info (assq category gnus-category-alist))
2870         (buffer-read-only nil))
2871     (gnus-delete-line)
2872     (setq gnus-category-alist (delq info gnus-category-alist))
2873     (gnus-category-write)))
2874
2875 (defun gnus-category-copy (category to)
2876   "Copy the current category."
2877   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
2878   (let ((info (assq category gnus-category-alist)))
2879     (push (let ((newcat (gnus-copy-sequence info)))
2880             (setf (gnus-agent-cat-name newcat) to)
2881             (setf (gnus-agent-cat-groups newcat) nil)
2882             newcat)
2883           gnus-category-alist)
2884     (gnus-category-write)
2885     (gnus-category-list)))
2886
2887 (defun gnus-category-add (category)
2888   "Create a new category."
2889   (interactive "SCategory name: ")
2890   (when (assq category gnus-category-alist)
2891     (error "Category %s already exists" category))
2892   (push (gnus-agent-cat-make category)
2893         gnus-category-alist)
2894   (gnus-category-write)
2895   (gnus-category-list))
2896
2897 (defun gnus-category-list ()
2898   "List all categories."
2899   (interactive)
2900   (gnus-category-prepare))
2901
2902 (defun gnus-category-exit ()
2903   "Return to the group buffer."
2904   (interactive)
2905   (kill-buffer (current-buffer))
2906   (gnus-configure-windows 'group t))
2907
2908 ;; To avoid having 8-bit characters in the source file.
2909 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
2910
2911 (defvar gnus-category-predicate-alist
2912   '((spam . gnus-agent-spam-p)
2913     (short . gnus-agent-short-p)
2914     (long . gnus-agent-long-p)
2915     (low . gnus-agent-low-scored-p)
2916     (high . gnus-agent-high-scored-p)
2917     (read . gnus-agent-read-p)
2918     (true . gnus-agent-true)
2919     (false . gnus-agent-false))
2920   "Mapping from short score predicate symbols to predicate functions.")
2921
2922 (defun gnus-agent-spam-p ()
2923   "Say whether an article is spam or not."
2924   (unless gnus-agent-spam-hashtb
2925     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
2926   (if (not (equal (mail-header-references gnus-headers) ""))
2927       nil
2928     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
2929       (prog1
2930           (gnus-gethash string gnus-agent-spam-hashtb)
2931         (gnus-sethash string t gnus-agent-spam-hashtb)))))
2932
2933 (defun gnus-agent-short-p ()
2934   "Say whether an article is short or not."
2935   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
2936
2937 (defun gnus-agent-long-p ()
2938   "Say whether an article is long or not."
2939   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
2940
2941 (defun gnus-agent-low-scored-p ()
2942   "Say whether an article has a low score or not."
2943   (< gnus-score gnus-agent-low-score))
2944
2945 (defun gnus-agent-high-scored-p ()
2946   "Say whether an article has a high score or not."
2947   (> gnus-score gnus-agent-high-score))
2948
2949 (defun gnus-agent-read-p ()
2950   "Say whether an article is read or not."
2951   (gnus-member-of-range (mail-header-number gnus-headers)
2952                         (gnus-info-read (gnus-get-info gnus-newsgroup-name))))
2953
2954 (defun gnus-category-make-function (predicate)
2955   "Make a function from PREDICATE."
2956   (let ((func (gnus-category-make-function-1 predicate)))
2957     (if (and (= (length func) 1)
2958              (symbolp (car func)))
2959         (car func)
2960       (gnus-byte-compile `(lambda () ,func)))))
2961
2962 (defun gnus-agent-true ()
2963   "Return t."
2964   t)
2965
2966 (defun gnus-agent-false ()
2967   "Return nil."
2968   nil)
2969
2970 (defun gnus-category-make-function-1 (predicate)
2971   "Make a function from PREDICATE."
2972   (cond
2973    ;; Functions are just returned as is.
2974    ((or (symbolp predicate)
2975         (functionp predicate))
2976     `(,(or (cdr (assq predicate gnus-category-predicate-alist))
2977            predicate)))
2978    ;; More complex predicate.
2979    ((consp predicate)
2980     `(,(cond
2981         ((memq (car predicate) '(& and))
2982          'and)
2983         ((memq (car predicate) '(| or))
2984          'or)
2985         ((memq (car predicate) gnus-category-not)
2986          'not))
2987       ,@(mapcar 'gnus-category-make-function-1 (cdr predicate))))
2988    (t
2989     (error "Unknown predicate type: %s" predicate))))
2990
2991 (defun gnus-get-predicate (predicate)
2992   "Return the function implementing PREDICATE."
2993   (or (cdr (assoc predicate gnus-category-predicate-cache))
2994       (let ((func (gnus-category-make-function predicate)))
2995         (setq gnus-category-predicate-cache
2996               (nconc gnus-category-predicate-cache
2997                      (list (cons predicate func))))
2998         func)))
2999
3000 (defun gnus-predicate-implies-unread (predicate)
3001   "Say whether PREDICATE implies unread articles only.
3002 It is okay to miss some cases, but there must be no false positives.
3003 That is, if this predicate returns true, then indeed the predicate must
3004 return only unread articles."
3005   (eq t (gnus-function-implies-unread-1
3006          (gnus-category-make-function-1 predicate))))
3007
3008 (defun gnus-function-implies-unread-1 (function)
3009   "Recursively evaluate a predicate function to determine whether it can select
3010 any read articles.  Returns t if the function is known to never
3011 return read articles, nil when it is known to always return read
3012 articles, and t_nil when the function may return both read and unread
3013 articles."
3014   (let ((func (car function))
3015         (args (mapcar 'gnus-function-implies-unread-1 (cdr function))))
3016     (cond ((eq func 'and)
3017            (cond ((memq t args) ; if any argument returns only unread articles
3018                   ;; then that argument constrains the result to only unread articles.
3019                   t)
3020                  ((memq 't_nil args) ; if any argument is indeterminate
3021                   ;; then the result is indeterminate
3022                   't_nil)))
3023           ((eq func 'or)
3024            (cond ((memq nil args) ; if any argument returns read articles
3025                   ;; then that argument ensures that the results includes read articles.
3026                   nil)
3027                  ((memq 't_nil args) ; if any argument is indeterminate
3028                   ;; then that argument ensures that the results are indeterminate
3029                   't_nil)
3030                  (t ; if all arguments return only unread articles
3031                   ;; then the result returns only unread articles
3032                   t)))
3033           ((eq func 'not)
3034            (cond ((eq (car args) 't_nil) ; if the argument is indeterminate
3035                   ; then the result is indeterminate
3036                   (car args))
3037                  (t ; otherwise
3038                   ; toggle the result to be the opposite of the argument
3039                   (not (car args)))))
3040           ((eq func 'gnus-agent-read-p)
3041            nil) ; The read predicate NEVER returns unread articles
3042           ((eq func 'gnus-agent-false)
3043            t) ; The false predicate returns t as the empty set excludes all read articles
3044           ((eq func 'gnus-agent-true)
3045            nil) ; The true predicate ALWAYS returns read articles
3046           ((catch 'found-match
3047              (let ((alist gnus-category-predicate-alist))
3048                (while alist
3049                  (if (eq func (cdar alist))
3050                      (throw 'found-match t)
3051                    (setq alist (cdr alist))))))
3052            't_nil) ; All other predicates return read and unread articles
3053           (t
3054            (error "Unknown predicate function: %s" function)))))
3055
3056 (defun gnus-group-category (group)
3057   "Return the category GROUP belongs to."
3058   (unless gnus-category-group-cache
3059     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
3060     (let ((cs gnus-category-alist)
3061           groups cat)
3062       (while (setq cat (pop cs))
3063         (setq groups (gnus-agent-cat-groups cat))
3064         (while groups
3065           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
3066   (or (gnus-gethash group gnus-category-group-cache)
3067       (assq 'default gnus-category-alist)))
3068
3069 (defun gnus-agent-expire-group (group &optional articles force)
3070   "Expire all old articles in GROUP.
3071 If you want to force expiring of certain articles, this function can
3072 take ARTICLES, and FORCE parameters as well.
3073
3074 The articles on which the expiration process runs are selected as follows:
3075   if ARTICLES is null, all read and unmarked articles.
3076   if ARTICLES is t, all articles.
3077   if ARTICLES is a list, just those articles.
3078 FORCE is equivalent to setting the expiration predicates to true."
3079   (interactive (list (gnus-agent-read-group)))
3080
3081   (if (not group)
3082       (gnus-agent-expire articles group force)
3083     (let ( ;; Bind gnus-agent-expire-stats to enable tracking of
3084           ;; expiration statistics of this single group
3085           (gnus-agent-expire-stats (list 0 0 0.0)))
3086       (if (or (not (eq articles t))
3087               (yes-or-no-p
3088                (concat "Are you sure that you want to "
3089                        "expire all articles in " group "? ")))
3090           (let ((gnus-command-method (gnus-find-method-for-group group))
3091                 (overview (gnus-get-buffer-create " *expire overview*"))
3092                 orig)
3093             (unwind-protect
3094                 (let ((active-file (gnus-agent-lib-file "active")))
3095                   (when (file-exists-p active-file)
3096                     (with-temp-buffer
3097                       (nnheader-insert-file-contents active-file)
3098                       (gnus-active-to-gnus-format
3099                        gnus-command-method
3100                        (setq orig (gnus-make-hashtable
3101                                    (count-lines (point-min) (point-max))))))
3102                     (save-excursion
3103                       (gnus-agent-expire-group-1
3104                        group overview (gnus-gethash-safe group orig)
3105                        articles force))))
3106               (kill-buffer overview))))
3107       (gnus-message 4 "%s" (gnus-agent-expire-done-message)))))
3108
3109 (defun gnus-agent-expire-group-1 (group overview active articles force)
3110   ;; Internal function - requires caller to have set
3111   ;; gnus-command-method, initialized overview buffer, and to have
3112   ;; provided a non-nil active
3113
3114   (let ((dir (gnus-agent-group-pathname group))
3115         (file-name-coding-system nnmail-pathname-coding-system)
3116         (decoded (gnus-agent-decoded-group-name group)))
3117     (gnus-agent-with-refreshed-group
3118      group
3119      (when (boundp 'gnus-agent-expire-current-dirs)
3120        (set 'gnus-agent-expire-current-dirs
3121             (cons dir
3122                   (symbol-value 'gnus-agent-expire-current-dirs))))
3123
3124      (if (and (not force)
3125               (eq 'DISABLE (gnus-agent-find-parameter group
3126                                                       'agent-enable-expiration)))
3127          (gnus-message 5 "Expiry skipping over %s" decoded)
3128        (gnus-message 5 "Expiring articles in %s" decoded)
3129        (gnus-agent-load-alist group)
3130        (let* ((bytes-freed 0)
3131               (size-files-deleted 0.0)
3132               (files-deleted 0)
3133               (nov-entries-deleted 0)
3134               (info (gnus-get-info group))
3135               (alist gnus-agent-article-alist)
3136               (day (- (time-to-days (current-time))
3137                       (gnus-agent-find-parameter group 'agent-days-until-old)))
3138               (specials (if (and alist
3139                                  (not force))
3140                             ;; This could be a bit of a problem.  I need to
3141                             ;; keep the last article to avoid refetching
3142                             ;; headers when using nntp in the backend.  At
3143                             ;; the same time, if someone uses a backend
3144                             ;; that supports article moving then I may have
3145                             ;; to remove the last article to complete the
3146                             ;; move.  Right now, I'm going to assume that
3147                             ;; FORCE overrides specials.
3148                             (list (caar (last alist)))))
3149               (unreads ;; Articles that are excluded from the
3150                ;; expiration process
3151                (cond (gnus-agent-expire-all
3152                       ;; All articles are marked read by global decree
3153                       nil)
3154                      ((eq articles t)
3155                       ;; All articles are marked read by function
3156                       ;; parameter
3157                       nil)
3158                      ((not articles)
3159                       ;; Unread articles are marked protected from
3160                       ;; expiration Don't call
3161                       ;; gnus-list-of-unread-articles as it returns
3162                       ;; articles that have not been fetched into the
3163                       ;; agent.
3164                       (ignore-errors
3165                         (gnus-agent-unread-articles group)))
3166                      (t
3167                       ;; All articles EXCEPT those named by the caller
3168                       ;; are protected from expiration
3169                       (gnus-sorted-difference
3170                        (gnus-uncompress-range
3171                         (cons (caar alist)
3172                               (caar (last alist))))
3173                        (sort articles '<)))))
3174               (marked ;; More articles that are excluded from the
3175                ;; expiration process
3176                (cond (gnus-agent-expire-all
3177                       ;; All articles are unmarked by global decree
3178                       nil)
3179                      ((eq articles t)
3180                       ;; All articles are unmarked by function
3181                       ;; parameter
3182                       nil)
3183                      (articles
3184                       ;; All articles may as well be unmarked as the
3185                       ;; unreads list already names the articles we are
3186                       ;; going to keep
3187                       nil)
3188                      (t
3189                       ;; Ticked and/or dormant articles are excluded
3190                       ;; from expiration
3191                       (nconc
3192                        (gnus-uncompress-range
3193                         (cdr (assq 'tick (gnus-info-marks info))))
3194                        (gnus-uncompress-range
3195                         (cdr (assq 'dormant
3196                                    (gnus-info-marks info))))))))
3197               (nov-file (concat dir ".overview"))
3198               (cnt 0)
3199               (completed -1)
3200               dlist
3201               type)
3202
3203          ;; The normal article alist contains elements that look like
3204          ;; (article# .  fetch_date) I need to combine other
3205          ;; information with this list.  For example, a flag indicating
3206          ;; that a particular article MUST BE KEPT.  To do this, I'm
3207          ;; going to transform the elements to look like (article#
3208          ;; fetch_date keep_flag NOV_entry_position) Later, I'll reverse
3209          ;; the process to generate the expired article alist.
3210
3211          ;; Convert the alist elements to (article# fetch_date nil
3212          ;; nil).
3213          (setq dlist (mapcar (lambda (e)
3214                                (list (car e) (cdr e) nil nil)) alist))
3215
3216          ;; Convert the keep lists to elements that look like (article#
3217          ;; nil keep_flag nil) then append it to the expanded dlist
3218          ;; These statements are sorted by ascending precedence of the
3219          ;; keep_flag.
3220          (setq dlist (nconc dlist
3221                             (mapcar (lambda (e)
3222                                       (list e nil 'unread  nil))
3223                                     unreads)))
3224          (setq dlist (nconc dlist
3225                             (mapcar (lambda (e)
3226                                       (list e nil 'marked  nil))
3227                                     marked)))
3228          (setq dlist (nconc dlist
3229                             (mapcar (lambda (e)
3230                                       (list e nil 'special nil))
3231                                     specials)))
3232
3233          (set-buffer overview)
3234          (erase-buffer)
3235          (buffer-disable-undo)
3236          (when (file-exists-p nov-file)
3237            (gnus-message 7 "gnus-agent-expire: Loading overview...")
3238            (nnheader-insert-file-contents nov-file)
3239            (goto-char (point-min))
3240
3241            (let (p)
3242              (while (< (setq p (point)) (point-max))
3243                (condition-case nil
3244                    ;; If I successfully read an integer (the plus zero
3245                    ;; ensures a numeric type), append the position
3246                    ;; to the list
3247                    (push (list (+ 0 (read (current-buffer))) nil nil
3248                                p)
3249                          dlist)
3250                  (error
3251                   (gnus-message 1 "gnus-agent-expire: read error \
3252 occurred when reading expression at %s in %s.  Skipping to next \
3253 line." (point) nov-file)))
3254                ;; Whether I succeeded, or failed, it doesn't matter.
3255                ;; Move to the next line then try again.
3256                (forward-line 1)))
3257
3258            (gnus-message
3259             7 "gnus-agent-expire: Loading overview... Done"))
3260          (set-buffer-modified-p nil)
3261
3262          ;; At this point, all of the information is in dlist.  The
3263          ;; only problem is that much of it is spread across multiple
3264          ;; entries.  Sort then MERGE!!
3265          (gnus-message 7 "gnus-agent-expire: Sorting entries... ")
3266          ;; If two entries have the same article-number then sort by
3267          ;; ascending keep_flag.
3268          (let ((special 0)
3269                (marked 1)
3270                (unread 2))
3271            (setq dlist
3272                  (sort dlist
3273                        (lambda (a b)
3274                          (cond ((< (nth 0 a) (nth 0 b))
3275                                 t)
3276                                ((> (nth 0 a) (nth 0 b))
3277                                 nil)
3278                                (t
3279                                 (let ((a (or (symbol-value (nth 2 a))
3280                                              3))
3281                                       (b (or (symbol-value (nth 2 b))
3282                                              3)))
3283                                   (<= a b))))))))
3284          (gnus-message 7 "gnus-agent-expire: Sorting entries... Done")
3285          (gnus-message 7 "gnus-agent-expire: Merging entries... ")
3286          (let ((dlist dlist))
3287            (while (cdr dlist)           ; I'm not at the end-of-list
3288              (if (eq (caar dlist) (caadr dlist))
3289                  (let ((first (cdr (car dlist)))
3290                        (secnd (cdr (cadr dlist))))
3291                    (setcar first (or (car first)
3292                                      (car secnd))) ; fetch_date
3293                    (setq first (cdr first)
3294                          secnd (cdr secnd))
3295                    (setcar first (or (car first)
3296                                      (car secnd))) ; Keep_flag
3297                    (setq first (cdr first)
3298                          secnd (cdr secnd))
3299                    (setcar first (or (car first)
3300                                      (car secnd))) ; NOV_entry_position
3301
3302                    (setcdr dlist (cddr dlist)))
3303                (setq dlist (cdr dlist)))))
3304
3305          ;; Check the order of the entry positions.  They should be in
3306          ;; ascending order.  If they aren't, the positions must be
3307          ;; converted to markers.
3308          (when (catch 'sort-results
3309                  (let ((dlist dlist)
3310                        (prev-pos -1)
3311                        pos)
3312                    (while dlist
3313                      (if (setq pos (nth 3 (pop dlist)))
3314                          (if (< pos prev-pos)
3315                              (throw 'sort-results 'unsorted)
3316                            (setq prev-pos pos))))))
3317            (gnus-message 7 "gnus-agent-expire: Unsorted overview; inserting markers to compensate.")
3318            (mapc (lambda (entry)
3319                      (let ((pos (nth 3 entry)))
3320                        (if pos
3321                            (setf (nth 3 entry)
3322                                  (set-marker (make-marker)
3323                                              pos)))))
3324                    dlist))
3325
3326          (gnus-message 7 "gnus-agent-expire: Merging entries... Done")
3327
3328          (let* ((len (float (length dlist)))
3329                 (alist (list nil))
3330                 (tail-alist alist)
3331                 (position-offset 0)
3332                 )
3333
3334            (while dlist
3335              (let ((new-completed (truncate (* 100.0
3336                                                (/ (setq cnt (1+ cnt))
3337                                                   len))))
3338                    message-log-max)
3339                (when (> new-completed completed)
3340                  (setq completed new-completed)
3341                  (gnus-message 7 "%3d%% completed..."  completed)))
3342              (let* ((entry          (car dlist))
3343                     (article-number (nth 0 entry))
3344                     (fetch-date     (nth 1 entry))
3345                     (keep           (nth 2 entry))
3346                     (marker         (nth 3 entry)))
3347
3348                (cond
3349                 ;; Kept articles are unread, marked, or special.
3350                 (keep
3351                  (gnus-agent-message 10
3352                                      "gnus-agent-expire: %s:%d: Kept %s article%s."
3353                                      decoded article-number keep (if fetch-date " and file" ""))
3354                  (when fetch-date
3355                    (unless (file-exists-p
3356                             (concat dir (number-to-string
3357                                          article-number)))
3358                      (setf (nth 1 entry) nil)
3359                      (gnus-agent-message 3 "gnus-agent-expire cleared \
3360 download flag on %s:%d as the cached article file is missing."
3361                                          decoded (caar dlist)))
3362                    (unless marker
3363                      (gnus-message 1 "gnus-agent-expire detected a \
3364 missing NOV entry.  Run gnus-agent-regenerate-group to restore it.")))
3365                  (gnus-agent-append-to-list
3366                   tail-alist
3367                   (cons article-number fetch-date)))
3368
3369                 ;; The following articles are READ, UNMARKED, and
3370                 ;; ORDINARY.  See if they can be EXPIRED!!!
3371                 ((setq type
3372                        (cond
3373                         ((not (integerp fetch-date))
3374                          'read) ;; never fetched article (may expire
3375                         ;; right now)
3376                         ((not (file-exists-p
3377                                (concat dir (number-to-string
3378                                             article-number))))
3379                          (setf (nth 1 entry) nil)
3380                          'externally-expired) ;; Can't find the cached
3381                         ;; article.  Handle case
3382                         ;; as though this article
3383                         ;; was never fetched.
3384
3385                         ;; We now have the arrival day, so we see
3386                         ;; whether it's old enough to be expired.
3387                         ((< fetch-date day)
3388                          'expired)
3389                         (force
3390                          'forced)))
3391
3392                  ;; I found some reason to expire this entry.
3393
3394                  (let ((actions nil))
3395                    (when (memq type '(forced expired))
3396                      (ignore-errors     ; Just being paranoid.
3397                        (let* ((file-name (nnheader-concat dir (number-to-string
3398                                                                article-number)))
3399                               (size (float (nth 7 (file-attributes file-name)))))
3400                          (incf bytes-freed size)
3401                          (incf size-files-deleted size)
3402                          (incf files-deleted)
3403                          (delete-file file-name))
3404                        (push "expired cached article" actions))
3405                      (setf (nth 1 entry) nil)
3406                      )
3407
3408                    (when marker
3409                      (push "NOV entry removed" actions)
3410
3411                      (goto-char (if (markerp marker)
3412                                     marker
3413                                   (- marker position-offset)))
3414
3415                      (incf nov-entries-deleted)
3416
3417                      (let* ((from (point-at-bol))
3418                             (to (progn (forward-line 1) (point)))
3419                             (freed (- to from)))
3420                        (incf bytes-freed freed)
3421                        (incf position-offset freed)
3422                        (delete-region from to)))
3423
3424                    ;; If considering all articles is set, I can only
3425                    ;; expire article IDs that are no longer in the
3426                    ;; active range (That is, articles that precede the
3427                    ;; first article in the new alist).
3428                    (if (and gnus-agent-consider-all-articles
3429                             (>= article-number (car active)))
3430                        ;; I have to keep this ID in the alist
3431                        (gnus-agent-append-to-list
3432                         tail-alist (cons article-number fetch-date))
3433                      (push (format "Removed %s article number from \
3434 article alist" type) actions))
3435
3436                    (when actions
3437                      (gnus-agent-message 8 "gnus-agent-expire: %s:%d: %s"
3438                                          decoded article-number
3439                                          (mapconcat 'identity actions ", ")))))
3440                 (t
3441                  (gnus-agent-message
3442                   10 "gnus-agent-expire: %s:%d: Article kept as \
3443 expiration tests failed." decoded article-number)
3444                  (gnus-agent-append-to-list
3445                   tail-alist (cons article-number fetch-date)))
3446                 )
3447
3448                ;; Remove markers as I intend to reuse this buffer again.
3449                (when (and marker
3450                           (markerp marker))
3451                  (set-marker marker nil))
3452
3453                (setq dlist (cdr dlist))))
3454
3455            (setq alist (cdr alist))
3456
3457            (let ((inhibit-quit t))
3458              (unless (equal alist gnus-agent-article-alist)
3459                (setq gnus-agent-article-alist alist)
3460                (gnus-agent-save-alist group))
3461
3462              (when (buffer-modified-p)
3463                (let ((coding-system-for-write
3464                       gnus-agent-file-coding-system))
3465                  (gnus-make-directory dir)
3466                  (write-region (point-min) (point-max) nov-file nil
3467                                'silent)
3468                  ;; clear the modified flag as that I'm not confused by
3469                  ;; its status on the next pass through this routine.
3470                  (set-buffer-modified-p nil)
3471                  (gnus-agent-update-view-total-fetched-for group t)))
3472
3473              (when (eq articles t)
3474                (gnus-summary-update-info))))
3475
3476          (when (boundp 'gnus-agent-expire-stats)
3477            (let ((stats (symbol-value 'gnus-agent-expire-stats)))
3478              (incf (nth 2 stats) bytes-freed)
3479              (incf (nth 1 stats) files-deleted)
3480              (incf (nth 0 stats) nov-entries-deleted)))
3481
3482          (gnus-agent-update-files-total-fetched-for group (- size-files-deleted)))))))
3483
3484 (defun gnus-agent-expire (&optional articles group force)
3485   "Expire all old articles.
3486 If you want to force expiring of certain articles, this function can
3487 take ARTICLES, GROUP and FORCE parameters as well.
3488
3489 The articles on which the expiration process runs are selected as follows:
3490   if ARTICLES is null, all read and unmarked articles.
3491   if ARTICLES is t, all articles.
3492   if ARTICLES is a list, just those articles.
3493 Setting GROUP will limit expiration to that group.
3494 FORCE is equivalent to setting the expiration predicates to true."
3495   (interactive)
3496
3497   (if group
3498       (gnus-agent-expire-group group articles force)
3499     (if (or (not (eq articles t))
3500             (yes-or-no-p "Are you sure that you want to expire all \
3501 articles in every agentized group? "))
3502         (let ((methods (gnus-agent-covered-methods))
3503               ;; Bind gnus-agent-expire-current-dirs to enable tracking
3504               ;; of agent directories.
3505               (gnus-agent-expire-current-dirs nil)
3506               ;; Bind gnus-agent-expire-stats to enable tracking of
3507               ;; expiration statistics across all groups
3508               (gnus-agent-expire-stats (list 0 0 0.0))
3509               gnus-command-method overview orig)
3510           (setq overview (gnus-get-buffer-create " *expire overview*"))
3511           (unwind-protect
3512               (while (setq gnus-command-method (pop methods))
3513                 (let ((active-file (gnus-agent-lib-file "active")))
3514                   (when (file-exists-p active-file)
3515                     (with-temp-buffer
3516                       (nnheader-insert-file-contents active-file)
3517                       (gnus-active-to-gnus-format
3518                        gnus-command-method
3519                        (setq orig (gnus-make-hashtable
3520                                    (count-lines (point-min) (point-max))))))
3521                     (dolist (expiring-group (gnus-groups-from-server
3522                                              gnus-command-method))
3523                       (let* ((active
3524                               (gnus-gethash-safe expiring-group orig)))
3525
3526                         (when active
3527                           (save-excursion
3528                             (gnus-agent-expire-group-1
3529                              expiring-group overview active articles force))))))))
3530             (kill-buffer overview))
3531           (gnus-agent-expire-unagentized-dirs)
3532           (gnus-message 4 "%s" (gnus-agent-expire-done-message))))))
3533
3534 (defun gnus-agent-expire-done-message ()
3535   (if (and (> gnus-verbose 4)
3536            (boundp 'gnus-agent-expire-stats))
3537       (let* ((stats (symbol-value 'gnus-agent-expire-stats))
3538              (size (nth 2 stats))
3539             (units '(B KB MB GB)))
3540         (while (and (> size 1024.0)
3541                     (cdr units))
3542           (setq size (/ size 1024.0)
3543                 units (cdr units)))
3544
3545         (format "Expiry recovered %d NOV entries, deleted %d files,\
3546  and freed %.f %s."
3547                 (nth 0 stats)
3548                 (nth 1 stats)
3549                 size (car units)))
3550     "Expiry...done"))
3551
3552 (defun gnus-agent-expire-unagentized-dirs ()
3553   (when (and gnus-agent-expire-unagentized-dirs
3554              (boundp 'gnus-agent-expire-current-dirs))
3555     (let* ((keep (gnus-make-hashtable))
3556            ;; Formally bind gnus-agent-expire-current-dirs so that the
3557            ;; compiler will not complain about free references.
3558            (gnus-agent-expire-current-dirs
3559             (symbol-value 'gnus-agent-expire-current-dirs))
3560            dir
3561            (file-name-coding-system nnmail-pathname-coding-system))
3562
3563       (gnus-sethash gnus-agent-directory t keep)
3564       (while gnus-agent-expire-current-dirs
3565         (setq dir (pop gnus-agent-expire-current-dirs))
3566         (when (and (stringp dir)
3567                    (file-directory-p dir))
3568           (while (not (gnus-gethash dir keep))
3569             (gnus-sethash dir t keep)
3570             (setq dir (file-name-directory (directory-file-name dir))))))
3571
3572       (let* (to-remove
3573              checker
3574              (checker
3575               (function
3576                (lambda (d)
3577                  "Given a directory, check it and its subdirectories for
3578               membership in the keep hash.  If it isn't found, add
3579               it to to-remove."
3580                  (let ((files (directory-files d))
3581                        file)
3582                    (while (setq file (pop files))
3583                      (cond ((equal file ".") ; Ignore self
3584                             nil)
3585                            ((equal file "..") ; Ignore parent
3586                             nil)
3587                            ((equal file ".overview")
3588                             ;; Directory must contain .overview to be
3589                             ;; agent's cache of a group.
3590                             (let ((d (file-name-as-directory d))
3591                                   r)
3592                               ;; Search ancestor's for last directory NOT
3593                               ;; found in keep hash.
3594                               (while (not (gnus-gethash
3595                                            (setq d (file-name-directory d)) keep))
3596                                 (setq r d
3597                                       d (directory-file-name d)))
3598                               ;; if ANY ancestor was NOT in keep hash and
3599                               ;; it's not already in to-remove, add it to
3600                               ;; to-remove.
3601                               (if (and r
3602                                        (not (member r to-remove)))
3603                                   (push r to-remove))))
3604                            ((file-directory-p (setq file (nnheader-concat d file)))
3605                             (funcall checker file)))))))))
3606         (funcall checker (expand-file-name gnus-agent-directory))
3607
3608         (when (and to-remove
3609                    (or gnus-expert-user
3610                        (gnus-y-or-n-p
3611                         "gnus-agent-expire has identified local directories that are\
3612  not currently required by any agentized group.  Do you wish to consider\
3613  deleting them?")))
3614           (while to-remove
3615             (let ((dir (pop to-remove)))
3616               (if (or gnus-expert-user
3617                       (gnus-y-or-n-p (format "Delete %s? " dir)))
3618                   (let* (delete-recursive
3619                          files f
3620                          (delete-recursive
3621                           (function
3622                            (lambda (f-or-d)
3623                              (ignore-errors
3624                                (if (file-directory-p f-or-d)
3625                                    (condition-case nil
3626                                        (delete-directory f-or-d)
3627                                      (file-error
3628                                       (setq files (directory-files f-or-d))
3629                                       (while files
3630                                         (setq f (pop files))
3631                                         (or (member f '("." ".."))
3632                                             (funcall delete-recursive
3633                                                      (nnheader-concat
3634                                                       f-or-d f))))
3635                                       (delete-directory f-or-d)))
3636                                  (delete-file f-or-d)))))))
3637                     (funcall delete-recursive dir))))))))))
3638
3639 ;;;###autoload
3640 (defun gnus-agent-batch ()
3641   "Start Gnus, send queue and fetch session."
3642   (interactive)
3643   (let ((init-file-user "")
3644         (gnus-always-read-dribble-file t))
3645     (gnus))
3646   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
3647     (gnus-group-send-queue)
3648     (gnus-agent-fetch-session)))
3649
3650 (defun gnus-agent-unread-articles (group)
3651   (let* ((read (gnus-info-read (gnus-get-info group)))
3652          (known (gnus-agent-load-alist group))
3653          (unread (list nil))
3654          (tail-unread unread))
3655     (while (and known read)
3656       (let ((candidate (car (pop known))))
3657         (while (let* ((range (car read))
3658                       (min   (if (numberp range) range (car range)))
3659                       (max   (if (numberp range) range (cdr range))))
3660                  (cond ((or (not min)
3661                             (< candidate min))
3662                         (gnus-agent-append-to-list tail-unread candidate)
3663                         nil)
3664                        ((> candidate max)
3665                         (setq read (cdr read))
3666                         ;; return t so that I always loop one more
3667                         ;; time.  If I just iterated off the end of
3668                         ;; read, min will become nil and the current
3669                         ;; candidate will be added to the unread list.
3670                         t))))))
3671     (while known
3672       (gnus-agent-append-to-list tail-unread (car (pop known))))
3673     (cdr unread)))
3674
3675 (defun gnus-agent-uncached-articles (articles group &optional cached-header)
3676   "Restrict ARTICLES to numbers already fetched.
3677 Returns a sublist of ARTICLES that excludes those article ids in GROUP
3678 that have already been fetched.
3679 If CACHED-HEADER is nil, articles are only excluded if the article itself
3680 has been fetched."
3681
3682   ;; Logically equivalent to: (gnus-sorted-difference articles (mapcar
3683   ;; 'car gnus-agent-article-alist))
3684
3685   ;; Functionally, I don't need to construct a temp list using mapcar.
3686
3687   (if (and (or gnus-agent-cache (not gnus-plugged))
3688            (gnus-agent-load-alist group))
3689     (let* ((ref gnus-agent-article-alist)
3690            (arts articles)
3691            (uncached (list nil))
3692            (tail-uncached uncached))
3693       (while (and ref arts)
3694         (let ((v1 (car arts))
3695               (v2 (caar ref)))
3696           (cond ((< v1 v2) ; v1 does not appear in the reference list
3697                  (gnus-agent-append-to-list tail-uncached v1)
3698                  (setq arts (cdr arts)))
3699                 ((= v1 v2)
3700                  (unless (or cached-header (cdar ref)) ; v1 is already cached
3701                    (gnus-agent-append-to-list tail-uncached v1))
3702                  (setq arts (cdr arts))
3703                  (setq ref (cdr ref)))
3704                 (t ; reference article (v2) precedes the list being filtered
3705                  (setq ref (cdr ref))))))
3706       (while arts
3707         (gnus-agent-append-to-list tail-uncached (pop arts)))
3708       (cdr uncached))
3709     ;; if gnus-agent-load-alist fails, no articles are cached.
3710     articles))
3711
3712 (defun gnus-agent-retrieve-headers (articles group &optional fetch-old)
3713   (save-excursion
3714     (gnus-agent-create-buffer)
3715     (let ((gnus-decode-encoded-word-function 'identity)
3716           (gnus-decode-encoded-address-function 'identity)
3717           (file (gnus-agent-article-name ".overview" group))
3718           cached-articles uncached-articles
3719           (file-name-coding-system nnmail-pathname-coding-system))
3720       (gnus-make-directory (nnheader-translate-file-chars
3721                             (file-name-directory file) t))
3722
3723       (when fetch-old
3724         (setq articles (gnus-uncompress-range
3725                         (cons (if (numberp fetch-old)
3726                                   (max 1 (- (car articles) fetch-old))
3727                                 1)
3728                               (car (last articles))))))
3729
3730       ;; Populate temp buffer with known headers
3731       (when (file-exists-p file)
3732         (with-current-buffer gnus-agent-overview-buffer
3733           (erase-buffer)
3734           (let ((nnheader-file-coding-system
3735                  gnus-agent-file-coding-system))
3736             (nnheader-insert-nov-file file (car articles)))))
3737
3738       (if (setq uncached-articles (gnus-agent-uncached-articles articles group
3739                                                                 t))
3740           (progn
3741             ;; Populate nntp-server-buffer with uncached headers
3742             (set-buffer nntp-server-buffer)
3743             (erase-buffer)
3744             (cond ((not (eq 'nov (let (gnus-agent) ; Turn off agent
3745                                    (gnus-retrieve-headers
3746                                     uncached-articles group))))
3747                    (nnvirtual-convert-headers))
3748                   ((eq 'nntp (car gnus-current-select-method))
3749                    ;; The author of gnus-get-newsgroup-headers-xover
3750                    ;; reports that the XOVER command is commonly
3751                    ;; unreliable. The problem is that recently
3752                    ;; posted articles may not be entered into the
3753                    ;; NOV database in time to respond to my XOVER
3754                    ;; query.
3755                    ;;
3756                    ;; I'm going to use his assumption that the NOV
3757                    ;; database is updated in order of ascending
3758                    ;; article ID.  Therefore, a response containing
3759                    ;; article ID N implies that all articles from 1
3760                    ;; to N-1 are up-to-date.  Therefore, missing
3761                    ;; articles in that range have expired.
3762
3763                    (set-buffer nntp-server-buffer)
3764                    (let* ((fetched-articles (list nil))
3765                           (tail-fetched-articles fetched-articles)
3766                           (min (car articles))
3767                           (max (car (last articles))))
3768
3769                      ;; Get the list of articles that were fetched
3770                      (goto-char (point-min))
3771                      (let ((pm (point-max))
3772                            art)
3773                        (while (< (point) pm)
3774                          (when (setq art (gnus-agent-read-article-number))
3775                            (gnus-agent-append-to-list tail-fetched-articles art))
3776                          (forward-line 1)))
3777
3778                      ;; Clip this list to the headers that will
3779                      ;; actually be returned
3780                      (setq fetched-articles (gnus-list-range-intersection
3781                                              (cdr fetched-articles)
3782                                              (cons min max)))
3783
3784                      ;; Clip the uncached articles list to exclude
3785                      ;; IDs after the last FETCHED header.  The
3786                      ;; excluded IDs may be fetchable using HEAD.
3787                      (if (car tail-fetched-articles)
3788                          (setq uncached-articles
3789                                (gnus-list-range-intersection
3790                                 uncached-articles
3791                                 (cons (car uncached-articles)
3792                                       (car tail-fetched-articles)))))
3793
3794                      ;; Create the list of articles that were
3795                      ;; "successfully" fetched.  Success, in this
3796                      ;; case, means that the ID should not be
3797                      ;; fetched again.  In the case of an expired
3798                      ;; article, the header will not be fetched.
3799                      (setq uncached-articles
3800                            (gnus-sorted-nunion fetched-articles
3801                                                uncached-articles))
3802                      )))
3803
3804             ;; Erase the temp buffer
3805             (set-buffer gnus-agent-overview-buffer)
3806             (erase-buffer)
3807
3808             ;; Copy the nntp-server-buffer to the temp buffer
3809             (set-buffer nntp-server-buffer)
3810             (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
3811
3812             ;; Merge the temp buffer with the known headers (found on
3813             ;; disk in FILE) into the nntp-server-buffer
3814             (when uncached-articles
3815               (gnus-agent-braid-nov group uncached-articles file))
3816
3817             ;; Save the new set of known headers to FILE
3818             (set-buffer nntp-server-buffer)
3819             (let ((coding-system-for-write
3820                    gnus-agent-file-coding-system))
3821               (gnus-agent-check-overview-buffer)
3822               (write-region (point-min) (point-max) file nil 'silent))
3823
3824             (gnus-agent-update-view-total-fetched-for group t)
3825
3826             ;; Update the group's article alist to include the newly
3827             ;; fetched articles.
3828             (gnus-agent-load-alist group)
3829             (gnus-agent-save-alist group uncached-articles nil)
3830             )
3831
3832         ;; Copy the temp buffer to the nntp-server-buffer
3833         (set-buffer nntp-server-buffer)
3834         (erase-buffer)
3835         (insert-buffer-substring gnus-agent-overview-buffer)))
3836
3837     (if (and fetch-old
3838              (not (numberp fetch-old)))
3839         t                               ; Don't remove anything.
3840       (nnheader-nov-delete-outside-range
3841        (car articles)
3842        (car (last articles)))
3843       t)
3844
3845     'nov))
3846
3847 (defun gnus-agent-request-article (article group)
3848   "Retrieve ARTICLE in GROUP from the agent cache."
3849   (when (and gnus-agent
3850              (or gnus-agent-cache
3851                  (not gnus-plugged))
3852              (numberp article))
3853     (let* ((gnus-command-method (gnus-find-method-for-group group))
3854            (file (gnus-agent-article-name (number-to-string article) group))
3855            (buffer-read-only nil)
3856            (file-name-coding-system nnmail-pathname-coding-system))
3857       (when (and (file-exists-p file)
3858                  (> (nth 7 (file-attributes file)) 0))
3859         (erase-buffer)
3860         (gnus-kill-all-overlays)
3861         (let ((coding-system-for-read gnus-cache-coding-system))
3862           (insert-file-contents file))
3863         t))))
3864
3865 (defun gnus-agent-store-article (article group)
3866   (let* ((gnus-command-method (gnus-find-method-for-group group))
3867          (file (gnus-agent-article-name (number-to-string article) group))
3868          (file-name-coding-system nnmail-pathname-coding-system)
3869          (coding-system-for-write gnus-cache-coding-system))
3870     (when (not (file-exists-p file))
3871       (gnus-make-directory (file-name-directory file))
3872       (write-region (point-min) (point-max) file nil 'silent)
3873       ;; Tell the Agent when the article was fetched, so that it can
3874       ;; be expired later.
3875       (gnus-agent-load-alist group)
3876       (gnus-agent-save-alist group (list article)
3877                              (time-to-days (current-time))))))
3878
3879 (defun gnus-agent-regenerate-group (group &optional reread)
3880   "Regenerate GROUP.
3881 If REREAD is t, all articles in the .overview are marked as unread.
3882 If REREAD is a list, the specified articles will be marked as unread.
3883 In addition, their NOV entries in .overview will be refreshed using
3884 the articles' current headers.
3885 If REREAD is not nil, downloaded articles are marked as unread."
3886   (interactive
3887    (list (gnus-agent-read-group)
3888          (catch 'mark
3889            (while (let (c
3890                         (cursor-in-echo-area t)
3891                         (echo-keystrokes 0))
3892                     (message "Mark as unread: (n)one / (a)ll / all (d)ownloaded articles? (n) ")
3893                     (setq c (read-char-exclusive))
3894
3895                     (cond ((or (eq c ?\r) (eq c ?n) (eq c ?N))
3896                            (throw 'mark nil))
3897                           ((or (eq c ?a) (eq c ?A))
3898                            (throw 'mark t))
3899                           ((or (eq c ?d) (eq c ?D))
3900                            (throw 'mark 'some)))
3901                     (gnus-message 3 "Ignoring unexpected input")
3902                     (sit-for 1)
3903                     t)))))
3904   (when group
3905     (gnus-message 5 "Regenerating in %s" (gnus-agent-decoded-group-name group))
3906     (let* ((gnus-command-method (or gnus-command-method
3907                                     (gnus-find-method-for-group group)))
3908            (file (gnus-agent-article-name ".overview" group))
3909            (dir (file-name-directory file))
3910            point
3911            (file-name-coding-system nnmail-pathname-coding-system)
3912            (downloaded (if (file-exists-p dir)
3913                            (sort (delq nil (mapcar (lambda (name)
3914                                                      (and (not (file-directory-p (nnheader-concat dir name)))
3915                                                           (string-to-number name)))
3916                                                    (directory-files dir nil "^[0-9]+$" t)))
3917                                  '>)
3918                          (progn (gnus-make-directory dir) nil)))
3919            dl nov-arts
3920            alist header
3921            regenerated)
3922
3923       (mm-with-unibyte-buffer
3924         (if (file-exists-p file)
3925             (let ((nnheader-file-coding-system
3926                    gnus-agent-file-coding-system))
3927               (nnheader-insert-file-contents file)))
3928         (set-buffer-modified-p nil)
3929
3930         ;; Load the article IDs found in the overview file.  As a
3931         ;; side-effect, validate the file contents.
3932         (let ((load t))
3933           (while load
3934             (setq load nil)
3935             (goto-char (point-min))
3936             (while (< (point) (point-max))
3937               (cond ((and (looking-at "[0-9]+\t")
3938                           (<= (- (match-end 0) (match-beginning 0)) 9))
3939                      (push (read (current-buffer)) nov-arts)
3940                      (forward-line 1)
3941                      (let ((l1 (car nov-arts))
3942                            (l2 (cadr nov-arts)))
3943                        (cond ((and (listp reread) (memq l1 reread))
3944                               (gnus-delete-line)
3945                               (setq nov-arts (cdr nov-arts))
3946                               (gnus-message 4 "gnus-agent-regenerate-group: NOV\
3947  entry of article %s deleted." l1))
3948                              ((not l2)
3949                               nil)
3950                              ((< l1 l2)
3951                               (gnus-message 3 "gnus-agent-regenerate-group: NOV\
3952  entries are NOT in ascending order.")
3953                               ;; Don't sort now as I haven't verified
3954                               ;; that every line begins with a number
3955                               (setq load t))
3956                              ((= l1 l2)
3957                               (forward-line -1)
3958                               (gnus-message 4 "gnus-agent-regenerate-group: NOV\
3959  entries contained duplicate of article %s.      Duplicate deleted." l1)
3960                               (gnus-delete-line)
3961                               (setq nov-arts (cdr nov-arts))))))
3962                     (t
3963                      (gnus-message 1 "gnus-agent-regenerate-group: NOV\
3964  entries contained line that did not begin with an article number.  Deleted\
3965  line.")
3966                      (gnus-delete-line))))
3967             (when load
3968               (gnus-message 5 "gnus-agent-regenerate-group: Sorting NOV\
3969  entries into ascending order.")
3970               (sort-numeric-fields 1 (point-min) (point-max))
3971               (setq nov-arts nil))))
3972         (gnus-agent-check-overview-buffer)
3973
3974         ;; Construct a new article alist whose nodes match every header
3975         ;; in the .overview file.  As a side-effect, missing headers are
3976         ;; reconstructed from the downloaded article file.
3977         (while (or downloaded nov-arts)
3978           (cond ((and downloaded
3979                       (or (not nov-arts)
3980                           (> (car downloaded) (car nov-arts))))
3981                  ;; This entry is missing from the overview file
3982                  (gnus-message 3 "Regenerating NOV %s %d..."
3983                                (gnus-agent-decoded-group-name group)
3984                                (car downloaded))
3985                  (let ((file (concat dir (number-to-string (car downloaded)))))
3986                    (mm-with-unibyte-buffer
3987                      (nnheader-insert-file-contents file)
3988                      (nnheader-remove-body)
3989                      (setq header (nnheader-parse-naked-head)))
3990                    (mail-header-set-number header (car downloaded))
3991                    (if nov-arts
3992                        (let ((key (concat "^" (int-to-string (car nov-arts))
3993                                           "\t")))
3994                          (or (re-search-backward key nil t)
3995                              (re-search-forward key))
3996                          (forward-line 1))
3997                      (goto-char (point-min)))
3998                    (nnheader-insert-nov header))
3999                  (setq nov-arts (cons (car downloaded) nov-arts)))
4000                 ((eq (car downloaded) (car nov-arts))
4001                  ;; This entry in the overview has been downloaded
4002                  (push (cons (car downloaded)
4003                              (time-to-days
4004                               (nth 5 (file-attributes
4005                                       (concat dir (number-to-string
4006                                                    (car downloaded))))))) alist)
4007                  (setq downloaded (cdr downloaded))
4008                  (setq nov-arts (cdr nov-arts)))
4009                 (t
4010                  ;; This entry in the overview has not been downloaded
4011                  (push (cons (car nov-arts) nil) alist)
4012                  (setq nov-arts (cdr nov-arts)))))
4013
4014         ;; When gnus-agent-consider-all-articles is set,
4015         ;; gnus-agent-regenerate-group should NOT remove article IDs from
4016         ;; the alist.  Those IDs serve as markers to indicate that an
4017         ;; attempt has been made to fetch that article's header.
4018
4019         ;; When gnus-agent-consider-all-articles is NOT set,
4020         ;; gnus-agent-regenerate-group can remove the article ID of every
4021         ;; article (with the exception of the last ID in the list - it's
4022         ;; special) that no longer appears in the overview.  In this
4023         ;; situation, the last article ID in the list implies that it,
4024         ;; and every article ID preceding it, have been fetched from the
4025         ;; server.
4026
4027         (if gnus-agent-consider-all-articles
4028             ;; Restore all article IDs that were not found in the overview file.
4029             (let* ((n (cons nil alist))
4030                    (merged n)
4031                    (o (gnus-agent-load-alist group)))
4032               (while o
4033                 (let ((nID (caadr n))
4034                       (oID (caar o)))
4035                   (cond ((not nID)
4036                          (setq n (setcdr n (list (list oID))))
4037                          (setq o (cdr o)))
4038                         ((< oID nID)
4039                          (setcdr n (cons (list oID) (cdr n)))
4040                          (setq o (cdr o)))
4041                         ((= oID nID)
4042                          (setq o (cdr o))
4043                          (setq n (cdr n)))
4044                         (t
4045                          (setq n (cdr n))))))
4046               (setq alist (cdr merged)))
4047           ;; Restore the last article ID if it is not already in the new alist
4048           (let ((n (last alist))
4049                 (o (last (gnus-agent-load-alist group))))
4050             (cond ((not o)
4051                    nil)
4052                   ((not n)
4053                    (push (cons (caar o) nil) alist))
4054                   ((< (caar n) (caar o))
4055                    (setcdr n (list (car o)))))))
4056
4057         (let ((inhibit-quit t))
4058           (if (setq regenerated (buffer-modified-p))
4059               (let ((coding-system-for-write gnus-agent-file-coding-system))
4060                 (write-region (point-min) (point-max) file nil 'silent)))
4061
4062           (setq regenerated (or regenerated
4063                                 (and reread gnus-agent-article-alist)
4064                                 (not (equal alist gnus-agent-article-alist))))
4065
4066           (setq gnus-agent-article-alist alist)
4067
4068           (when regenerated
4069             (gnus-agent-save-alist group)
4070
4071             ;; I have to alter the group's active range NOW as
4072             ;; gnus-make-ascending-articles-unread will use it to
4073             ;; recalculate the number of unread articles in the group
4074
4075             (let ((group (gnus-group-real-name group))
4076                   (group-active (or (gnus-active group)
4077                                     (gnus-activate-group group))))
4078               (gnus-agent-possibly-alter-active group group-active)))))
4079
4080       (when (and reread gnus-agent-article-alist)
4081         (gnus-agent-synchronize-group-flags
4082          group
4083          (list (list
4084                 (if (listp reread)
4085                     reread
4086                   (delq nil (mapcar (function (lambda (c)
4087                                                 (cond ((eq reread t)
4088                                                        (car c))
4089                                                       ((cdr c)
4090                                                        (car c)))))
4091                                     gnus-agent-article-alist)))
4092                 'del '(read)))
4093          gnus-command-method)
4094
4095         (when regenerated
4096           (gnus-agent-update-files-total-fetched-for group nil)))
4097
4098       (gnus-message 5 "")
4099       regenerated)))
4100
4101 ;;;###autoload
4102 (defun gnus-agent-regenerate (&optional clean reread)
4103   "Regenerate all agent covered files.
4104 If CLEAN, obsolete (ignore)."
4105   (interactive "P")
4106   (let (regenerated)
4107     (gnus-message 4 "Regenerating Gnus agent files...")
4108     (dolist (gnus-command-method (gnus-agent-covered-methods))
4109         (dolist (group (gnus-groups-from-server gnus-command-method))
4110           (setq regenerated (or (gnus-agent-regenerate-group group reread)
4111                                 regenerated))))
4112     (gnus-message 4 "Regenerating Gnus agent files...done")
4113
4114     regenerated))
4115
4116 (defun gnus-agent-go-online (&optional force)
4117   "Switch servers into online status."
4118   (interactive (list t))
4119   (dolist (server gnus-opened-servers)
4120     (when (eq (nth 1 server) 'offline)
4121       (if (if (eq force 'ask)
4122               (gnus-y-or-n-p
4123                (format "Switch %s:%s into online status? "
4124                        (caar server) (cadar server)))
4125             force)
4126           (setcar (nthcdr 1 server) 'close)))))
4127
4128 (defun gnus-agent-toggle-group-plugged (group)
4129   "Toggle the status of the server of the current group."
4130   (interactive (list (gnus-group-group-name)))
4131   (let* ((method (gnus-find-method-for-group group))
4132          (status (cadr (assoc method gnus-opened-servers))))
4133     (if (eq status 'offline)
4134         (gnus-server-set-status method 'closed)
4135       (gnus-close-server method)
4136       (gnus-server-set-status method 'offline))
4137     (message "Turn %s:%s from %s to %s." (car method) (cadr method)
4138              (if (eq status 'offline) 'offline 'online)
4139              (if (eq status 'offline) 'online 'offline))))
4140
4141 (defun gnus-agent-group-covered-p (group)
4142   (gnus-agent-method-p (gnus-group-method group)))
4143
4144 (defun gnus-agent-update-files-total-fetched-for
4145   (group delta &optional method path)
4146   "Update, or set, the total disk space used by the articles that the
4147 agent has fetched."
4148   (when gnus-agent-total-fetched-hashtb
4149     (gnus-agent-with-refreshed-group
4150      group
4151      ;; if null, gnus-agent-group-pathname will calc method.
4152      (let* ((gnus-command-method method)
4153             (path (or path (gnus-agent-group-pathname group)))
4154             (entry (or (gnus-gethash path gnus-agent-total-fetched-hashtb)
4155                        (gnus-sethash path (make-list 3 0)
4156                                      gnus-agent-total-fetched-hashtb)))
4157             (file-name-coding-system nnmail-pathname-coding-system))
4158        (when (listp delta)
4159          (if delta
4160              (let ((sum 0.0)
4161                    file)
4162                (while (setq file (pop delta))
4163                  (incf sum (float (or (nth 7 (file-attributes
4164                                               (nnheader-concat
4165                                                path
4166                                                (if (numberp file)
4167                                                    (number-to-string file)
4168                                                  file)))) 0))))
4169                (setq delta sum))
4170            (let ((sum (- (nth 2 entry)))
4171                  (info (directory-files-and-attributes path nil "^-?[0-9]+$" t))
4172                  file)
4173              (while (setq file (pop info))
4174                (incf sum (float (or (nth 8 file) 0))))
4175              (setq delta sum))))
4176
4177        (setq gnus-agent-need-update-total-fetched-for t)
4178        (incf (nth 2 entry) delta)))))
4179
4180 (defun gnus-agent-update-view-total-fetched-for
4181   (group agent-over &optional method path)
4182   "Update, or set, the total disk space used by the .agentview and
4183 .overview files.  These files are calculated separately as they can be
4184 modified."
4185   (when gnus-agent-total-fetched-hashtb
4186     (gnus-agent-with-refreshed-group
4187      group
4188      ;; if null, gnus-agent-group-pathname will calc method.
4189      (let* ((gnus-command-method method)
4190             (path (or path (gnus-agent-group-pathname group)))
4191             (entry (or (gnus-gethash path gnus-agent-total-fetched-hashtb)
4192                        (gnus-sethash path (make-list 3 0)
4193                                      gnus-agent-total-fetched-hashtb)))
4194             (file-name-coding-system nnmail-pathname-coding-system)
4195             (size (or (nth 7 (file-attributes
4196                               (nnheader-concat
4197                                path (if agent-over
4198                                         ".overview"
4199                                       ".agentview"))))
4200                       0)))
4201        (setq gnus-agent-need-update-total-fetched-for t)
4202        (setf (nth (if agent-over 1 0) entry) size)))))
4203
4204 (defun gnus-agent-total-fetched-for (group &optional method no-inhibit)
4205   "Get the total disk space used by the specified GROUP."
4206   (unless (equal group "dummy.group")
4207     (unless gnus-agent-total-fetched-hashtb
4208       (setq gnus-agent-total-fetched-hashtb (gnus-make-hashtable 1024)))
4209
4210     ;; if null, gnus-agent-group-pathname will calc method.
4211     (let* ((gnus-command-method method)
4212            (path (gnus-agent-group-pathname group))
4213            (entry (gnus-gethash path gnus-agent-total-fetched-hashtb)))
4214       (if entry
4215           (apply '+ entry)
4216         (let ((gnus-agent-inhibit-update-total-fetched-for (not no-inhibit)))
4217           (+
4218            (gnus-agent-update-view-total-fetched-for  group nil method path)
4219            (gnus-agent-update-view-total-fetched-for  group t   method path)
4220            (gnus-agent-update-files-total-fetched-for group nil method path)))))))
4221
4222 (provide 'gnus-agent)
4223
4224 ;;; gnus-agent.el ends here