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