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