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