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