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