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