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