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