Add arch taglines
[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 nil
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 (inline
1861                                    (gnus-uncompress-range
1862                                     (cdr comp-list)))))
1863                    (mapcar (lambda (article-id)
1864                              (setq uncomp (cons (cons article-id state) uncomp)))
1865                            sequence)))
1866                alist)
1867               (setq alist (sort uncomp 'car-less-than-car)))))
1868           (when changed-version
1869             (let ((gnus-agent-article-alist alist))
1870               (gnus-agent-save-alist gnus-agent-read-agentview)))
1871           alist))
1872       (file-error nil))))
1873
1874 (defun gnus-agent-save-alist (group &optional articles state)
1875   "Save the article-state alist for GROUP."
1876   (let* ((file-name-coding-system nnmail-pathname-coding-system)
1877          (prev (cons nil gnus-agent-article-alist))
1878          (all prev)
1879          print-level print-length item article)
1880     (while (setq article (pop articles))
1881       (while (and (cdr prev)
1882                   (< (caadr prev) article))
1883         (setq prev (cdr prev)))
1884       (cond
1885        ((not (cdr prev))
1886         (setcdr prev (list (cons article state))))
1887        ((> (caadr prev) article)
1888         (setcdr prev (cons (cons article state) (cdr prev))))
1889        ((= (caadr prev) article)
1890         (setcdr (cadr prev) state)))
1891       (setq prev (cdr prev)))
1892     (setq gnus-agent-article-alist (cdr all))
1893
1894     (gnus-agent-set-local group 
1895                           (caar gnus-agent-article-alist) 
1896                           (caar (last gnus-agent-article-alist)))
1897
1898     (gnus-make-directory (gnus-agent-article-name "" group))
1899     (with-temp-file (gnus-agent-article-name ".agentview" group)
1900       (cond ((eq gnus-agent-article-alist-save-format 1)
1901              (princ gnus-agent-article-alist (current-buffer)))
1902             ((eq gnus-agent-article-alist-save-format 2)
1903              (let ((compressed nil))
1904                (mapcar (lambda (pair)
1905                          (let* ((article-id (car pair))
1906                                 (day-of-download (cdr pair))
1907                                 (comp-list (assq day-of-download compressed)))
1908                            (if comp-list
1909                                (setcdr comp-list
1910                                        (cons article-id (cdr comp-list)))
1911                              (setq compressed
1912                                    (cons (list day-of-download article-id)
1913                                          compressed)))
1914                            nil)) gnus-agent-article-alist)
1915                (mapcar (lambda (comp-list)
1916                          (setcdr comp-list
1917                                  (gnus-compress-sequence
1918                                   (nreverse (cdr comp-list)))))
1919                        compressed)
1920                (princ compressed (current-buffer)))))
1921       (insert "\n")
1922       (princ gnus-agent-article-alist-save-format (current-buffer))
1923       (insert "\n"))
1924
1925     (gnus-agent-update-view-total-fetched-for group nil)))
1926
1927 (defvar gnus-agent-article-local nil)
1928 (defvar gnus-agent-file-loading-local nil)
1929
1930 (defun gnus-agent-load-local (&optional method)
1931   "Load the METHOD'S local file.  The local file contains min/max
1932 article counts for each of the method's subscribed groups."
1933   (let ((gnus-command-method (or method gnus-command-method)))
1934     (setq gnus-agent-article-local
1935           (gnus-cache-file-contents
1936            (gnus-agent-lib-file "local")
1937            'gnus-agent-file-loading-local
1938            'gnus-agent-read-and-cache-local))))
1939
1940 (defun gnus-agent-read-and-cache-local (file)
1941   "Load and read FILE then bind its contents to
1942 gnus-agent-article-local.  If that variable had `dirty' (also known as
1943 modified) original contents, they are first saved to their own file."
1944
1945   (if (and gnus-agent-article-local
1946            (symbol-value (intern "+dirty" gnus-agent-article-local)))
1947       (gnus-agent-save-local))
1948   (gnus-agent-read-local file))
1949
1950 (defun gnus-agent-read-local (file)
1951   "Load FILE and do a `read' there."
1952   (let ((my-obarray (gnus-make-hashtable (count-lines (point-min) 
1953                                                       (point-max))))
1954         (line 1))
1955     (with-temp-buffer
1956       (condition-case nil
1957           (let ((nnheader-file-coding-system gnus-agent-file-coding-system))
1958             (nnheader-insert-file-contents file))
1959         (file-error))
1960
1961       (goto-char (point-min))
1962       ;; Skip any comments at the beginning of the file (the only place where they may appear)
1963       (while (= (following-char) ?\;)
1964         (forward-line 1)
1965         (setq line (1+ line)))
1966
1967       (while (not (eobp))
1968         (condition-case err
1969             (let (group 
1970                   min
1971                   max
1972                   (cur (current-buffer)))
1973               (setq group (read cur)
1974                     min (read cur)
1975                     max (read cur))
1976
1977               (when (stringp group)
1978                 (setq group (intern group my-obarray)))
1979
1980               ;; NOTE: The '+ 0' ensure that min and max are both numerics.
1981               (set group (cons (+ 0 min) (+ 0 max))))
1982           (error
1983            (gnus-message 3 "Warning - invalid agent local: %s on line %d: "
1984                          file line (error-message-string err))))
1985         (forward-line 1)
1986         (setq line (1+ line))))
1987       
1988     (set (intern "+dirty" my-obarray) nil)
1989     (set (intern "+method" my-obarray) gnus-command-method)
1990     my-obarray))
1991
1992 (defun gnus-agent-save-local (&optional force)
1993   "Save gnus-agent-article-local under it method's agent.lib directory."
1994   (let ((my-obarray gnus-agent-article-local))
1995     (when (and my-obarray
1996                (or force (symbol-value (intern "+dirty" my-obarray))))
1997       (let* ((gnus-command-method (symbol-value (intern "+method" my-obarray)))
1998              ;; NOTE: gnus-command-method is used within gnus-agent-lib-file.
1999              (dest (gnus-agent-lib-file "local")))
2000         (gnus-make-directory (gnus-agent-lib-file ""))
2001
2002         (let ((buffer-file-coding-system gnus-agent-file-coding-system))
2003           (with-temp-file dest
2004             (let ((gnus-command-method (symbol-value (intern "+method" my-obarray)))
2005                   (file-name-coding-system nnmail-pathname-coding-system)
2006                   print-level print-length item article
2007                   (standard-output (current-buffer)))
2008               (mapatoms (lambda (symbol)
2009                           (cond ((not (boundp symbol))
2010                                  nil)
2011                                 ((member (symbol-name symbol) '("+dirty" "+method"))
2012                                  nil)
2013                                 (t
2014                                  (prin1 symbol)
2015                                  (let ((range (symbol-value symbol)))
2016                                    (princ " ")
2017                                    (princ (car range))
2018                                    (princ " ")
2019                                    (princ (cdr range))
2020                                    (princ "\n"))))) 
2021                         my-obarray))))))))
2022
2023 (defun gnus-agent-get-local (group &optional gmane method)
2024   (let* ((gmane (or gmane (gnus-group-real-name group)))
2025          (gnus-command-method (or method (gnus-find-method-for-group group)))
2026          (local (gnus-agent-load-local))
2027          (symb (intern gmane local))
2028          (minmax (and (boundp symb) (symbol-value symb))))
2029     (unless minmax
2030       ;; Bind these so that gnus-agent-load-alist doesn't change the
2031       ;; current alist (i.e. gnus-agent-article-alist)
2032       (let* ((gnus-agent-article-alist gnus-agent-article-alist)
2033              (gnus-agent-file-loading-cache gnus-agent-file-loading-cache)
2034              (alist (gnus-agent-load-alist group)))
2035         (when alist
2036           (setq minmax
2037                 (cons (caar alist)
2038                       (caar (last alist))))
2039           (gnus-agent-set-local group (car minmax) (cdr minmax) 
2040                                 gmane gnus-command-method local))))
2041     minmax))
2042
2043 (defun gnus-agent-set-local (group min max &optional gmane method local)
2044   (let* ((gmane (or gmane (gnus-group-real-name group)))
2045          (gnus-command-method (or method (gnus-find-method-for-group group)))
2046          (local (or local (gnus-agent-load-local)))
2047          (symb (intern gmane local))
2048          (minmax (and (boundp symb) (symbol-value symb))))
2049     
2050     (if (cond ((and minmax
2051                     (or (not (eq min (car minmax)))
2052                         (not (eq max (cdr minmax)))))
2053                (setcar minmax min)
2054                (setcdr minmax max)
2055                t)
2056               (minmax
2057                nil)
2058               ((and min max)
2059                (set symb (cons min max))
2060                t)
2061               (t
2062                (unintern symb local)))
2063         (set (intern "+dirty" local) t))))
2064
2065 (defun gnus-agent-article-name (article group)
2066   (expand-file-name article
2067                     (file-name-as-directory
2068                      (gnus-agent-group-pathname group))))
2069
2070 (defun gnus-agent-batch-confirmation (msg)
2071   "Show error message and return t."
2072   (gnus-message 1 msg)
2073   t)
2074
2075 ;;;###autoload
2076 (defun gnus-agent-batch-fetch ()
2077   "Start Gnus and fetch session."
2078   (interactive)
2079   (gnus)
2080   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
2081     (gnus-agent-fetch-session))
2082   (gnus-group-exit))
2083
2084 (defun gnus-agent-fetch-session ()
2085   "Fetch all articles and headers that are eligible for fetching."
2086   (interactive)
2087   (unless gnus-agent-covered-methods
2088     (error "No servers are covered by the Gnus agent"))
2089   (unless gnus-plugged
2090     (error "Can't fetch articles while Gnus is unplugged"))
2091   (let ((methods (gnus-agent-covered-methods))
2092         groups group gnus-command-method)
2093     (save-excursion
2094       (while methods
2095         (setq gnus-command-method (car methods))
2096         (when (and (or (gnus-server-opened gnus-command-method)
2097                        (gnus-open-server gnus-command-method))
2098                    (gnus-online gnus-command-method))
2099           (setq groups (gnus-groups-from-server (car methods)))
2100           (gnus-agent-with-fetch
2101             (while (setq group (pop groups))
2102               (when (<= (gnus-group-level group)
2103                         gnus-agent-handle-level)
2104                 (if (or debug-on-error debug-on-quit)
2105                     (gnus-agent-fetch-group-1
2106                      group gnus-command-method)
2107                   (condition-case err
2108                       (gnus-agent-fetch-group-1
2109                        group gnus-command-method)
2110                     (error
2111                      (unless (funcall gnus-agent-confirmation-function
2112                                       (format "Error %s while fetching session.  Should gnus continue? "
2113                                               (error-message-string err)))
2114                        (error "Cannot fetch articles into the Gnus agent")))
2115                     (quit
2116                      (gnus-agent-regenerate-group group)
2117                      (unless (funcall gnus-agent-confirmation-function
2118                                       (format
2119                                        "%s while fetching session.  Should gnus continue? "
2120                                        (error-message-string err)))
2121                        (signal 'quit
2122                                "Cannot fetch articles into the Gnus agent")))))))))
2123         (setq methods (cdr methods)))
2124       (gnus-run-hooks 'gnus-agent-fetched-hook)
2125       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
2126
2127 (defun gnus-agent-fetch-group-1 (group method)
2128   "Fetch GROUP."
2129   (let ((gnus-command-method method)
2130         (gnus-newsgroup-name group)
2131         (gnus-newsgroup-dependencies gnus-newsgroup-dependencies)
2132         (gnus-newsgroup-headers gnus-newsgroup-headers)
2133         (gnus-newsgroup-scored gnus-newsgroup-scored)
2134         (gnus-use-cache gnus-use-cache)
2135         (gnus-summary-expunge-below gnus-summary-expunge-below)
2136         (gnus-summary-mark-below gnus-summary-mark-below)
2137         (gnus-orphan-score gnus-orphan-score)
2138         ;; Maybe some other gnus-summary local variables should also
2139         ;; be put here.
2140
2141         gnus-headers
2142         gnus-score
2143         articles arts
2144         category predicate info marks score-param
2145         )
2146     (unless (gnus-check-group group)
2147       (error "Can't open server for %s" group))
2148
2149     ;; Fetch headers.
2150     (when (or gnus-newsgroup-active
2151               (gnus-active group)
2152               (gnus-activate-group group))
2153       (let ((marked-articles gnus-newsgroup-downloadable))
2154         ;; Identify the articles marked for download
2155         (unless gnus-newsgroup-active
2156           ;; The variable gnus-newsgroup-active was selected as I need
2157           ;; a gnus-summary local variable that is NOT bound to any
2158           ;; value (its global value should default to nil).
2159           (dolist (mark gnus-agent-download-marks)
2160             (let ((arts (cdr (assq mark (gnus-info-marks
2161                                          (setq info (gnus-get-info group)))))))
2162               (when arts
2163                 (setq marked-articles (nconc (gnus-uncompress-range arts)
2164                                              marked-articles))
2165                 ))))
2166         (setq marked-articles (sort marked-articles '<))
2167
2168         ;; Fetch any new articles from the server
2169         (setq articles (gnus-agent-fetch-headers group))
2170
2171         ;; Merge new articles with marked
2172         (setq articles (sort (append marked-articles articles) '<))
2173
2174         (when articles
2175           ;; Parse them and see which articles we want to fetch.
2176           (setq gnus-newsgroup-dependencies
2177                 (or gnus-newsgroup-dependencies
2178                     (make-vector (length articles) 0)))
2179           (setq gnus-newsgroup-headers
2180                 (or gnus-newsgroup-headers
2181                     (gnus-get-newsgroup-headers-xover articles nil nil
2182                                                       group)))
2183           ;; `gnus-agent-overview-buffer' may be killed for
2184           ;; timeout reason.  If so, recreate it.
2185           (gnus-agent-create-buffer)
2186
2187           ;; Figure out how to select articles in this group
2188           (setq category (gnus-group-category group))
2189
2190           (setq predicate
2191                 (gnus-get-predicate
2192                  (gnus-agent-find-parameter group 'agent-predicate)))
2193
2194           ;; If the selection predicate requires scoring, score each header
2195           (unless (memq predicate '(gnus-agent-true gnus-agent-false))
2196             (let ((score-param
2197                    (gnus-agent-find-parameter group 'agent-score-file)))
2198               ;; Translate score-param into real one
2199               (cond
2200                ((not score-param))
2201                ((eq score-param 'file)
2202                 (setq score-param (gnus-all-score-files group)))
2203                ((stringp (car score-param)))
2204                (t
2205                 (setq score-param (list (list score-param)))))
2206               (when score-param
2207                 (gnus-score-headers score-param))))
2208
2209           (unless (and (eq predicate 'gnus-agent-false)
2210                        (not marked-articles))
2211             (let ((arts (list nil)))
2212               (let ((arts-tail arts)
2213                     (alist (gnus-agent-load-alist group))
2214                     (marked-articles marked-articles)
2215                     (gnus-newsgroup-headers gnus-newsgroup-headers))
2216                 (while (setq gnus-headers (pop gnus-newsgroup-headers))
2217                   (let ((num (mail-header-number gnus-headers)))
2218                     ;; Determine if this article is already in the cache
2219                     (while (and alist
2220                                 (> num (caar alist)))
2221                       (setq alist (cdr alist)))
2222
2223                     (unless (and (eq num (caar alist))
2224                                  (cdar alist))
2225
2226                       ;; Determine if this article was marked for download.
2227                       (while (and marked-articles
2228                                   (> num (car marked-articles)))
2229                         (setq marked-articles
2230                               (cdr marked-articles)))
2231
2232                       ;; When this article is marked, or selected by the
2233                       ;; predicate, add it to the download list
2234                       (when (or (eq num (car marked-articles))
2235                                 (let ((gnus-score
2236                                        (or (cdr
2237                                             (assq num gnus-newsgroup-scored))
2238                                            gnus-summary-default-score))
2239                                       (gnus-agent-long-article
2240                                        (gnus-agent-find-parameter
2241                                         group 'agent-long-article))
2242                                       (gnus-agent-short-article
2243                                        (gnus-agent-find-parameter
2244                                         group 'agent-short-article))
2245                                       (gnus-agent-low-score
2246                                        (gnus-agent-find-parameter
2247                                         group 'agent-low-score))
2248                                       (gnus-agent-high-score
2249                                        (gnus-agent-find-parameter
2250                                         group 'agent-high-score))
2251                                       (gnus-agent-expire-days
2252                                        (gnus-agent-find-parameter
2253                                         group 'agent-days-until-old)))
2254                                   (funcall predicate)))
2255                         (gnus-agent-append-to-list arts-tail num))))))
2256
2257               (let (fetched-articles)
2258                 ;; Fetch all selected articles
2259                 (setq gnus-newsgroup-undownloaded
2260                       (gnus-sorted-ndifference
2261                        gnus-newsgroup-undownloaded
2262                        (setq fetched-articles
2263                              (if (cdr arts)
2264                                  (gnus-agent-fetch-articles group (cdr arts))
2265                                nil))))
2266
2267                 (let ((unfetched-articles
2268                        (gnus-sorted-ndifference (cdr arts) fetched-articles)))
2269                   (if gnus-newsgroup-active
2270                       ;; Update the summary buffer
2271                       (progn
2272                         (dolist (article marked-articles)
2273                           (gnus-summary-set-agent-mark article t))
2274                         (dolist (article fetched-articles)
2275                           (if gnus-agent-mark-unread-after-downloaded
2276                               (gnus-summary-mark-article
2277                                article gnus-unread-mark))
2278                           (when (gnus-summary-goto-subject article nil t)
2279                             (gnus-summary-update-download-mark article)))
2280                         (dolist (article unfetched-articles)
2281                           (gnus-summary-mark-article
2282                            article gnus-canceled-mark)))
2283
2284                     ;; Update the group buffer.
2285
2286                     ;; When some, or all, of the marked articles came
2287                     ;; from the download mark.  Remove that mark.  I
2288                     ;; didn't do this earlier as I only want to remove
2289                     ;; the marks after the fetch is completed.
2290
2291                     (dolist (mark gnus-agent-download-marks)
2292                       (when (eq mark 'download)
2293                         (let ((marked-arts
2294                                (assq mark (gnus-info-marks
2295                                            (setq info (gnus-get-info group))))))
2296                           (when (cdr marked-arts)
2297                             (setq marks
2298                                   (delq marked-arts (gnus-info-marks info)))
2299                             (gnus-info-set-marks info marks)))))
2300                     (let ((read (gnus-info-read
2301                                  (or info (setq info (gnus-get-info group))))))
2302                       (gnus-info-set-read
2303                        info (gnus-add-to-range read unfetched-articles)))
2304
2305                     (gnus-group-update-group group t)
2306                     (sit-for 0)
2307
2308                     (gnus-dribble-enter
2309                      (concat "(gnus-group-set-info '"
2310                              (gnus-prin1-to-string info)
2311                              ")"))))))))))))
2312
2313 ;;;
2314 ;;; Agent Category Mode
2315 ;;;
2316
2317 (defvar gnus-category-mode-hook nil
2318   "Hook run in `gnus-category-mode' buffers.")
2319
2320 (defvar gnus-category-line-format "     %(%20c%): %g\n"
2321   "Format of category lines.
2322
2323 Valid specifiers include:
2324 %c  Topic name (string)
2325 %g  The number of groups in the topic (integer)
2326
2327 General format specifiers can also be used.  See Info node
2328 `(gnus)Formatting Variables'.")
2329
2330 (defvar gnus-category-mode-line-format "Gnus: %%b"
2331   "The format specification for the category mode line.")
2332
2333 (defvar gnus-agent-predicate 'false
2334   "The selection predicate used when no other source is available.")
2335
2336 (defvar gnus-agent-short-article 100
2337   "Articles that have fewer lines than this are short.")
2338
2339 (defvar gnus-agent-long-article 200
2340   "Articles that have more lines than this are long.")
2341
2342 (defvar gnus-agent-low-score 0
2343   "Articles that have a score lower than this have a low score.")
2344
2345 (defvar gnus-agent-high-score 0
2346   "Articles that have a score higher than this have a high score.")
2347
2348
2349 ;;; Internal variables.
2350
2351 (defvar gnus-category-buffer "*Agent Category*")
2352
2353 (defvar gnus-category-line-format-alist
2354   `((?c gnus-tmp-name ?s)
2355     (?g gnus-tmp-groups ?d)))
2356
2357 (defvar gnus-category-mode-line-format-alist
2358   `((?u user-defined ?s)))
2359
2360 (defvar gnus-category-line-format-spec nil)
2361 (defvar gnus-category-mode-line-format-spec nil)
2362
2363 (defvar gnus-category-mode-map nil)
2364 (put 'gnus-category-mode 'mode-class 'special)
2365
2366 (unless gnus-category-mode-map
2367   (setq gnus-category-mode-map (make-sparse-keymap))
2368   (suppress-keymap gnus-category-mode-map)
2369
2370   (gnus-define-keys gnus-category-mode-map
2371     "q" gnus-category-exit
2372     "k" gnus-category-kill
2373     "c" gnus-category-copy
2374     "a" gnus-category-add
2375     "e" gnus-agent-customize-category
2376     "p" gnus-category-edit-predicate
2377     "g" gnus-category-edit-groups
2378     "s" gnus-category-edit-score
2379     "l" gnus-category-list
2380
2381     "\C-c\C-i" gnus-info-find-node
2382     "\C-c\C-b" gnus-bug))
2383
2384 (defvar gnus-category-menu-hook nil
2385   "*Hook run after the creation of the menu.")
2386
2387 (defun gnus-category-make-menu-bar ()
2388   (gnus-turn-off-edit-menu 'category)
2389   (unless (boundp 'gnus-category-menu)
2390     (easy-menu-define
2391      gnus-category-menu gnus-category-mode-map ""
2392      '("Categories"
2393        ["Add" gnus-category-add t]
2394        ["Kill" gnus-category-kill t]
2395        ["Copy" gnus-category-copy t]
2396        ["Edit category" gnus-agent-customize-category t]
2397        ["Edit predicate" gnus-category-edit-predicate t]
2398        ["Edit score" gnus-category-edit-score t]
2399        ["Edit groups" gnus-category-edit-groups t]
2400        ["Exit" gnus-category-exit t]))
2401
2402     (gnus-run-hooks 'gnus-category-menu-hook)))
2403
2404 (defun gnus-category-mode ()
2405   "Major mode for listing and editing agent categories.
2406
2407 All normal editing commands are switched off.
2408 \\<gnus-category-mode-map>
2409 For more in-depth information on this mode, read the manual
2410 \(`\\[gnus-info-find-node]').
2411
2412 The following commands are available:
2413
2414 \\{gnus-category-mode-map}"
2415   (interactive)
2416   (when (gnus-visual-p 'category-menu 'menu)
2417     (gnus-category-make-menu-bar))
2418   (kill-all-local-variables)
2419   (gnus-simplify-mode-line)
2420   (setq major-mode 'gnus-category-mode)
2421   (setq mode-name "Category")
2422   (gnus-set-default-directory)
2423   (setq mode-line-process nil)
2424   (use-local-map gnus-category-mode-map)
2425   (buffer-disable-undo)
2426   (setq truncate-lines t)
2427   (setq buffer-read-only t)
2428   (gnus-run-hooks 'gnus-category-mode-hook))
2429
2430 (defalias 'gnus-category-position-point 'gnus-goto-colon)
2431
2432 (defun gnus-category-insert-line (category)
2433   (let* ((gnus-tmp-name (format "%s" (car category)))
2434          (gnus-tmp-groups (length (gnus-agent-cat-groups category))))
2435     (beginning-of-line)
2436     (gnus-add-text-properties
2437      (point)
2438      (prog1 (1+ (point))
2439        ;; Insert the text.
2440        (eval gnus-category-line-format-spec))
2441      (list 'gnus-category gnus-tmp-name))))
2442
2443 (defun gnus-enter-category-buffer ()
2444   "Go to the Category buffer."
2445   (interactive)
2446   (gnus-category-setup-buffer)
2447   (gnus-configure-windows 'category)
2448   (gnus-category-prepare))
2449
2450 (defun gnus-category-setup-buffer ()
2451   (unless (get-buffer gnus-category-buffer)
2452     (save-excursion
2453       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
2454       (gnus-category-mode))))
2455
2456 (defun gnus-category-prepare ()
2457   (gnus-set-format 'category-mode)
2458   (gnus-set-format 'category t)
2459   (let ((alist gnus-category-alist)
2460         (buffer-read-only nil))
2461     (erase-buffer)
2462     (while alist
2463       (gnus-category-insert-line (pop alist)))
2464     (goto-char (point-min))
2465     (gnus-category-position-point)))
2466
2467 (defun gnus-category-name ()
2468   (or (intern (get-text-property (point-at-bol) 'gnus-category))
2469       (error "No category on the current line")))
2470
2471 (defun gnus-category-read ()
2472   "Read the category alist."
2473   (setq gnus-category-alist
2474         (or
2475          (with-temp-buffer
2476            (ignore-errors
2477             (nnheader-insert-file-contents (nnheader-concat gnus-agent-directory "lib/categories"))
2478             (goto-char (point-min))
2479             ;; This code isn't temp, it will be needed so long as
2480             ;; anyone may be migrating from an older version.
2481
2482             ;; Once we're certain that people will not revert to an
2483             ;; earlier version, we can take out the old-list code in
2484             ;; gnus-category-write.
2485             (let* ((old-list (read (current-buffer)))
2486                    (new-list (ignore-errors (read (current-buffer)))))
2487               (if new-list
2488                   new-list
2489                 ;; Convert from a positional list to an alist.
2490                 (mapcar
2491                  (lambda (c)
2492                    (setcdr c
2493                            (delq nil
2494                                  (gnus-mapcar
2495                                   (lambda (valu symb)
2496                                     (if valu
2497                                         (cons symb valu)))
2498                                   (cdr c)
2499                                   '(agent-predicate agent-score-file agent-groups))))
2500                    c)
2501                  old-list)))))
2502          (list (gnus-agent-cat-make 'default 'short)))))
2503
2504 (defun gnus-category-write ()
2505   "Write the category alist."
2506   (setq gnus-category-predicate-cache nil
2507         gnus-category-group-cache nil)
2508   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
2509   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
2510     ;; This prin1 is temporary.  It exists so that people can revert
2511     ;; to an earlier version of gnus-agent.
2512     (prin1 (mapcar (lambda (c)
2513               (list (car c)
2514                     (cdr (assoc 'agent-predicate c))
2515                     (cdr (assoc 'agent-score-file c))
2516                     (cdr (assoc 'agent-groups c))))
2517                    gnus-category-alist)
2518            (current-buffer))
2519     (newline)
2520     (prin1 gnus-category-alist (current-buffer))))
2521
2522 (defun gnus-category-edit-predicate (category)
2523   "Edit the predicate for CATEGORY."
2524   (interactive (list (gnus-category-name)))
2525   (let ((info (assq category gnus-category-alist)))
2526     (gnus-edit-form
2527      (gnus-agent-cat-predicate info)
2528      (format "Editing the select predicate for category %s" category)
2529      `(lambda (predicate)
2530         ;; Avoid run-time execution of setf form
2531         ;; (setf (gnus-agent-cat-predicate (assq ',category gnus-category-alist))
2532         ;;       predicate)
2533         ;; use its expansion instead:
2534         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2535                                      'agent-predicate predicate)
2536
2537         (gnus-category-write)
2538         (gnus-category-list)))))
2539
2540 (defun gnus-category-edit-score (category)
2541   "Edit the score expression for CATEGORY."
2542   (interactive (list (gnus-category-name)))
2543   (let ((info (assq category gnus-category-alist)))
2544     (gnus-edit-form
2545      (gnus-agent-cat-score-file info)
2546      (format "Editing the score expression for category %s" category)
2547      `(lambda (score-file)
2548         ;; Avoid run-time execution of setf form
2549         ;; (setf (gnus-agent-cat-score-file (assq ',category gnus-category-alist))
2550         ;;       score-file)
2551         ;; use its expansion instead:
2552         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2553                                      'agent-score-file score-file)
2554
2555         (gnus-category-write)
2556         (gnus-category-list)))))
2557
2558 (defun gnus-category-edit-groups (category)
2559   "Edit the group list for CATEGORY."
2560   (interactive (list (gnus-category-name)))
2561   (let ((info (assq category gnus-category-alist)))
2562     (gnus-edit-form
2563      (gnus-agent-cat-groups info)
2564      (format "Editing the group list for category %s" category)
2565      `(lambda (groups)
2566         ;; Avoid run-time execution of setf form
2567         ;; (setf (gnus-agent-cat-groups (assq ',category gnus-category-alist))
2568         ;;       groups)
2569         ;; use its expansion instead:
2570         (gnus-agent-set-cat-groups (assq ',category gnus-category-alist)
2571                                    groups)
2572
2573         (gnus-category-write)
2574         (gnus-category-list)))))
2575
2576 (defun gnus-category-kill (category)
2577   "Kill the current category."
2578   (interactive (list (gnus-category-name)))
2579   (let ((info (assq category gnus-category-alist))
2580         (buffer-read-only nil))
2581     (gnus-delete-line)
2582     (setq gnus-category-alist (delq info gnus-category-alist))
2583     (gnus-category-write)))
2584
2585 (defun gnus-category-copy (category to)
2586   "Copy the current category."
2587   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
2588   (let ((info (assq category gnus-category-alist)))
2589     (push (let ((newcat (gnus-copy-sequence info)))
2590             (setf (gnus-agent-cat-name newcat) to)
2591             (setf (gnus-agent-cat-groups newcat) nil)
2592             newcat)
2593           gnus-category-alist)
2594     (gnus-category-write)
2595     (gnus-category-list)))
2596
2597 (defun gnus-category-add (category)
2598   "Create a new category."
2599   (interactive "SCategory name: ")
2600   (when (assq category gnus-category-alist)
2601     (error "Category %s already exists" category))
2602   (push (gnus-agent-cat-make category)
2603         gnus-category-alist)
2604   (gnus-category-write)
2605   (gnus-category-list))
2606
2607 (defun gnus-category-list ()
2608   "List all categories."
2609   (interactive)
2610   (gnus-category-prepare))
2611
2612 (defun gnus-category-exit ()
2613   "Return to the group buffer."
2614   (interactive)
2615   (kill-buffer (current-buffer))
2616   (gnus-configure-windows 'group t))
2617
2618 ;; To avoid having 8-bit characters in the source file.
2619 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
2620
2621 (defvar gnus-category-predicate-alist
2622   '((spam . gnus-agent-spam-p)
2623     (short . gnus-agent-short-p)
2624     (long . gnus-agent-long-p)
2625     (low . gnus-agent-low-scored-p)
2626     (high . gnus-agent-high-scored-p)
2627     (read . gnus-agent-read-p)
2628     (true . gnus-agent-true)
2629     (false . gnus-agent-false))
2630   "Mapping from short score predicate symbols to predicate functions.")
2631
2632 (defun gnus-agent-spam-p ()
2633   "Say whether an article is spam or not."
2634   (unless gnus-agent-spam-hashtb
2635     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
2636   (if (not (equal (mail-header-references gnus-headers) ""))
2637       nil
2638     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
2639       (prog1
2640           (gnus-gethash string gnus-agent-spam-hashtb)
2641         (gnus-sethash string t gnus-agent-spam-hashtb)))))
2642
2643 (defun gnus-agent-short-p ()
2644   "Say whether an article is short or not."
2645   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
2646
2647 (defun gnus-agent-long-p ()
2648   "Say whether an article is long or not."
2649   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
2650
2651 (defun gnus-agent-low-scored-p ()
2652   "Say whether an article has a low score or not."
2653   (< gnus-score gnus-agent-low-score))
2654
2655 (defun gnus-agent-high-scored-p ()
2656   "Say whether an article has a high score or not."
2657   (> gnus-score gnus-agent-high-score))
2658
2659 (defun gnus-agent-read-p ()
2660   "Say whether an article is read or not."
2661   (gnus-member-of-range (mail-header-number gnus-headers)
2662                         (gnus-info-read (gnus-get-info gnus-newsgroup-name))))
2663
2664 (defun gnus-category-make-function (predicate)
2665   "Make a function from PREDICATE."
2666   (let ((func (gnus-category-make-function-1 predicate)))
2667     (if (and (= (length func) 1)
2668              (symbolp (car func)))
2669         (car func)
2670       (gnus-byte-compile `(lambda () ,func)))))
2671
2672 (defun gnus-agent-true ()
2673   "Return t."
2674   t)
2675
2676 (defun gnus-agent-false ()
2677   "Return nil."
2678   nil)
2679
2680 (defun gnus-category-make-function-1 (predicate)
2681   "Make a function from PREDICATE."
2682   (cond
2683    ;; Functions are just returned as is.
2684    ((or (symbolp predicate)
2685         (functionp predicate))
2686     `(,(or (cdr (assq predicate gnus-category-predicate-alist))
2687            predicate)))
2688    ;; More complex predicate.
2689    ((consp predicate)
2690     `(,(cond
2691         ((memq (car predicate) '(& and))
2692          'and)
2693         ((memq (car predicate) '(| or))
2694          'or)
2695         ((memq (car predicate) gnus-category-not)
2696          'not))
2697       ,@(mapcar 'gnus-category-make-function-1 (cdr predicate))))
2698    (t
2699     (error "Unknown predicate type: %s" predicate))))
2700
2701 (defun gnus-get-predicate (predicate)
2702   "Return the function implementing PREDICATE."
2703   (or (cdr (assoc predicate gnus-category-predicate-cache))
2704       (let ((func (gnus-category-make-function predicate)))
2705         (setq gnus-category-predicate-cache
2706               (nconc gnus-category-predicate-cache
2707                      (list (cons predicate func))))
2708         func)))
2709
2710 (defun gnus-predicate-implies-unread (predicate)
2711   "Say whether PREDICATE implies unread articles only.
2712 It is okay to miss some cases, but there must be no false positives.
2713 That is, if this predicate returns true, then indeed the predicate must
2714 return only unread articles."
2715   (eq t (gnus-function-implies-unread-1 
2716          (gnus-category-make-function-1 predicate))))
2717
2718 (defun gnus-function-implies-unread-1 (function)
2719   "Recursively evaluate a predicate function to determine whether it can select
2720 any read articles.  Returns t if the function is known to never
2721 return read articles, nil when it is known to always return read
2722 articles, and t_nil when the function may return both read and unread
2723 articles."
2724   (let ((func (car function))
2725         (args (mapcar 'gnus-function-implies-unread-1 (cdr function))))
2726     (cond ((eq func 'and)
2727            (cond ((memq t args) ; if any argument returns only unread articles
2728                   ;; then that argument constrains the result to only unread articles.
2729                   t)
2730                  ((memq 't_nil args) ; if any argument is indeterminate
2731                   ;; then the result is indeterminate
2732                   't_nil)))
2733           ((eq func 'or)
2734            (cond ((memq nil args) ; if any argument returns read articles
2735                   ;; then that argument ensures that the results includes read articles.
2736                   nil)
2737                  ((memq 't_nil args) ; if any argument is indeterminate
2738                   ;; then that argument ensures that the results are indeterminate
2739                   't_nil)
2740                  (t ; if all arguments return only unread articles
2741                   ;; then the result returns only unread articles
2742                   t)))
2743           ((eq func 'not)
2744            (cond ((eq (car args) 't_nil) ; if the argument is indeterminate
2745                   ; then the result is indeterminate
2746                   (car args))
2747                  (t ; otherwise
2748                   ; toggle the result to be the opposite of the argument
2749                   (not (car args)))))
2750           ((eq func 'gnus-agent-read-p)
2751            nil) ; The read predicate NEVER returns unread articles
2752           ((eq func 'gnus-agent-false)
2753            t) ; The false predicate returns t as the empty set excludes all read articles
2754           ((eq func 'gnus-agent-true)
2755            nil) ; The true predicate ALWAYS returns read articles
2756           ((catch 'found-match
2757              (let ((alist gnus-category-predicate-alist))
2758                (while alist
2759                  (if (eq func (cdar alist))
2760                      (throw 'found-match t)
2761                    (setq alist (cdr alist))))))
2762            't_nil) ; All other predicates return read and unread articles
2763           (t
2764            (error "Unknown predicate function: %s" function)))))
2765
2766 (defun gnus-group-category (group)
2767   "Return the category GROUP belongs to."
2768   (unless gnus-category-group-cache
2769     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
2770     (let ((cs gnus-category-alist)
2771           groups cat)
2772       (while (setq cat (pop cs))
2773         (setq groups (gnus-agent-cat-groups cat))
2774         (while groups
2775           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
2776   (or (gnus-gethash group gnus-category-group-cache)
2777       (assq 'default gnus-category-alist)))
2778
2779 (defun gnus-agent-expire-group (group &optional articles force)
2780   "Expire all old articles in GROUP.
2781 If you want to force expiring of certain articles, this function can
2782 take ARTICLES, and FORCE parameters as well.
2783
2784 The articles on which the expiration process runs are selected as follows:
2785   if ARTICLES is null, all read and unmarked articles.
2786   if ARTICLES is t, all articles.
2787   if ARTICLES is a list, just those articles.
2788 FORCE is equivalent to setting the expiration predicates to true."
2789   (interactive
2790    (list (let ((def (or (gnus-group-group-name)
2791                         gnus-newsgroup-name)))
2792            (let ((select (read-string (if def
2793                                           (concat "Group Name ("
2794                                                   def "): ")
2795                                         "Group Name: "))))
2796              (if (and (equal "" select)
2797                       def)
2798                  def
2799                select)))))
2800
2801   (if (not group)
2802       (gnus-agent-expire articles group force)
2803     (let ( ;; Bind gnus-agent-expire-stats to enable tracking of
2804           ;; expiration statistics of this single group
2805           (gnus-agent-expire-stats (list 0 0 0.0)))
2806       (if (or (not (eq articles t))
2807               (yes-or-no-p
2808                (concat "Are you sure that you want to "
2809                        "expire all articles in " group ".")))
2810           (let ((gnus-command-method (gnus-find-method-for-group group))
2811                 (overview (gnus-get-buffer-create " *expire overview*"))
2812                 orig)
2813             (unwind-protect
2814                 (let ((active-file (gnus-agent-lib-file "active")))
2815                   (when (file-exists-p active-file)
2816                     (with-temp-buffer
2817                       (nnheader-insert-file-contents active-file)
2818                       (gnus-active-to-gnus-format
2819                        gnus-command-method
2820                        (setq orig (gnus-make-hashtable
2821                                    (count-lines (point-min) (point-max))))))
2822                     (save-excursion
2823                       (gnus-agent-expire-group-1
2824                        group overview (gnus-gethash-safe group orig)
2825                        articles force))))
2826               (kill-buffer overview))))
2827       (gnus-message 4 (gnus-agent-expire-done-message)))))
2828
2829 (defun gnus-agent-expire-group-1 (group overview active articles force)
2830   ;; Internal function - requires caller to have set
2831   ;; gnus-command-method, initialized overview buffer, and to have
2832   ;; provided a non-nil active
2833
2834   (let ((dir (gnus-agent-group-pathname group)))
2835     (gnus-agent-with-refreshed-group 
2836      group
2837      (when (boundp 'gnus-agent-expire-current-dirs)
2838        (set 'gnus-agent-expire-current-dirs 
2839             (cons dir 
2840                   (symbol-value 'gnus-agent-expire-current-dirs))))
2841
2842      (if (and (not force)
2843               (eq 'DISABLE (gnus-agent-find-parameter group 
2844                                                       'agent-enable-expiration)))
2845          (gnus-message 5 "Expiry skipping over %s" group)
2846        (gnus-message 5 "Expiring articles in %s" group)
2847        (gnus-agent-load-alist group)
2848        (let* ((bytes-freed 0)
2849               (size-files-deleted 0.0)
2850               (files-deleted 0)
2851               (nov-entries-deleted 0)
2852               (info (gnus-get-info group))
2853               (alist gnus-agent-article-alist)
2854               (day (- (time-to-days (current-time))
2855                       (gnus-agent-find-parameter group 'agent-days-until-old)))
2856               (specials (if (and alist
2857                                  (not force))
2858                             ;; This could be a bit of a problem.  I need to
2859                             ;; keep the last article to avoid refetching
2860                             ;; headers when using nntp in the backend.  At
2861                             ;; the same time, if someone uses a backend
2862                             ;; that supports article moving then I may have
2863                             ;; to remove the last article to complete the
2864                             ;; move.  Right now, I'm going to assume that
2865                             ;; FORCE overrides specials.
2866                             (list (caar (last alist)))))
2867               (unreads ;; Articles that are excluded from the
2868                ;; expiration process
2869                (cond (gnus-agent-expire-all
2870                       ;; All articles are marked read by global decree
2871                       nil)
2872                      ((eq articles t)
2873                       ;; All articles are marked read by function
2874                       ;; parameter
2875                       nil)
2876                      ((not articles)
2877                       ;; Unread articles are marked protected from
2878                       ;; expiration Don't call
2879                       ;; gnus-list-of-unread-articles as it returns
2880                       ;; articles that have not been fetched into the
2881                       ;; agent.
2882                       (ignore-errors
2883                         (gnus-agent-unread-articles group)))
2884                      (t
2885                       ;; All articles EXCEPT those named by the caller
2886                       ;; are protected from expiration
2887                       (gnus-sorted-difference
2888                        (gnus-uncompress-range
2889                         (cons (caar alist)
2890                               (caar (last alist))))
2891                        (sort articles '<)))))
2892               (marked ;; More articles that are excluded from the
2893                ;; expiration process
2894                (cond (gnus-agent-expire-all
2895                       ;; All articles are unmarked by global decree
2896                       nil)
2897                      ((eq articles t)
2898                       ;; All articles are unmarked by function
2899                       ;; parameter
2900                       nil)
2901                      (articles
2902                       ;; All articles may as well be unmarked as the
2903                       ;; unreads list already names the articles we are
2904                       ;; going to keep
2905                       nil)
2906                      (t
2907                       ;; Ticked and/or dormant articles are excluded
2908                       ;; from expiration
2909                       (nconc
2910                        (gnus-uncompress-range
2911                         (cdr (assq 'tick (gnus-info-marks info))))
2912                        (gnus-uncompress-range
2913                         (cdr (assq 'dormant
2914                                    (gnus-info-marks info))))))))
2915               (nov-file (concat dir ".overview"))
2916               (cnt 0)
2917               (completed -1)
2918               dlist
2919               type)
2920
2921          ;; The normal article alist contains elements that look like
2922          ;; (article# .  fetch_date) I need to combine other
2923          ;; information with this list.  For example, a flag indicating
2924          ;; that a particular article MUST BE KEPT.  To do this, I'm
2925          ;; going to transform the elements to look like (article#
2926          ;; fetch_date keep_flag NOV_entry_marker) Later, I'll reverse
2927          ;; the process to generate the expired article alist.
2928
2929          ;; Convert the alist elements to (article# fetch_date nil
2930          ;; nil).
2931          (setq dlist (mapcar (lambda (e)
2932                                (list (car e) (cdr e) nil nil)) alist))
2933
2934          ;; Convert the keep lists to elements that look like (article#
2935          ;; nil keep_flag nil) then append it to the expanded dlist
2936          ;; These statements are sorted by ascending precidence of the
2937          ;; keep_flag.
2938          (setq dlist (nconc dlist
2939                             (mapcar (lambda (e)
2940                                       (list e nil 'unread  nil))
2941                                     unreads)))
2942          (setq dlist (nconc dlist
2943                             (mapcar (lambda (e)
2944                                       (list e nil 'marked  nil))
2945                                     marked)))
2946          (setq dlist (nconc dlist
2947                             (mapcar (lambda (e)
2948                                       (list e nil 'special nil))
2949                                     specials)))
2950
2951          (set-buffer overview)
2952          (erase-buffer)
2953          (buffer-disable-undo)
2954          (when (file-exists-p nov-file)
2955            (gnus-message 7 "gnus-agent-expire: Loading overview...")
2956            (nnheader-insert-file-contents nov-file)
2957            (goto-char (point-min))
2958
2959            (let (p)
2960              (while (< (setq p (point)) (point-max))
2961                (condition-case nil
2962                    ;; If I successfully read an integer (the plus zero
2963                    ;; ensures a numeric type), prepend a marker entry
2964                    ;; to the list
2965                    (push (list (+ 0 (read (current-buffer))) nil nil
2966                                (set-marker (make-marker) p))
2967                          dlist)
2968                  (error
2969                   (gnus-message 1 "gnus-agent-expire: read error \
2970 occurred when reading expression at %s in %s.  Skipping to next \
2971 line." (point) nov-file)))
2972                ;; Whether I succeeded, or failed, it doesn't matter.
2973                ;; Move to the next line then try again.
2974                (forward-line 1)))
2975
2976            (gnus-message
2977             7 "gnus-agent-expire: Loading overview... Done"))
2978          (set-buffer-modified-p nil)
2979
2980          ;; At this point, all of the information is in dlist.  The
2981          ;; only problem is that much of it is spread across multiple
2982          ;; entries.  Sort then MERGE!!
2983          (gnus-message 7 "gnus-agent-expire: Sorting entries... ")
2984          ;; If two entries have the same article-number then sort by
2985          ;; ascending keep_flag.
2986          (let ((special 0)
2987                (marked 1)
2988                (unread 2))
2989            (setq dlist
2990                  (sort dlist
2991                        (lambda (a b)
2992                          (cond ((< (nth 0 a) (nth 0 b))
2993                                 t)
2994                                ((> (nth 0 a) (nth 0 b))
2995                                 nil)
2996                                (t
2997                                 (let ((a (or (symbol-value (nth 2 a))
2998                                              3))
2999                                       (b (or (symbol-value (nth 2 b))
3000                                              3)))
3001                                   (<= a b))))))))
3002          (gnus-message 7 "gnus-agent-expire: Sorting entries... Done")
3003          (gnus-message 7 "gnus-agent-expire: Merging entries... ")
3004          (let ((dlist dlist))
3005            (while (cdr dlist)           ; I'm not at the end-of-list
3006              (if (eq (caar dlist) (caadr dlist))
3007                  (let ((first (cdr (car dlist)))
3008                        (secnd (cdr (cadr dlist))))
3009                    (setcar first (or (car first)
3010                                      (car secnd))) ; fetch_date
3011                    (setq first (cdr first)
3012                          secnd (cdr secnd))
3013                    (setcar first (or (car first)
3014                                      (car secnd))) ; Keep_flag
3015                    (setq first (cdr first)
3016                          secnd (cdr secnd))
3017                    (setcar first (or (car first)
3018                                      (car secnd))) ; NOV_entry_marker
3019
3020                    (setcdr dlist (cddr dlist)))
3021                (setq dlist (cdr dlist)))))
3022          (gnus-message 7 "gnus-agent-expire: Merging entries... Done")
3023
3024          (let* ((len (float (length dlist)))
3025                 (alist (list nil))
3026                 (tail-alist alist))
3027            (while dlist
3028              (let ((new-completed (truncate (* 100.0
3029                                                (/ (setq cnt (1+ cnt))
3030                                                   len))))
3031                    message-log-max)
3032                (when (> new-completed completed)
3033                  (setq completed new-completed)
3034                  (gnus-message 7 "%3d%% completed..."  completed)))
3035              (let* ((entry          (car dlist))
3036                     (article-number (nth 0 entry))
3037                     (fetch-date     (nth 1 entry))
3038                     (keep           (nth 2 entry))
3039                     (marker         (nth 3 entry)))
3040
3041                (cond
3042                 ;; Kept articles are unread, marked, or special.
3043                 (keep
3044                  (gnus-agent-message 10
3045                                      "gnus-agent-expire: %s:%d: Kept %s article%s."
3046                                      group article-number keep (if fetch-date " and file" ""))
3047                  (when fetch-date
3048                    (unless (file-exists-p
3049                             (concat dir (number-to-string
3050                                          article-number)))
3051                      (setf (nth 1 entry) nil)
3052                      (gnus-agent-message 3 "gnus-agent-expire cleared \
3053 download flag on %s:%d as the cached article file is missing."
3054                                          group (caar dlist)))
3055                    (unless marker
3056                      (gnus-message 1 "gnus-agent-expire detected a \
3057 missing NOV entry.  Run gnus-agent-regenerate-group to restore it.")))
3058                  (gnus-agent-append-to-list
3059                   tail-alist
3060                   (cons article-number fetch-date)))
3061
3062                 ;; The following articles are READ, UNMARKED, and
3063                 ;; ORDINARY.  See if they can be EXPIRED!!!
3064                 ((setq type
3065                        (cond
3066                         ((not (integerp fetch-date))
3067                          'read) ;; never fetched article (may expire
3068                         ;; right now)
3069                         ((not (file-exists-p
3070                                (concat dir (number-to-string
3071                                             article-number))))
3072                          (setf (nth 1 entry) nil)
3073                          'externally-expired) ;; Can't find the cached
3074                         ;; article.  Handle case
3075                         ;; as though this article
3076                         ;; was never fetched.
3077
3078                         ;; We now have the arrival day, so we see
3079                         ;; whether it's old enough to be expired.
3080                         ((< fetch-date day)
3081                          'expired)
3082                         (force
3083                          'forced)))
3084
3085                  ;; I found some reason to expire this entry.
3086
3087                  (let ((actions nil))
3088                    (when (memq type '(forced expired))
3089                      (ignore-errors     ; Just being paranoid.
3090                        (let* ((file-name (nnheader-concat dir (number-to-string
3091                                                                article-number)))
3092                               (size (float (nth 7 (file-attributes file-name)))))
3093                          (incf bytes-freed size)
3094                          (incf size-files-deleted size)
3095                          (incf files-deleted)
3096                          (delete-file file-name))
3097                        (push "expired cached article" actions))
3098                      (setf (nth 1 entry) nil)
3099                      )
3100
3101                    (when marker
3102                      (push "NOV entry removed" actions)
3103                      (goto-char marker)
3104
3105                      (incf nov-entries-deleted)
3106
3107                      (let ((from (point-at-bol))
3108                            (to (progn (forward-line 1) (point))))
3109                        (incf bytes-freed (- to from))
3110                        (delete-region from to)))
3111
3112                    ;; If considering all articles is set, I can only
3113                    ;; expire article IDs that are no longer in the
3114                    ;; active range (That is, articles that preceed the
3115                    ;; first article in the new alist).
3116                    (if (and gnus-agent-consider-all-articles
3117                             (>= article-number (car active)))
3118                        ;; I have to keep this ID in the alist
3119                        (gnus-agent-append-to-list
3120                         tail-alist (cons article-number fetch-date))
3121                      (push (format "Removed %s article number from \
3122 article alist" type) actions))
3123
3124                    (when actions
3125                      (gnus-agent-message 8 "gnus-agent-expire: %s:%d: %s"
3126                                          group article-number
3127                                          (mapconcat 'identity actions ", ")))))
3128                 (t
3129                  (gnus-agent-message
3130                   10 "gnus-agent-expire: %s:%d: Article kept as \
3131 expiration tests failed." group article-number)
3132                  (gnus-agent-append-to-list
3133                   tail-alist (cons article-number fetch-date)))
3134                 )
3135
3136                ;; Clean up markers as I want to recycle this buffer
3137                ;; over several groups.
3138                (when marker
3139                  (set-marker marker nil))
3140
3141                (setq dlist (cdr dlist))))
3142
3143            (setq alist (cdr alist))
3144
3145            (let ((inhibit-quit t))
3146              (unless (equal alist gnus-agent-article-alist)
3147                (setq gnus-agent-article-alist alist)
3148                (gnus-agent-save-alist group))
3149
3150              (when (buffer-modified-p)
3151                (let ((coding-system-for-write
3152                       gnus-agent-file-coding-system))
3153                  (gnus-make-directory dir)
3154                  (write-region (point-min) (point-max) nov-file nil
3155                                'silent)
3156                  ;; clear the modified flag as that I'm not confused by
3157                  ;; its status on the next pass through this routine.
3158                  (set-buffer-modified-p nil)
3159                  (gnus-agent-update-view-total-fetched-for group t)))
3160
3161              (when (eq articles t)
3162                (gnus-summary-update-info))))
3163
3164          (when (boundp 'gnus-agent-expire-stats)
3165            (let ((stats (symbol-value 'gnus-agent-expire-stats)))
3166              (incf (nth 2 stats) bytes-freed)
3167              (incf (nth 1 stats) files-deleted)
3168              (incf (nth 0 stats) nov-entries-deleted)))
3169
3170          (gnus-agent-update-files-total-fetched-for group (- size-files-deleted)))))))
3171
3172 (defun gnus-agent-expire (&optional articles group force)
3173   "Expire all old articles.
3174 If you want to force expiring of certain articles, this function can
3175 take ARTICLES, GROUP and FORCE parameters as well.
3176
3177 The articles on which the expiration process runs are selected as follows:
3178   if ARTICLES is null, all read and unmarked articles.
3179   if ARTICLES is t, all articles.
3180   if ARTICLES is a list, just those articles.
3181 Setting GROUP will limit expiration to that group.
3182 FORCE is equivalent to setting the expiration predicates to true."
3183   (interactive)
3184   
3185   (if group
3186       (gnus-agent-expire-group group articles force)
3187     (if (or (not (eq articles t))
3188             (yes-or-no-p "Are you sure that you want to expire all \
3189 articles in every agentized group."))
3190         (let ((methods (gnus-agent-covered-methods))
3191               ;; Bind gnus-agent-expire-current-dirs to enable tracking
3192               ;; of agent directories.
3193               (gnus-agent-expire-current-dirs nil)
3194               ;; Bind gnus-agent-expire-stats to enable tracking of
3195               ;; expiration statistics across all groups
3196               (gnus-agent-expire-stats (list 0 0 0.0))
3197               gnus-command-method overview orig)
3198           (setq overview (gnus-get-buffer-create " *expire overview*"))
3199           (unwind-protect
3200               (while (setq gnus-command-method (pop methods))
3201                 (let ((active-file (gnus-agent-lib-file "active")))
3202                   (when (file-exists-p active-file)
3203                     (with-temp-buffer
3204                       (nnheader-insert-file-contents active-file)
3205                       (gnus-active-to-gnus-format
3206                        gnus-command-method
3207                        (setq orig (gnus-make-hashtable
3208                                    (count-lines (point-min) (point-max))))))
3209                     (dolist (expiring-group (gnus-groups-from-server
3210                                              gnus-command-method))
3211                       (let* ((active
3212                               (gnus-gethash-safe expiring-group orig)))
3213                                         
3214                         (when active
3215                           (save-excursion
3216                             (gnus-agent-expire-group-1
3217                              expiring-group overview active articles force))))))))
3218             (kill-buffer overview))
3219           (gnus-agent-expire-unagentized-dirs)
3220           (gnus-message 4 (gnus-agent-expire-done-message))))))
3221
3222 (defun gnus-agent-expire-done-message ()
3223   (if (and (> gnus-verbose 4)
3224            (boundp 'gnus-agent-expire-stats))
3225       (let* ((stats (symbol-value 'gnus-agent-expire-stats))
3226              (size (nth 2 stats))
3227             (units '(B KB MB GB)))
3228         (while (and (> size 1024.0)
3229                     (cdr units))
3230           (setq size (/ size 1024.0)
3231                 units (cdr units)))
3232
3233         (format "Expiry recovered %d NOV entries, deleted %d files,\
3234  and freed %f %s." 
3235                 (nth 0 stats) 
3236                 (nth 1 stats) 
3237                 size (car units)))
3238     "Expiry...done"))
3239
3240 (defun gnus-agent-expire-unagentized-dirs ()
3241   (when (and gnus-agent-expire-unagentized-dirs
3242              (boundp 'gnus-agent-expire-current-dirs))
3243     (let* ((keep (gnus-make-hashtable))
3244            ;; Formally bind gnus-agent-expire-current-dirs so that the
3245            ;; compiler will not complain about free references.
3246            (gnus-agent-expire-current-dirs
3247             (symbol-value 'gnus-agent-expire-current-dirs))
3248            dir)
3249
3250       (gnus-sethash gnus-agent-directory t keep)
3251       (while gnus-agent-expire-current-dirs
3252         (setq dir (pop gnus-agent-expire-current-dirs))
3253         (when (and (stringp dir)
3254                    (file-directory-p dir))
3255           (while (not (gnus-gethash dir keep))
3256             (gnus-sethash dir t keep)
3257             (setq dir (file-name-directory (directory-file-name dir))))))
3258
3259       (let* (to-remove
3260              checker
3261              (checker
3262               (function
3263                (lambda (d)
3264                  "Given a directory, check it and its subdirectories for 
3265               membership in the keep hash.  If it isn't found, add 
3266               it to to-remove." 
3267                  (let ((files (directory-files d))
3268                        file)
3269                    (while (setq file (pop files))
3270                      (cond ((equal file ".") ; Ignore self
3271                             nil)
3272                            ((equal file "..") ; Ignore parent
3273                             nil)
3274                            ((equal file ".overview") 
3275                             ;; Directory must contain .overview to be
3276                             ;; agent's cache of a group.
3277                             (let ((d (file-name-as-directory d))
3278                                   r)
3279                               ;; Search ancestor's for last directory NOT
3280                               ;; found in keep hash.
3281                               (while (not (gnus-gethash
3282                                            (setq d (file-name-directory d)) keep))
3283                                 (setq r d
3284                                       d (directory-file-name d)))
3285                               ;; if ANY ancestor was NOT in keep hash and
3286                               ;; it it's already in to-remove, add it to
3287                               ;; to-remove.                          
3288                               (if (and r
3289                                        (not (member r to-remove)))
3290                                   (push r to-remove))))
3291                            ((file-directory-p (setq file (nnheader-concat d file)))
3292                             (funcall checker file)))))))))
3293         (funcall checker (expand-file-name gnus-agent-directory))
3294
3295         (when (and to-remove
3296                    (or gnus-expert-user
3297                        (gnus-y-or-n-p
3298                         "gnus-agent-expire has identified local directories that are\
3299  not currently required by any agentized group.  Do you wish to consider\
3300  deleting them?")))
3301           (while to-remove
3302             (let ((dir (pop to-remove)))
3303               (if (gnus-y-or-n-p (format "Delete %s? " dir))
3304                   (let* (delete-recursive
3305                          (delete-recursive
3306                           (function
3307                            (lambda (f-or-d)
3308                              (ignore-errors
3309                                (if (file-directory-p f-or-d)
3310                                    (condition-case nil
3311                                        (delete-directory f-or-d)
3312                                      (file-error
3313                                       (mapcar (lambda (f)
3314                                                 (or (member f '("." ".."))
3315                                                     (funcall delete-recursive
3316                                                              (nnheader-concat
3317                                                               f-or-d f))))
3318                                               (directory-files f-or-d))
3319                                       (delete-directory f-or-d)))
3320                                  (delete-file f-or-d)))))))
3321                     (funcall delete-recursive dir))))))))))
3322
3323 ;;;###autoload
3324 (defun gnus-agent-batch ()
3325   "Start Gnus, send queue and fetch session."
3326   (interactive)
3327   (let ((init-file-user "")
3328         (gnus-always-read-dribble-file t))
3329     (gnus))
3330   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
3331     (gnus-group-send-queue)
3332     (gnus-agent-fetch-session)))
3333
3334 (defun gnus-agent-unread-articles (group)
3335   (let* ((read (gnus-info-read (gnus-get-info group)))
3336          (known (gnus-agent-load-alist group))
3337          (unread (list nil))
3338          (tail-unread unread))
3339     (while (and known read)
3340       (let ((candidate (car (pop known))))
3341         (while (let* ((range (car read))
3342                       (min   (if (numberp range) range (car range)))
3343                       (max   (if (numberp range) range (cdr range))))
3344                  (cond ((or (not min)
3345                             (< candidate min))
3346                         (gnus-agent-append-to-list tail-unread candidate)
3347                         nil)
3348                        ((> candidate max)
3349                         (setq read (cdr read))
3350                         ;; return t so that I always loop one more
3351                         ;; time.  If I just iterated off the end of
3352                         ;; read, min will become nil and the current
3353                         ;; candidate will be added to the unread list.
3354                         t))))))
3355     (while known
3356       (gnus-agent-append-to-list tail-unread (car (pop known))))
3357     (cdr unread)))
3358
3359 (defun gnus-agent-uncached-articles (articles group &optional cached-header)
3360   "Restrict ARTICLES to numbers already fetched.
3361 Returns a sublist of ARTICLES that excludes thos article ids in GROUP
3362 that have already been fetched.
3363 If CACHED-HEADER is nil, articles are only excluded if the article itself
3364 has been fetched."
3365
3366   ;; Logically equivalent to: (gnus-sorted-difference articles (mapcar
3367   ;; 'car gnus-agent-article-alist))
3368
3369   ;; Functionally, I don't need to construct a temp list using mapcar.
3370
3371   (if (and (or gnus-agent-cache (not gnus-plugged))
3372            (gnus-agent-load-alist group))
3373     (let* ((ref gnus-agent-article-alist)
3374            (arts articles)
3375            (uncached (list nil))
3376            (tail-uncached uncached))
3377       (while (and ref arts)
3378         (let ((v1 (car arts))
3379               (v2 (caar ref)))
3380           (cond ((< v1 v2) ; v1 does not appear in the reference list
3381                  (gnus-agent-append-to-list tail-uncached v1)
3382                  (setq arts (cdr arts)))
3383                 ((= v1 v2)
3384                  (unless (or cached-header (cdar ref)) ; v1 is already cached
3385                    (gnus-agent-append-to-list tail-uncached v1))
3386                  (setq arts (cdr arts))
3387                  (setq ref (cdr ref)))
3388                 (t ; reference article (v2) preceeds the list being filtered
3389                  (setq ref (cdr ref))))))
3390       (while arts
3391         (gnus-agent-append-to-list tail-uncached (pop arts)))
3392       (cdr uncached))
3393     ;; if gnus-agent-load-alist fails, no articles are cached.
3394     articles))
3395
3396 (defun gnus-agent-retrieve-headers (articles group &optional fetch-old)
3397   (save-excursion
3398     (gnus-agent-create-buffer)
3399     (let ((gnus-decode-encoded-word-function 'identity)
3400           (file (gnus-agent-article-name ".overview" group))
3401           cached-articles uncached-articles)
3402       (gnus-make-directory (nnheader-translate-file-chars
3403                             (file-name-directory file) t))
3404
3405       ;; Populate temp buffer with known headers
3406       (when (file-exists-p file)
3407         (with-current-buffer gnus-agent-overview-buffer
3408           (erase-buffer)
3409           (let ((nnheader-file-coding-system
3410                  gnus-agent-file-coding-system))
3411             (nnheader-insert-nov-file file (car articles)))))
3412
3413       (if (setq uncached-articles (gnus-agent-uncached-articles articles group
3414                                                                 t))
3415           (progn
3416             ;; Populate nntp-server-buffer with uncached headers
3417             (set-buffer nntp-server-buffer)
3418             (erase-buffer)
3419             (cond ((not (eq 'nov (let (gnus-agent) ; Turn off agent
3420                                    (gnus-retrieve-headers
3421                                     uncached-articles group fetch-old))))
3422                    (nnvirtual-convert-headers))
3423                   ((eq 'nntp (car gnus-current-select-method))
3424                    ;; The author of gnus-get-newsgroup-headers-xover
3425                    ;; reports that the XOVER command is commonly
3426                    ;; unreliable. The problem is that recently
3427                    ;; posted articles may not be entered into the
3428                    ;; NOV database in time to respond to my XOVER
3429                    ;; query.
3430                    ;;
3431                    ;; I'm going to use his assumption that the NOV
3432                    ;; database is updated in order of ascending
3433                    ;; article ID.  Therefore, a response containing
3434                    ;; article ID N implies that all articles from 1
3435                    ;; to N-1 are up-to-date.  Therefore, missing
3436                    ;; articles in that range have expired.
3437
3438                    (set-buffer nntp-server-buffer)
3439                    (let* ((fetched-articles (list nil))
3440                           (tail-fetched-articles fetched-articles)
3441                           (min (cond ((numberp fetch-old)
3442                                       (max 1 (- (car articles) fetch-old)))
3443                                      (fetch-old
3444                                       1)
3445                                      (t
3446                                       (car articles))))
3447                           (max (car (last articles))))
3448
3449                      ;; Get the list of articles that were fetched
3450                      (goto-char (point-min))
3451                      (let ((pm (point-max)))
3452                        (while (< (point) pm)
3453                          (when (looking-at "[0-9]+\t")
3454                            (gnus-agent-append-to-list
3455                             tail-fetched-articles
3456                             (read (current-buffer))))
3457                          (forward-line 1)))
3458
3459                      ;; Clip this list to the headers that will
3460                      ;; actually be returned
3461                      (setq fetched-articles (gnus-list-range-intersection
3462                                              (cdr fetched-articles)
3463                                              (cons min max)))
3464
3465                      ;; Clip the uncached articles list to exclude
3466                      ;; IDs after the last FETCHED header.  The
3467                      ;; excluded IDs may be fetchable using HEAD.
3468                      (if (car tail-fetched-articles)
3469                          (setq uncached-articles
3470                                (gnus-list-range-intersection
3471                                 uncached-articles
3472                                 (cons (car uncached-articles)
3473                                       (car tail-fetched-articles)))))
3474
3475                      ;; Create the list of articles that were
3476                      ;; "successfully" fetched.  Success, in this
3477                      ;; case, means that the ID should not be
3478                      ;; fetched again.  In the case of an expired
3479                      ;; article, the header will not be fetched.
3480                      (setq uncached-articles
3481                            (gnus-sorted-nunion fetched-articles
3482                                                uncached-articles))
3483                      )))
3484
3485             ;; Erase the temp buffer
3486             (set-buffer gnus-agent-overview-buffer)
3487             (erase-buffer)
3488
3489             ;; Copy the nntp-server-buffer to the temp buffer
3490             (set-buffer nntp-server-buffer)
3491             (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
3492
3493             ;; Merge the temp buffer with the known headers (found on
3494             ;; disk in FILE) into the nntp-server-buffer
3495             (when (and uncached-articles (file-exists-p file))
3496               (gnus-agent-braid-nov group uncached-articles file))
3497
3498             ;; Save the new set of known headers to FILE
3499             (set-buffer nntp-server-buffer)
3500             (let ((coding-system-for-write
3501                    gnus-agent-file-coding-system))
3502               (gnus-agent-check-overview-buffer)
3503               (write-region (point-min) (point-max) file nil 'silent))
3504
3505             (gnus-agent-update-view-total-fetched-for group t)
3506
3507             ;; Update the group's article alist to include the newly
3508             ;; fetched articles.
3509             (gnus-agent-load-alist group)
3510             (gnus-agent-save-alist group uncached-articles nil)
3511             )
3512
3513         ;; Copy the temp buffer to the nntp-server-buffer
3514         (set-buffer nntp-server-buffer)
3515         (erase-buffer)
3516         (insert-buffer-substring gnus-agent-overview-buffer)))
3517
3518     (if (and fetch-old
3519              (not (numberp fetch-old)))
3520         t                               ; Don't remove anything.
3521       (nnheader-nov-delete-outside-range
3522        (if fetch-old (max 1 (- (car articles) fetch-old))
3523          (car articles))
3524        (car (last articles)))
3525       t)
3526
3527     'nov))
3528
3529 (defun gnus-agent-request-article (article group)
3530   "Retrieve ARTICLE in GROUP from the agent cache."
3531   (when (and gnus-agent
3532              (or gnus-agent-cache
3533                  (not gnus-plugged))
3534              (numberp article))
3535     (let* ((gnus-command-method (gnus-find-method-for-group group))
3536            (file (gnus-agent-article-name (number-to-string article) group))
3537            (buffer-read-only nil))
3538       (when (and (file-exists-p file)
3539                  (> (nth 7 (file-attributes file)) 0))
3540         (erase-buffer)
3541         (gnus-kill-all-overlays)
3542         (let ((coding-system-for-read gnus-cache-coding-system))
3543           (insert-file-contents file))
3544         t))))
3545
3546 (defun gnus-agent-regenerate-group (group &optional reread)
3547   "Regenerate GROUP.
3548 If REREAD is t, all articles in the .overview are marked as unread.
3549 If REREAD is a list, the specified articles will be marked as unread.
3550 In addition, their NOV entries in .overview will be refreshed using
3551 the articles' current headers.
3552 If REREAD is not nil, downloaded articles are marked as unread."
3553   (interactive
3554    (list (let ((def (or (gnus-group-group-name)
3555                         gnus-newsgroup-name)))
3556            (let ((select (read-string (if def
3557                                           (concat "Group Name ("
3558                                                   def "): ")
3559                                         "Group Name: "))))
3560              (if (and (equal "" select)
3561                       def)
3562                  def
3563                select)))
3564          (catch 'mark
3565            (while (let (c
3566                         (cursor-in-echo-area t)
3567                         (echo-keystrokes 0))
3568                     (message "Mark as unread: (n)one / (a)ll / all (d)ownloaded articles? (n) ")
3569                     (setq c (read-char-exclusive))
3570
3571                     (cond ((or (eq c ?\r) (eq c ?n) (eq c ?N))
3572                            (throw 'mark nil))
3573                           ((or (eq c ?a) (eq c ?A))
3574                            (throw 'mark t))
3575                           ((or (eq c ?d) (eq c ?D))
3576                            (throw 'mark 'some)))
3577                     (gnus-message 3 "Ignoring unexpected input")
3578                     (sit-for 1)
3579                     t)))))
3580   (when group
3581     (gnus-message 5 "Regenerating in %s" group)
3582     (let* ((gnus-command-method (or gnus-command-method
3583                                     (gnus-find-method-for-group group)))
3584            (file (gnus-agent-article-name ".overview" group))
3585            (dir (file-name-directory file))
3586            point
3587            (downloaded (if (file-exists-p dir)
3588                            (sort (mapcar (lambda (name) (string-to-int name))
3589                                          (directory-files dir nil "^[0-9]+$" t))
3590                                  '>)
3591                          (progn (gnus-make-directory dir) nil)))
3592            dl nov-arts
3593            alist header
3594            regenerated)
3595
3596       (mm-with-unibyte-buffer
3597         (if (file-exists-p file)
3598             (let ((nnheader-file-coding-system
3599                    gnus-agent-file-coding-system))
3600               (nnheader-insert-file-contents file)))
3601         (set-buffer-modified-p nil)
3602
3603         ;; Load the article IDs found in the overview file.  As a
3604         ;; side-effect, validate the file contents.
3605         (let ((load t))
3606           (while load
3607             (setq load nil)
3608             (goto-char (point-min))
3609             (while (< (point) (point-max))
3610               (cond ((and (looking-at "[0-9]+\t")
3611                           (<= (- (match-end 0) (match-beginning 0)) 9))
3612                      (push (read (current-buffer)) nov-arts)
3613                      (forward-line 1)
3614                      (let ((l1 (car nov-arts))
3615                            (l2 (cadr nov-arts)))
3616                        (cond ((and (listp reread) (memq l1 reread))
3617                               (gnus-delete-line)
3618                               (setq nov-arts (cdr nov-arts))
3619                               (gnus-message 4 "gnus-agent-regenerate-group: NOV\
3620 entry of article %s deleted." l1))
3621                              ((not l2)
3622                               nil)
3623                              ((< l1 l2)
3624                               (gnus-message 3 "gnus-agent-regenerate-group: NOV\
3625  entries are NOT in ascending order.")
3626                               ;; Don't sort now as I haven't verified
3627                               ;; that every line begins with a number
3628                               (setq load t))
3629                              ((= l1 l2)
3630                               (forward-line -1)
3631                               (gnus-message 4 "gnus-agent-regenerate-group: NOV\
3632  entries contained duplicate of article %s.      Duplicate deleted." l1)
3633                               (gnus-delete-line)
3634                               (setq nov-arts (cdr nov-arts))))))
3635                     (t
3636                      (gnus-message 1 "gnus-agent-regenerate-group: NOV\
3637  entries contained line that did not begin with an article number.  Deleted\
3638  line.")
3639                      (gnus-delete-line))))
3640             (when load
3641               (gnus-message 5 "gnus-agent-regenerate-group: Sorting NOV\
3642  entries into ascending order.")
3643               (sort-numeric-fields 1 (point-min) (point-max))
3644               (setq nov-arts nil))))
3645         (gnus-agent-check-overview-buffer)
3646
3647         ;; Construct a new article alist whose nodes match every header
3648         ;; in the .overview file.  As a side-effect, missing headers are
3649         ;; reconstructed from the downloaded article file.
3650         (while (or downloaded nov-arts)
3651           (cond ((and downloaded
3652                       (or (not nov-arts)
3653                           (> (car downloaded) (car nov-arts))))
3654                  ;; This entry is missing from the overview file
3655                  (gnus-message 3 "Regenerating NOV %s %d..." group
3656                                (car downloaded))
3657                  (let ((file (concat dir (number-to-string (car downloaded)))))
3658                    (mm-with-unibyte-buffer
3659                      (nnheader-insert-file-contents file)
3660                      (nnheader-remove-body)
3661                      (setq header (nnheader-parse-naked-head)))
3662                    (mail-header-set-number header (car downloaded))
3663                    (if nov-arts
3664                        (let ((key (concat "^" (int-to-string (car nov-arts))
3665                                           "\t")))
3666                          (or (re-search-backward key nil t)
3667                              (re-search-forward key))
3668                          (forward-line 1))
3669                      (goto-char (point-min)))
3670                    (nnheader-insert-nov header))
3671                  (setq nov-arts (cons (car downloaded) nov-arts)))
3672                 ((eq (car downloaded) (car nov-arts))
3673                  ;; This entry in the overview has been downloaded
3674                  (push (cons (car downloaded)
3675                              (time-to-days
3676                               (nth 5 (file-attributes
3677                                       (concat dir (number-to-string
3678                                                    (car downloaded))))))) alist)
3679                  (setq downloaded (cdr downloaded))
3680                  (setq nov-arts (cdr nov-arts)))
3681                 (t
3682                  ;; This entry in the overview has not been downloaded
3683                  (push (cons (car nov-arts) nil) alist)
3684                  (setq nov-arts (cdr nov-arts)))))
3685
3686         ;; When gnus-agent-consider-all-articles is set,
3687         ;; gnus-agent-regenerate-group should NOT remove article IDs from
3688         ;; the alist.  Those IDs serve as markers to indicate that an
3689         ;; attempt has been made to fetch that article's header.
3690
3691         ;; When gnus-agent-consider-all-articles is NOT set,
3692         ;; gnus-agent-regenerate-group can remove the article ID of every
3693         ;; article (with the exception of the last ID in the list - it's
3694         ;; special) that no longer appears in the overview.  In this
3695         ;; situtation, the last article ID in the list implies that it,
3696         ;; and every article ID preceeding it, have been fetched from the
3697         ;; server.
3698
3699         (if gnus-agent-consider-all-articles
3700             ;; Restore all article IDs that were not found in the overview file.
3701             (let* ((n (cons nil alist))
3702                    (merged n)
3703                    (o (gnus-agent-load-alist group)))
3704               (while o
3705                 (let ((nID (caadr n))
3706                       (oID (caar o)))
3707                   (cond ((not nID)
3708                          (setq n (setcdr n (list (list oID))))
3709                          (setq o (cdr o)))
3710                         ((< oID nID)
3711                          (setcdr n (cons (list oID) (cdr n)))
3712                          (setq o (cdr o)))
3713                         ((= oID nID)
3714                          (setq o (cdr o))
3715                          (setq n (cdr n)))
3716                         (t
3717                          (setq n (cdr n))))))
3718               (setq alist (cdr merged)))
3719           ;; Restore the last article ID if it is not already in the new alist
3720           (let ((n (last alist))
3721                 (o (last (gnus-agent-load-alist group))))
3722             (cond ((not o)
3723                    nil)
3724                   ((not n)
3725                    (push (cons (caar o) nil) alist))
3726                   ((< (caar n) (caar o))
3727                    (setcdr n (list (car o)))))))
3728
3729         (let ((inhibit-quit t))
3730           (if (setq regenerated (buffer-modified-p))
3731               (let ((coding-system-for-write gnus-agent-file-coding-system))
3732                 (write-region (point-min) (point-max) file nil 'silent)))
3733
3734           (setq regenerated (or regenerated
3735                                 (and reread gnus-agent-article-alist)
3736                                 (not (equal alist gnus-agent-article-alist))))
3737
3738           (setq gnus-agent-article-alist alist)
3739
3740           (when regenerated
3741             (gnus-agent-save-alist group)
3742        
3743             ;; I have to alter the group's active range NOW as
3744             ;; gnus-make-ascending-articles-unread will use it to
3745             ;; recalculate the number of unread articles in the group
3746
3747             (let ((group (gnus-group-real-name group))
3748                   (group-active (or (gnus-active group)
3749                                     (gnus-activate-group group))))
3750               (gnus-agent-possibly-alter-active group group-active)))))
3751
3752       (when (and reread gnus-agent-article-alist)
3753         (gnus-make-ascending-articles-unread
3754          group
3755          (if (listp reread)
3756              reread
3757            (delq nil (mapcar (function (lambda (c)
3758                                          (cond ((eq reread t)
3759                                                 (car c))
3760                                                ((cdr c)
3761                                                 (car c)))))
3762                              gnus-agent-article-alist))))
3763
3764         (when regenerated
3765             (gnus-agent-update-files-total-fetched-for group nil)))
3766
3767       (gnus-message 5 "")
3768       regenerated)))
3769
3770 ;;;###autoload
3771 (defun gnus-agent-regenerate (&optional clean reread)
3772   "Regenerate all agent covered files.
3773 If CLEAN, obsolete (ignore)."
3774   (interactive "P")
3775   (let (regenerated)
3776     (gnus-message 4 "Regenerating Gnus agent files...")
3777     (dolist (gnus-command-method (gnus-agent-covered-methods))
3778         (dolist (group (gnus-groups-from-server gnus-command-method))
3779           (setq regenerated (or (gnus-agent-regenerate-group group reread)
3780                                 regenerated))))
3781     (gnus-message 4 "Regenerating Gnus agent files...done")
3782
3783     regenerated))
3784
3785 (defun gnus-agent-go-online (&optional force)
3786   "Switch servers into online status."
3787   (interactive (list t))
3788   (dolist (server gnus-opened-servers)
3789     (when (eq (nth 1 server) 'offline)
3790       (if (if (eq force 'ask)
3791               (gnus-y-or-n-p
3792                (format "Switch %s:%s into online status? "
3793                        (caar server) (cadar server)))
3794             force)
3795           (setcar (nthcdr 1 server) 'close)))))
3796
3797 (defun gnus-agent-toggle-group-plugged (group)
3798   "Toggle the status of the server of the current group."
3799   (interactive (list (gnus-group-group-name)))
3800   (let* ((method (gnus-find-method-for-group group))
3801          (status (cadr (assoc method gnus-opened-servers))))
3802     (if (eq status 'offline)
3803         (gnus-server-set-status method 'closed)
3804       (gnus-close-server method)
3805       (gnus-server-set-status method 'offline))
3806     (message "Turn %s:%s from %s to %s." (car method) (cadr method)
3807              (if (eq status 'offline) 'offline 'online)
3808              (if (eq status 'offline) 'online 'offline))))
3809
3810 (defun gnus-agent-group-covered-p (group)
3811   (gnus-agent-method-p (gnus-group-method group)))
3812
3813 (defun gnus-agent-update-files-total-fetched-for 
3814   (group delta &optional method path)
3815   "Update, or set, the total disk space used by the articles that the
3816 agent has fetched."
3817   (when gnus-agent-total-fetched-hashtb
3818     (gnus-agent-with-refreshed-group
3819      group
3820      ;; if null, gnus-agent-group-pathname will calc method.
3821      (let* ((gnus-command-method method) 
3822             (path (or path (gnus-agent-group-pathname group)))
3823             (entry (or (gnus-gethash path gnus-agent-total-fetched-hashtb)
3824                        (gnus-sethash path (make-list 3 0) 
3825                                      gnus-agent-total-fetched-hashtb))))
3826        (when (listp delta)
3827          (unless delta
3828            (setq delta (directory-files path nil "^-?[0-9]+$" t)))
3829
3830          (let ((sum 0.0)
3831                file)
3832            (while (setq file (pop delta))
3833              (incf sum (float (or (nth 7 (file-attributes 
3834                                           (nnheader-concat 
3835                                            path 
3836                                            (if (numberp file)
3837                                                (number-to-string file)
3838                                              file)))) 0))))
3839            (setq delta sum)))
3840
3841        (setq gnus-agent-need-update-total-fetched-for t)
3842        (incf (nth 2 entry) delta)))))
3843
3844 (defun gnus-agent-update-view-total-fetched-for 
3845   (group agent-over &optional method path)
3846   "Update, or set, the total disk space used by the .agentview and
3847 .overview files.  These files are calculated separately as they can be
3848 modified."
3849   (when gnus-agent-total-fetched-hashtb
3850     (gnus-agent-with-refreshed-group
3851      group
3852      ;; if null, gnus-agent-group-pathname will calc method.
3853      (let* ((gnus-command-method method) 
3854             (path (or path (gnus-agent-group-pathname group)))
3855             (entry (or (gnus-gethash path gnus-agent-total-fetched-hashtb)
3856                        (gnus-sethash path (make-list 3 0) 
3857                                      gnus-agent-total-fetched-hashtb)))
3858             (size (or (nth 7 (file-attributes 
3859                               (nnheader-concat
3860                                path (if agent-over 
3861                                         ".overview"
3862                                       ".agentview"))))
3863                       0)))
3864        (setq gnus-agent-need-update-total-fetched-for t)
3865        (setf (nth (if agent-over 1 0) entry) size)))))
3866
3867 (defun gnus-agent-total-fetched-for (group &optional method no-inhibit)
3868   "Get the total disk space used by the specified GROUP."
3869   (unless gnus-agent-total-fetched-hashtb
3870     (setq gnus-agent-total-fetched-hashtb (gnus-make-hashtable 1024)))
3871
3872   ;; if null, gnus-agent-group-pathname will calc method.
3873   (let* ((gnus-command-method method) 
3874          (path (gnus-agent-group-pathname group))
3875          (entry (gnus-gethash path gnus-agent-total-fetched-hashtb)))
3876     (if entry
3877         (apply '+ entry)
3878       (let ((gnus-agent-inhibit-update-total-fetched-for (not no-inhibit)))
3879         (+ 
3880          (gnus-agent-update-view-total-fetched-for  group nil method path)
3881          (gnus-agent-update-view-total-fetched-for  group t   method path)
3882          (gnus-agent-update-files-total-fetched-for group nil method path))))))
3883
3884 (provide 'gnus-agent)
3885
3886 ;;; arch-tag: b0ba4afc-5229-4cee-ad25-9956daa4e91e
3887 ;;; gnus-agent.el ends here