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