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