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