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