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