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