634b2b7a735490ab85ab498e2a6de7c2110a6bd2
[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                  (eq (gnus-server-status gnus-command-method) 'ok))
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: %s"
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                                  (let ((range (symbol-value symbol)))
2199                                    (when range
2200                                      (prin1 symbol)
2201                                      (princ " ")
2202                                      (princ (car range))
2203                                      (princ " ")
2204                                      (princ (cdr range))
2205                                      (princ "\n"))))))
2206                         my-obarray))))))))
2207
2208 (defun gnus-agent-get-local (group &optional gmane method)
2209   (let* ((gmane (or gmane (gnus-group-real-name group)))
2210          (gnus-command-method (or method (gnus-find-method-for-group group)))
2211          (local (gnus-agent-load-local))
2212          (symb (intern gmane local))
2213          (minmax (and (boundp symb) (symbol-value symb))))
2214     (unless minmax
2215       ;; Bind these so that gnus-agent-load-alist doesn't change the
2216       ;; current alist (i.e. gnus-agent-article-alist)
2217       (let* ((gnus-agent-article-alist gnus-agent-article-alist)
2218              (gnus-agent-file-loading-cache gnus-agent-file-loading-cache)
2219              (alist (gnus-agent-load-alist group)))
2220         (when alist
2221           (setq minmax
2222                 (cons (caar alist)
2223                       (caar (last alist))))
2224           (gnus-agent-set-local group (car minmax) (cdr minmax)
2225                                 gmane gnus-command-method local))))
2226     minmax))
2227
2228 (defun gnus-agent-set-local (group min max &optional gmane method local)
2229   (let* ((gmane (or gmane (gnus-group-real-name group)))
2230          (gnus-command-method (or method (gnus-find-method-for-group group)))
2231          (local (or local (gnus-agent-load-local)))
2232          (symb (intern gmane local))
2233          (minmax (and (boundp symb) (symbol-value symb))))
2234
2235     (if (cond ((and minmax
2236                     (or (not (eq min (car minmax)))
2237                         (not (eq max (cdr minmax)))))
2238                (setcar minmax min)
2239                (setcdr minmax max)
2240                t)
2241               (minmax
2242                nil)
2243               ((and min max)
2244                (set symb (cons min max))
2245                t)
2246               (t
2247                (unintern symb local)))
2248         (set (intern "+dirty" local) t))))
2249
2250 (defun gnus-agent-article-name (article group)
2251   (expand-file-name article
2252                     (file-name-as-directory
2253                      (gnus-agent-group-pathname group))))
2254
2255 (defun gnus-agent-batch-confirmation (msg)
2256   "Show error message and return t."
2257   (gnus-message 1 msg)
2258   t)
2259
2260 ;;;###autoload
2261 (defun gnus-agent-batch-fetch ()
2262   "Start Gnus and fetch session."
2263   (interactive)
2264   (gnus)
2265   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
2266     (gnus-agent-fetch-session))
2267   (gnus-group-exit))
2268
2269 (defun gnus-agent-fetch-session ()
2270   "Fetch all articles and headers that are eligible for fetching."
2271   (interactive)
2272   (unless gnus-agent-covered-methods
2273     (error "No servers are covered by the Gnus agent"))
2274   (unless gnus-plugged
2275     (error "Can't fetch articles while Gnus is unplugged"))
2276   (let ((methods (gnus-agent-covered-methods))
2277         groups group gnus-command-method)
2278     (save-excursion
2279       (while methods
2280         (setq gnus-command-method (car methods))
2281         (when (and (or (gnus-server-opened gnus-command-method)
2282                        (gnus-open-server gnus-command-method))
2283                    (gnus-online gnus-command-method))
2284           (setq groups (gnus-groups-from-server (car methods)))
2285           (gnus-agent-with-fetch
2286             (while (setq group (pop groups))
2287               (when (<= (gnus-group-level group)
2288                         gnus-agent-handle-level)
2289                 (if (or debug-on-error debug-on-quit)
2290                     (gnus-agent-fetch-group-1
2291                      group gnus-command-method)
2292                   (condition-case err
2293                       (gnus-agent-fetch-group-1
2294                        group gnus-command-method)
2295                     (error
2296                      (unless (funcall gnus-agent-confirmation-function
2297                                       (format "Error %s while fetching session.  Should gnus continue? "
2298                                               (error-message-string err)))
2299                        (error "Cannot fetch articles into the Gnus agent")))
2300                     (quit
2301                      (gnus-agent-regenerate-group group)
2302                      (unless (funcall gnus-agent-confirmation-function
2303                                       (format
2304                                        "%s while fetching session.  Should gnus continue? "
2305                                        (error-message-string err)))
2306                        (signal 'quit
2307                                "Cannot fetch articles into the Gnus agent")))))))))
2308         (setq methods (cdr methods)))
2309       (gnus-run-hooks 'gnus-agent-fetched-hook)
2310       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
2311
2312 (defun gnus-agent-fetch-group-1 (group method)
2313   "Fetch GROUP."
2314   (let ((gnus-command-method method)
2315         (gnus-newsgroup-name group)
2316         (gnus-newsgroup-dependencies gnus-newsgroup-dependencies)
2317         (gnus-newsgroup-headers gnus-newsgroup-headers)
2318         (gnus-newsgroup-scored gnus-newsgroup-scored)
2319         (gnus-use-cache gnus-use-cache)
2320         (gnus-summary-expunge-below gnus-summary-expunge-below)
2321         (gnus-summary-mark-below gnus-summary-mark-below)
2322         (gnus-orphan-score gnus-orphan-score)
2323         ;; Maybe some other gnus-summary local variables should also
2324         ;; be put here.
2325
2326         gnus-headers
2327         gnus-score
2328         articles arts
2329         category predicate info marks score-param
2330         )
2331     (unless (gnus-check-group group)
2332       (error "Can't open server for %s" group))
2333
2334     ;; Fetch headers.
2335     (when (or gnus-newsgroup-active
2336               (gnus-active group)
2337               (gnus-activate-group group))
2338       (let ((marked-articles gnus-newsgroup-downloadable))
2339         ;; Identify the articles marked for download
2340         (unless gnus-newsgroup-active
2341           ;; The variable gnus-newsgroup-active was selected as I need
2342           ;; a gnus-summary local variable that is NOT bound to any
2343           ;; value (its global value should default to nil).
2344           (dolist (mark gnus-agent-download-marks)
2345             (let ((arts (cdr (assq mark (gnus-info-marks
2346                                          (setq info (gnus-get-info group)))))))
2347               (when arts
2348                 (setq marked-articles (nconc (gnus-uncompress-range arts)
2349                                              marked-articles))
2350                 ))))
2351         (setq marked-articles (sort marked-articles '<))
2352
2353         ;; Fetch any new articles from the server
2354         (setq articles (gnus-agent-fetch-headers group))
2355
2356         ;; Merge new articles with marked
2357         (setq articles (sort (append marked-articles articles) '<))
2358
2359         (when articles
2360           ;; Parse them and see which articles we want to fetch.
2361           (setq gnus-newsgroup-dependencies
2362                 (or gnus-newsgroup-dependencies
2363                     (make-vector (length articles) 0)))
2364           (setq gnus-newsgroup-headers
2365                 (or gnus-newsgroup-headers
2366                     (gnus-get-newsgroup-headers-xover articles nil nil
2367                                                       group)))
2368           ;; `gnus-agent-overview-buffer' may be killed for
2369           ;; timeout reason.  If so, recreate it.
2370           (gnus-agent-create-buffer)
2371
2372           ;; Figure out how to select articles in this group
2373           (setq category (gnus-group-category group))
2374
2375           (setq predicate
2376                 (gnus-get-predicate
2377                  (gnus-agent-find-parameter group 'agent-predicate)))
2378
2379           ;; If the selection predicate requires scoring, score each header
2380           (unless (memq predicate '(gnus-agent-true gnus-agent-false))
2381             (let ((score-param
2382                    (gnus-agent-find-parameter group 'agent-score-file)))
2383               ;; Translate score-param into real one
2384               (cond
2385                ((not score-param))
2386                ((eq score-param 'file)
2387                 (setq score-param (gnus-all-score-files group)))
2388                ((stringp (car score-param)))
2389                (t
2390                 (setq score-param (list (list score-param)))))
2391               (when score-param
2392                 (gnus-score-headers score-param))))
2393
2394           (unless (and (eq predicate 'gnus-agent-false)
2395                        (not marked-articles))
2396             (let ((arts (list nil)))
2397               (let ((arts-tail arts)
2398                     (alist (gnus-agent-load-alist group))
2399                     (marked-articles marked-articles)
2400                     (gnus-newsgroup-headers gnus-newsgroup-headers))
2401                 (while (setq gnus-headers (pop gnus-newsgroup-headers))
2402                   (let ((num (mail-header-number gnus-headers)))
2403                     ;; Determine if this article is already in the cache
2404                     (while (and alist
2405                                 (> num (caar alist)))
2406                       (setq alist (cdr alist)))
2407
2408                     (unless (and (eq num (caar alist))
2409                                  (cdar alist))
2410
2411                       ;; Determine if this article was marked for download.
2412                       (while (and marked-articles
2413                                   (> num (car marked-articles)))
2414                         (setq marked-articles
2415                               (cdr marked-articles)))
2416
2417                       ;; When this article is marked, or selected by the
2418                       ;; predicate, add it to the download list
2419                       (when (or (eq num (car marked-articles))
2420                                 (let ((gnus-score
2421                                        (or (cdr
2422                                             (assq num gnus-newsgroup-scored))
2423                                            gnus-summary-default-score))
2424                                       (gnus-agent-long-article
2425                                        (gnus-agent-find-parameter
2426                                         group 'agent-long-article))
2427                                       (gnus-agent-short-article
2428                                        (gnus-agent-find-parameter
2429                                         group 'agent-short-article))
2430                                       (gnus-agent-low-score
2431                                        (gnus-agent-find-parameter
2432                                         group 'agent-low-score))
2433                                       (gnus-agent-high-score
2434                                        (gnus-agent-find-parameter
2435                                         group 'agent-high-score))
2436                                       (gnus-agent-expire-days
2437                                        (gnus-agent-find-parameter
2438                                         group 'agent-days-until-old)))
2439                                   (funcall predicate)))
2440                         (gnus-agent-append-to-list arts-tail num))))))
2441
2442               (let (fetched-articles)
2443                 ;; Fetch all selected articles
2444                 (setq gnus-newsgroup-undownloaded
2445                       (gnus-sorted-ndifference
2446                        gnus-newsgroup-undownloaded
2447                        (setq fetched-articles
2448                              (if (cdr arts)
2449                                  (gnus-agent-fetch-articles group (cdr arts))
2450                                nil))))
2451
2452                 (let ((unfetched-articles
2453                        (gnus-sorted-ndifference (cdr arts) fetched-articles)))
2454                   (if gnus-newsgroup-active
2455                       ;; Update the summary buffer
2456                       (progn
2457                         (dolist (article marked-articles)
2458                           (gnus-summary-set-agent-mark article t))
2459                         (dolist (article fetched-articles)
2460                           (when gnus-agent-mark-unread-after-downloaded
2461                             (setq gnus-newsgroup-downloadable
2462                                   (delq article gnus-newsgroup-downloadable))
2463                             (gnus-summary-mark-article
2464                              article gnus-unread-mark))
2465                           (when (gnus-summary-goto-subject article nil t)
2466                             (gnus-summary-update-download-mark article)))
2467                         (dolist (article unfetched-articles)
2468                           (gnus-summary-mark-article
2469                            article gnus-canceled-mark)))
2470
2471                     ;; Update the group buffer.
2472
2473                     ;; When some, or all, of the marked articles came
2474                     ;; from the download mark.  Remove that mark.  I
2475                     ;; didn't do this earlier as I only want to remove
2476                     ;; the marks after the fetch is completed.
2477
2478                     (dolist (mark gnus-agent-download-marks)
2479                       (when (eq mark 'download)
2480                         (let ((marked-arts
2481                                (assq mark (gnus-info-marks
2482                                            (setq info (gnus-get-info group))))))
2483                           (when (cdr marked-arts)
2484                             (setq marks
2485                                   (delq marked-arts (gnus-info-marks info)))
2486                             (gnus-info-set-marks info marks)))))
2487                     (let ((read (gnus-info-read
2488                                  (or info (setq info (gnus-get-info group))))))
2489                       (gnus-info-set-read
2490                        info (gnus-add-to-range read unfetched-articles)))
2491
2492                     (gnus-group-update-group group t)
2493                     (sit-for 0)
2494
2495                     (gnus-dribble-enter
2496                      (concat "(gnus-group-set-info '"
2497                              (gnus-prin1-to-string info)
2498                              ")"))))))))))))
2499
2500 ;;;
2501 ;;; Agent Category Mode
2502 ;;;
2503
2504 (defvar gnus-category-mode-hook nil
2505   "Hook run in `gnus-category-mode' buffers.")
2506
2507 (defvar gnus-category-line-format "     %(%20c%): %g\n"
2508   "Format of category lines.
2509
2510 Valid specifiers include:
2511 %c  Topic name (string)
2512 %g  The number of groups in the topic (integer)
2513
2514 General format specifiers can also be used.  See Info node
2515 `(gnus)Formatting Variables'.")
2516
2517 (defvar gnus-category-mode-line-format "Gnus: %%b"
2518   "The format specification for the category mode line.")
2519
2520 (defvar gnus-agent-predicate 'false
2521   "The selection predicate used when no other source is available.")
2522
2523 (defvar gnus-agent-short-article 100
2524   "Articles that have fewer lines than this are short.")
2525
2526 (defvar gnus-agent-long-article 200
2527   "Articles that have more lines than this are long.")
2528
2529 (defvar gnus-agent-low-score 0
2530   "Articles that have a score lower than this have a low score.")
2531
2532 (defvar gnus-agent-high-score 0
2533   "Articles that have a score higher than this have a high score.")
2534
2535
2536 ;;; Internal variables.
2537
2538 (defvar gnus-category-buffer "*Agent Category*")
2539
2540 (defvar gnus-category-line-format-alist
2541   `((?c gnus-tmp-name ?s)
2542     (?g gnus-tmp-groups ?d)))
2543
2544 (defvar gnus-category-mode-line-format-alist
2545   `((?u user-defined ?s)))
2546
2547 (defvar gnus-category-line-format-spec nil)
2548 (defvar gnus-category-mode-line-format-spec nil)
2549
2550 (defvar gnus-category-mode-map nil)
2551 (put 'gnus-category-mode 'mode-class 'special)
2552
2553 (unless gnus-category-mode-map
2554   (setq gnus-category-mode-map (make-sparse-keymap))
2555   (suppress-keymap gnus-category-mode-map)
2556
2557   (gnus-define-keys gnus-category-mode-map
2558     "q" gnus-category-exit
2559     "k" gnus-category-kill
2560     "c" gnus-category-copy
2561     "a" gnus-category-add
2562     "e" gnus-agent-customize-category
2563     "p" gnus-category-edit-predicate
2564     "g" gnus-category-edit-groups
2565     "s" gnus-category-edit-score
2566     "l" gnus-category-list
2567
2568     "\C-c\C-i" gnus-info-find-node
2569     "\C-c\C-b" gnus-bug))
2570
2571 (defvar gnus-category-menu-hook nil
2572   "*Hook run after the creation of the menu.")
2573
2574 (defun gnus-category-make-menu-bar ()
2575   (gnus-turn-off-edit-menu 'category)
2576   (unless (boundp 'gnus-category-menu)
2577     (easy-menu-define
2578      gnus-category-menu gnus-category-mode-map ""
2579      '("Categories"
2580        ["Add" gnus-category-add t]
2581        ["Kill" gnus-category-kill t]
2582        ["Copy" gnus-category-copy t]
2583        ["Edit category" gnus-agent-customize-category t]
2584        ["Edit predicate" gnus-category-edit-predicate t]
2585        ["Edit score" gnus-category-edit-score t]
2586        ["Edit groups" gnus-category-edit-groups t]
2587        ["Exit" gnus-category-exit t]))
2588
2589     (gnus-run-hooks 'gnus-category-menu-hook)))
2590
2591 (defun gnus-category-mode ()
2592   "Major mode for listing and editing agent categories.
2593
2594 All normal editing commands are switched off.
2595 \\<gnus-category-mode-map>
2596 For more in-depth information on this mode, read the manual
2597 \(`\\[gnus-info-find-node]').
2598
2599 The following commands are available:
2600
2601 \\{gnus-category-mode-map}"
2602   (interactive)
2603   (when (gnus-visual-p 'category-menu 'menu)
2604     (gnus-category-make-menu-bar))
2605   (kill-all-local-variables)
2606   (gnus-simplify-mode-line)
2607   (setq major-mode 'gnus-category-mode)
2608   (setq mode-name "Category")
2609   (gnus-set-default-directory)
2610   (setq mode-line-process nil)
2611   (use-local-map gnus-category-mode-map)
2612   (buffer-disable-undo)
2613   (setq truncate-lines t)
2614   (setq buffer-read-only t)
2615   (gnus-run-mode-hooks 'gnus-category-mode-hook))
2616
2617 (defalias 'gnus-category-position-point 'gnus-goto-colon)
2618
2619 (defun gnus-category-insert-line (category)
2620   (let* ((gnus-tmp-name (format "%s" (car category)))
2621          (gnus-tmp-groups (length (gnus-agent-cat-groups category))))
2622     (beginning-of-line)
2623     (gnus-add-text-properties
2624      (point)
2625      (prog1 (1+ (point))
2626        ;; Insert the text.
2627        (eval gnus-category-line-format-spec))
2628      (list 'gnus-category gnus-tmp-name))))
2629
2630 (defun gnus-enter-category-buffer ()
2631   "Go to the Category buffer."
2632   (interactive)
2633   (gnus-category-setup-buffer)
2634   (gnus-configure-windows 'category)
2635   (gnus-category-prepare))
2636
2637 (defun gnus-category-setup-buffer ()
2638   (unless (get-buffer gnus-category-buffer)
2639     (save-excursion
2640       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
2641       (gnus-category-mode))))
2642
2643 (defun gnus-category-prepare ()
2644   (gnus-set-format 'category-mode)
2645   (gnus-set-format 'category t)
2646   (let ((alist gnus-category-alist)
2647         (buffer-read-only nil))
2648     (erase-buffer)
2649     (while alist
2650       (gnus-category-insert-line (pop alist)))
2651     (goto-char (point-min))
2652     (gnus-category-position-point)))
2653
2654 (defun gnus-category-name ()
2655   (or (intern (get-text-property (point-at-bol) 'gnus-category))
2656       (error "No category on the current line")))
2657
2658 (defun gnus-category-read ()
2659   "Read the category alist."
2660   (setq gnus-category-alist
2661         (or
2662          (with-temp-buffer
2663            (ignore-errors
2664             (nnheader-insert-file-contents (nnheader-concat gnus-agent-directory "lib/categories"))
2665             (goto-char (point-min))
2666             ;; This code isn't temp, it will be needed so long as
2667             ;; anyone may be migrating from an older version.
2668
2669             ;; Once we're certain that people will not revert to an
2670             ;; earlier version, we can take out the old-list code in
2671             ;; gnus-category-write.
2672             (let* ((old-list (read (current-buffer)))
2673                    (new-list (ignore-errors (read (current-buffer)))))
2674               (if new-list
2675                   new-list
2676                 ;; Convert from a positional list to an alist.
2677                 (mapcar
2678                  (lambda (c)
2679                    (setcdr c
2680                            (delq nil
2681                                  (gnus-mapcar
2682                                   (lambda (valu symb)
2683                                     (if valu
2684                                         (cons symb valu)))
2685                                   (cdr c)
2686                                   '(agent-predicate agent-score-file agent-groups))))
2687                    c)
2688                  old-list)))))
2689          (list (gnus-agent-cat-make 'default 'short)))))
2690
2691 (defun gnus-category-write ()
2692   "Write the category alist."
2693   (setq gnus-category-predicate-cache nil
2694         gnus-category-group-cache nil)
2695   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
2696   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
2697     ;; This prin1 is temporary.  It exists so that people can revert
2698     ;; to an earlier version of gnus-agent.
2699     (prin1 (mapcar (lambda (c)
2700               (list (car c)
2701                     (cdr (assoc 'agent-predicate c))
2702                     (cdr (assoc 'agent-score-file c))
2703                     (cdr (assoc 'agent-groups c))))
2704                    gnus-category-alist)
2705            (current-buffer))
2706     (newline)
2707     (prin1 gnus-category-alist (current-buffer))))
2708
2709 (defun gnus-category-edit-predicate (category)
2710   "Edit the predicate for CATEGORY."
2711   (interactive (list (gnus-category-name)))
2712   (let ((info (assq category gnus-category-alist)))
2713     (gnus-edit-form
2714      (gnus-agent-cat-predicate info)
2715      (format "Editing the select predicate for category %s" category)
2716      `(lambda (predicate)
2717         ;; Avoid run-time execution of setf form
2718         ;; (setf (gnus-agent-cat-predicate (assq ',category gnus-category-alist))
2719         ;;       predicate)
2720         ;; use its expansion instead:
2721         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2722                                      'agent-predicate predicate)
2723
2724         (gnus-category-write)
2725         (gnus-category-list)))))
2726
2727 (defun gnus-category-edit-score (category)
2728   "Edit the score expression for CATEGORY."
2729   (interactive (list (gnus-category-name)))
2730   (let ((info (assq category gnus-category-alist)))
2731     (gnus-edit-form
2732      (gnus-agent-cat-score-file info)
2733      (format "Editing the score expression for category %s" category)
2734      `(lambda (score-file)
2735         ;; Avoid run-time execution of setf form
2736         ;; (setf (gnus-agent-cat-score-file (assq ',category gnus-category-alist))
2737         ;;       score-file)
2738         ;; use its expansion instead:
2739         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2740                                      'agent-score-file score-file)
2741
2742         (gnus-category-write)
2743         (gnus-category-list)))))
2744
2745 (defun gnus-category-edit-groups (category)
2746   "Edit the group list for CATEGORY."
2747   (interactive (list (gnus-category-name)))
2748   (let ((info (assq category gnus-category-alist)))
2749     (gnus-edit-form
2750      (gnus-agent-cat-groups info)
2751      (format "Editing the group list for category %s" category)
2752      `(lambda (groups)
2753         ;; Avoid run-time execution of setf form
2754         ;; (setf (gnus-agent-cat-groups (assq ',category gnus-category-alist))
2755         ;;       groups)
2756         ;; use its expansion instead:
2757         (gnus-agent-set-cat-groups (assq ',category gnus-category-alist)
2758                                    groups)
2759
2760         (gnus-category-write)
2761         (gnus-category-list)))))
2762
2763 (defun gnus-category-kill (category)
2764   "Kill the current category."
2765   (interactive (list (gnus-category-name)))
2766   (let ((info (assq category gnus-category-alist))
2767         (buffer-read-only nil))
2768     (gnus-delete-line)
2769     (setq gnus-category-alist (delq info gnus-category-alist))
2770     (gnus-category-write)))
2771
2772 (defun gnus-category-copy (category to)
2773   "Copy the current category."
2774   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
2775   (let ((info (assq category gnus-category-alist)))
2776     (push (let ((newcat (gnus-copy-sequence info)))
2777             (setf (gnus-agent-cat-name newcat) to)
2778             (setf (gnus-agent-cat-groups newcat) nil)
2779             newcat)
2780           gnus-category-alist)
2781     (gnus-category-write)
2782     (gnus-category-list)))
2783
2784 (defun gnus-category-add (category)
2785   "Create a new category."
2786   (interactive "SCategory name: ")
2787   (when (assq category gnus-category-alist)
2788     (error "Category %s already exists" category))
2789   (push (gnus-agent-cat-make category)
2790         gnus-category-alist)
2791   (gnus-category-write)
2792   (gnus-category-list))
2793
2794 (defun gnus-category-list ()
2795   "List all categories."
2796   (interactive)
2797   (gnus-category-prepare))
2798
2799 (defun gnus-category-exit ()
2800   "Return to the group buffer."
2801   (interactive)
2802   (kill-buffer (current-buffer))
2803   (gnus-configure-windows 'group t))
2804
2805 ;; To avoid having 8-bit characters in the source file.
2806 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
2807
2808 (defvar gnus-category-predicate-alist
2809   '((spam . gnus-agent-spam-p)
2810     (short . gnus-agent-short-p)
2811     (long . gnus-agent-long-p)
2812     (low . gnus-agent-low-scored-p)
2813     (high . gnus-agent-high-scored-p)
2814     (read . gnus-agent-read-p)
2815     (true . gnus-agent-true)
2816     (false . gnus-agent-false))
2817   "Mapping from short score predicate symbols to predicate functions.")
2818
2819 (defun gnus-agent-spam-p ()
2820   "Say whether an article is spam or not."
2821   (unless gnus-agent-spam-hashtb
2822     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
2823   (if (not (equal (mail-header-references gnus-headers) ""))
2824       nil
2825     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
2826       (prog1
2827           (gnus-gethash string gnus-agent-spam-hashtb)
2828         (gnus-sethash string t gnus-agent-spam-hashtb)))))
2829
2830 (defun gnus-agent-short-p ()
2831   "Say whether an article is short or not."
2832   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
2833
2834 (defun gnus-agent-long-p ()
2835   "Say whether an article is long or not."
2836   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
2837
2838 (defun gnus-agent-low-scored-p ()
2839   "Say whether an article has a low score or not."
2840   (< gnus-score gnus-agent-low-score))
2841
2842 (defun gnus-agent-high-scored-p ()
2843   "Say whether an article has a high score or not."
2844   (> gnus-score gnus-agent-high-score))
2845
2846 (defun gnus-agent-read-p ()
2847   "Say whether an article is read or not."
2848   (gnus-member-of-range (mail-header-number gnus-headers)
2849                         (gnus-info-read (gnus-get-info gnus-newsgroup-name))))
2850
2851 (defun gnus-category-make-function (predicate)
2852   "Make a function from PREDICATE."
2853   (let ((func (gnus-category-make-function-1 predicate)))
2854     (if (and (= (length func) 1)
2855              (symbolp (car func)))
2856         (car func)
2857       (gnus-byte-compile `(lambda () ,func)))))
2858
2859 (defun gnus-agent-true ()
2860   "Return t."
2861   t)
2862
2863 (defun gnus-agent-false ()
2864   "Return nil."
2865   nil)
2866
2867 (defun gnus-category-make-function-1 (predicate)
2868   "Make a function from PREDICATE."
2869   (cond
2870    ;; Functions are just returned as is.
2871    ((or (symbolp predicate)
2872         (functionp predicate))
2873     `(,(or (cdr (assq predicate gnus-category-predicate-alist))
2874            predicate)))
2875    ;; More complex predicate.
2876    ((consp predicate)
2877     `(,(cond
2878         ((memq (car predicate) '(& and))
2879          'and)
2880         ((memq (car predicate) '(| or))
2881          'or)
2882         ((memq (car predicate) gnus-category-not)
2883          'not))
2884       ,@(mapcar 'gnus-category-make-function-1 (cdr predicate))))
2885    (t
2886     (error "Unknown predicate type: %s" predicate))))
2887
2888 (defun gnus-get-predicate (predicate)
2889   "Return the function implementing PREDICATE."
2890   (or (cdr (assoc predicate gnus-category-predicate-cache))
2891       (let ((func (gnus-category-make-function predicate)))
2892         (setq gnus-category-predicate-cache
2893               (nconc gnus-category-predicate-cache
2894                      (list (cons predicate func))))
2895         func)))
2896
2897 (defun gnus-predicate-implies-unread (predicate)
2898   "Say whether PREDICATE implies unread articles only.
2899 It is okay to miss some cases, but there must be no false positives.
2900 That is, if this predicate returns true, then indeed the predicate must
2901 return only unread articles."
2902   (eq t (gnus-function-implies-unread-1
2903          (gnus-category-make-function-1 predicate))))
2904
2905 (defun gnus-function-implies-unread-1 (function)
2906   "Recursively evaluate a predicate function to determine whether it can select
2907 any read articles.  Returns t if the function is known to never
2908 return read articles, nil when it is known to always return read
2909 articles, and t_nil when the function may return both read and unread
2910 articles."
2911   (let ((func (car function))
2912         (args (mapcar 'gnus-function-implies-unread-1 (cdr function))))
2913     (cond ((eq func 'and)
2914            (cond ((memq t args) ; if any argument returns only unread articles
2915                   ;; then that argument constrains the result to only unread articles.
2916                   t)
2917                  ((memq 't_nil args) ; if any argument is indeterminate
2918                   ;; then the result is indeterminate
2919                   't_nil)))
2920           ((eq func 'or)
2921            (cond ((memq nil args) ; if any argument returns read articles
2922                   ;; then that argument ensures that the results includes read articles.
2923                   nil)
2924                  ((memq 't_nil args) ; if any argument is indeterminate
2925                   ;; then that argument ensures that the results are indeterminate
2926                   't_nil)
2927                  (t ; if all arguments return only unread articles
2928                   ;; then the result returns only unread articles
2929                   t)))
2930           ((eq func 'not)
2931            (cond ((eq (car args) 't_nil) ; if the argument is indeterminate
2932                   ; then the result is indeterminate
2933                   (car args))
2934                  (t ; otherwise
2935                   ; toggle the result to be the opposite of the argument
2936                   (not (car args)))))
2937           ((eq func 'gnus-agent-read-p)
2938            nil) ; The read predicate NEVER returns unread articles
2939           ((eq func 'gnus-agent-false)
2940            t) ; The false predicate returns t as the empty set excludes all read articles
2941           ((eq func 'gnus-agent-true)
2942            nil) ; The true predicate ALWAYS returns read articles
2943           ((catch 'found-match
2944              (let ((alist gnus-category-predicate-alist))
2945                (while alist
2946                  (if (eq func (cdar alist))
2947                      (throw 'found-match t)
2948                    (setq alist (cdr alist))))))
2949            't_nil) ; All other predicates return read and unread articles
2950           (t
2951            (error "Unknown predicate function: %s" function)))))
2952
2953 (defun gnus-group-category (group)
2954   "Return the category GROUP belongs to."
2955   (unless gnus-category-group-cache
2956     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
2957     (let ((cs gnus-category-alist)
2958           groups cat)
2959       (while (setq cat (pop cs))
2960         (setq groups (gnus-agent-cat-groups cat))
2961         (while groups
2962           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
2963   (or (gnus-gethash group gnus-category-group-cache)
2964       (assq 'default gnus-category-alist)))
2965
2966 (defun gnus-agent-expire-group (group &optional articles force)
2967   "Expire all old articles in GROUP.
2968 If you want to force expiring of certain articles, this function can
2969 take ARTICLES, and FORCE parameters as well.
2970
2971 The articles on which the expiration process runs are selected as follows:
2972   if ARTICLES is null, all read and unmarked articles.
2973   if ARTICLES is t, all articles.
2974   if ARTICLES is a list, just those articles.
2975 FORCE is equivalent to setting the expiration predicates to true."
2976   (interactive
2977    (list (let ((def (or (gnus-group-group-name)
2978                         gnus-newsgroup-name)))
2979            (let ((select (read-string (if def
2980                                           (concat "Group Name ("
2981                                                   def "): ")
2982                                         "Group Name: "))))
2983              (if (and (equal "" select)
2984                       def)
2985                  def
2986                select)))))
2987
2988   (if (not group)
2989       (gnus-agent-expire articles group force)
2990     (let ( ;; Bind gnus-agent-expire-stats to enable tracking of
2991           ;; expiration statistics of this single group
2992           (gnus-agent-expire-stats (list 0 0 0.0)))
2993       (if (or (not (eq articles t))
2994               (yes-or-no-p
2995                (concat "Are you sure that you want to "
2996                        "expire all articles in " group "? ")))
2997           (let ((gnus-command-method (gnus-find-method-for-group group))
2998                 (overview (gnus-get-buffer-create " *expire overview*"))
2999                 orig)
3000             (unwind-protect
3001                 (let ((active-file (gnus-agent-lib-file "active")))
3002                   (when (file-exists-p active-file)
3003                     (with-temp-buffer
3004                       (nnheader-insert-file-contents active-file)
3005                       (gnus-active-to-gnus-format
3006                        gnus-command-method
3007                        (setq orig (gnus-make-hashtable
3008                                    (count-lines (point-min) (point-max))))))
3009                     (save-excursion
3010                       (gnus-agent-expire-group-1
3011                        group overview (gnus-gethash-safe group orig)
3012                        articles force))))
3013               (kill-buffer overview))))
3014       (gnus-message 4 (gnus-agent-expire-done-message)))))
3015
3016 (defun gnus-agent-expire-group-1 (group overview active articles force)
3017   ;; Internal function - requires caller to have set
3018   ;; gnus-command-method, initialized overview buffer, and to have
3019   ;; provided a non-nil active
3020
3021   (let ((dir (gnus-agent-group-pathname group)))
3022     (gnus-agent-with-refreshed-group
3023      group
3024      (when (boundp 'gnus-agent-expire-current-dirs)
3025        (set 'gnus-agent-expire-current-dirs
3026             (cons dir
3027                   (symbol-value 'gnus-agent-expire-current-dirs))))
3028
3029      (if (and (not force)
3030               (eq 'DISABLE (gnus-agent-find-parameter group
3031                                                       'agent-enable-expiration)))
3032          (gnus-message 5 "Expiry skipping over %s" group)
3033        (gnus-message 5 "Expiring articles in %s" group)
3034        (gnus-agent-load-alist group)
3035        (let* ((bytes-freed 0)
3036               (size-files-deleted 0.0)
3037               (files-deleted 0)
3038               (nov-entries-deleted 0)
3039               (info (gnus-get-info group))
3040               (alist gnus-agent-article-alist)
3041               (day (- (time-to-days (current-time))
3042                       (gnus-agent-find-parameter group 'agent-days-until-old)))
3043               (specials (if (and alist
3044                                  (not force))
3045                             ;; This could be a bit of a problem.  I need to
3046                             ;; keep the last article to avoid refetching
3047                             ;; headers when using nntp in the backend.  At
3048                             ;; the same time, if someone uses a backend
3049                             ;; that supports article moving then I may have
3050                             ;; to remove the last article to complete the
3051                             ;; move.  Right now, I'm going to assume that
3052                             ;; FORCE overrides specials.
3053                             (list (caar (last alist)))))
3054               (unreads ;; Articles that are excluded from the
3055                ;; expiration process
3056                (cond (gnus-agent-expire-all
3057                       ;; All articles are marked read by global decree
3058                       nil)
3059                      ((eq articles t)
3060                       ;; All articles are marked read by function
3061                       ;; parameter
3062                       nil)
3063                      ((not articles)
3064                       ;; Unread articles are marked protected from
3065                       ;; expiration Don't call
3066                       ;; gnus-list-of-unread-articles as it returns
3067                       ;; articles that have not been fetched into the
3068                       ;; agent.
3069                       (ignore-errors
3070                         (gnus-agent-unread-articles group)))
3071                      (t
3072                       ;; All articles EXCEPT those named by the caller
3073                       ;; are protected from expiration
3074                       (gnus-sorted-difference
3075                        (gnus-uncompress-range
3076                         (cons (caar alist)
3077                               (caar (last alist))))
3078                        (sort articles '<)))))
3079               (marked ;; More articles that are excluded from the
3080                ;; expiration process
3081                (cond (gnus-agent-expire-all
3082                       ;; All articles are unmarked by global decree
3083                       nil)
3084                      ((eq articles t)
3085                       ;; All articles are unmarked by function
3086                       ;; parameter
3087                       nil)
3088                      (articles
3089                       ;; All articles may as well be unmarked as the
3090                       ;; unreads list already names the articles we are
3091                       ;; going to keep
3092                       nil)
3093                      (t
3094                       ;; Ticked and/or dormant articles are excluded
3095                       ;; from expiration
3096                       (nconc
3097                        (gnus-uncompress-range
3098                         (cdr (assq 'tick (gnus-info-marks info))))
3099                        (gnus-uncompress-range
3100                         (cdr (assq 'dormant
3101                                    (gnus-info-marks info))))))))
3102               (nov-file (concat dir ".overview"))
3103               (cnt 0)
3104               (completed -1)
3105               dlist
3106               type)
3107
3108          ;; The normal article alist contains elements that look like
3109          ;; (article# .  fetch_date) I need to combine other
3110          ;; information with this list.  For example, a flag indicating
3111          ;; that a particular article MUST BE KEPT.  To do this, I'm
3112          ;; going to transform the elements to look like (article#
3113          ;; fetch_date keep_flag NOV_entry_position) Later, I'll reverse
3114          ;; the process to generate the expired article alist.
3115
3116          ;; Convert the alist elements to (article# fetch_date nil
3117          ;; nil).
3118          (setq dlist (mapcar (lambda (e)
3119                                (list (car e) (cdr e) nil nil)) alist))
3120
3121          ;; Convert the keep lists to elements that look like (article#
3122          ;; nil keep_flag nil) then append it to the expanded dlist
3123          ;; These statements are sorted by ascending precidence of the
3124          ;; keep_flag.
3125          (setq dlist (nconc dlist
3126                             (mapcar (lambda (e)
3127                                       (list e nil 'unread  nil))
3128                                     unreads)))
3129          (setq dlist (nconc dlist
3130                             (mapcar (lambda (e)
3131                                       (list e nil 'marked  nil))
3132                                     marked)))
3133          (setq dlist (nconc dlist
3134                             (mapcar (lambda (e)
3135                                       (list e nil 'special nil))
3136                                     specials)))
3137
3138          (set-buffer overview)
3139          (erase-buffer)
3140          (buffer-disable-undo)
3141          (when (file-exists-p nov-file)
3142            (gnus-message 7 "gnus-agent-expire: Loading overview...")
3143            (nnheader-insert-file-contents nov-file)
3144            (goto-char (point-min))
3145         
3146            (let (p)
3147              (while (< (setq p (point)) (point-max))
3148                (condition-case nil
3149                    ;; If I successfully read an integer (the plus zero
3150                    ;; ensures a numeric type), append the position
3151                    ;; to the list
3152                    (push (list (+ 0 (read (current-buffer))) nil nil
3153                                p)
3154                          dlist)
3155                  (error
3156                   (gnus-message 1 "gnus-agent-expire: read error \
3157 occurred when reading expression at %s in %s.  Skipping to next \
3158 line." (point) nov-file)))
3159                ;; Whether I succeeded, or failed, it doesn't matter.
3160                ;; Move to the next line then try again.
3161                (forward-line 1)))
3162
3163            (gnus-message
3164             7 "gnus-agent-expire: Loading overview... Done"))
3165          (set-buffer-modified-p nil)
3166
3167          ;; At this point, all of the information is in dlist.  The
3168          ;; only problem is that much of it is spread across multiple
3169          ;; entries.  Sort then MERGE!!
3170          (gnus-message 7 "gnus-agent-expire: Sorting entries... ")
3171          ;; If two entries have the same article-number then sort by
3172          ;; ascending keep_flag.
3173          (let ((special 0)
3174                (marked 1)
3175                (unread 2))
3176            (setq dlist
3177                  (sort dlist
3178                        (lambda (a b)
3179                          (cond ((< (nth 0 a) (nth 0 b))
3180                                 t)
3181                                ((> (nth 0 a) (nth 0 b))
3182                                 nil)
3183                                (t
3184                                 (let ((a (or (symbol-value (nth 2 a))
3185                                              3))
3186                                       (b (or (symbol-value (nth 2 b))
3187                                              3)))
3188                                   (<= a b))))))))
3189          (gnus-message 7 "gnus-agent-expire: Sorting entries... Done")
3190          (gnus-message 7 "gnus-agent-expire: Merging entries... ")
3191          (let ((dlist dlist))
3192            (while (cdr dlist)           ; I'm not at the end-of-list
3193              (if (eq (caar dlist) (caadr dlist))
3194                  (let ((first (cdr (car dlist)))
3195                        (secnd (cdr (cadr dlist))))
3196                    (setcar first (or (car first)
3197                                      (car secnd))) ; fetch_date
3198                    (setq first (cdr first)
3199                          secnd (cdr secnd))
3200                    (setcar first (or (car first)
3201                                      (car secnd))) ; Keep_flag
3202                    (setq first (cdr first)
3203                          secnd (cdr secnd))
3204                    (setcar first (or (car first)
3205                                      (car secnd))) ; NOV_entry_position
3206
3207                    (setcdr dlist (cddr dlist)))
3208                (setq dlist (cdr dlist)))))
3209
3210          ;; Check the order of the entry positions.  They should be in
3211          ;; ascending order.  If they aren't, the positions must be
3212          ;; converted to markers.
3213          (when (let ((dlist dlist)
3214                      (prev-pos -1)
3215                      pos)
3216                  (while dlist
3217                    (if (setq pos (nth 3 (pop dlist)))
3218                        (if (< pos prev-pos)
3219                            (throw 'sort-results 'unsorted)
3220                          (setq prev-pos pos)))))
3221            (gnus-message 7 "gnus-agent-expire: Unsorted overview; inserting markers to compensate.")
3222            (mapcar (lambda (entry)
3223                      (let ((pos (nth 3 entry)))
3224                        (if pos
3225                            (setf (nth 3 entry)
3226                                  (set-marker (make-marker)
3227                                              pos)))))
3228                    dlist))
3229
3230          (gnus-message 7 "gnus-agent-expire: Merging entries... Done")
3231
3232          (let* ((len (float (length dlist)))
3233                 (alist (list nil))
3234                 (tail-alist alist)
3235                 (position-offset 0)
3236                 )
3237
3238            (while dlist
3239              (let ((new-completed (truncate (* 100.0
3240                                                (/ (setq cnt (1+ cnt))
3241                                                   len))))
3242                    message-log-max)
3243                (when (> new-completed completed)
3244                  (setq completed new-completed)
3245                  (gnus-message 7 "%3d%% completed..."  completed)))
3246              (let* ((entry          (car dlist))
3247                     (article-number (nth 0 entry))
3248                     (fetch-date     (nth 1 entry))
3249                     (keep           (nth 2 entry))
3250                     (marker         (nth 3 entry)))
3251
3252                (cond
3253                 ;; Kept articles are unread, marked, or special.
3254                 (keep
3255                  (gnus-agent-message 10
3256                                      "gnus-agent-expire: %s:%d: Kept %s article%s."
3257                                      group article-number keep (if fetch-date " and file" ""))
3258                  (when fetch-date
3259                    (unless (file-exists-p
3260                             (concat dir (number-to-string
3261                                          article-number)))
3262                      (setf (nth 1 entry) nil)
3263                      (gnus-agent-message 3 "gnus-agent-expire cleared \
3264 download flag on %s:%d as the cached article file is missing."
3265                                          group (caar dlist)))
3266                    (unless marker
3267                      (gnus-message 1 "gnus-agent-expire detected a \
3268 missing NOV entry.  Run gnus-agent-regenerate-group to restore it.")))
3269                  (gnus-agent-append-to-list
3270                   tail-alist
3271                   (cons article-number fetch-date)))
3272
3273                 ;; The following articles are READ, UNMARKED, and
3274                 ;; ORDINARY.  See if they can be EXPIRED!!!
3275                 ((setq type
3276                        (cond
3277                         ((not (integerp fetch-date))
3278                          'read) ;; never fetched article (may expire
3279                         ;; right now)
3280                         ((not (file-exists-p
3281                                (concat dir (number-to-string
3282                                             article-number))))
3283                          (setf (nth 1 entry) nil)
3284                          'externally-expired) ;; Can't find the cached
3285                         ;; article.  Handle case
3286                         ;; as though this article
3287                         ;; was never fetched.
3288
3289                         ;; We now have the arrival day, so we see
3290                         ;; whether it's old enough to be expired.
3291                         ((< fetch-date day)
3292                          'expired)
3293                         (force
3294                          'forced)))
3295
3296                  ;; I found some reason to expire this entry.
3297
3298                  (let ((actions nil))
3299                    (when (memq type '(forced expired))
3300                      (ignore-errors     ; Just being paranoid.
3301                        (let* ((file-name (nnheader-concat dir (number-to-string
3302                                                                article-number)))
3303                               (size (float (nth 7 (file-attributes file-name)))))
3304                          (incf bytes-freed size)
3305                          (incf size-files-deleted size)
3306                          (incf files-deleted)
3307                          (delete-file file-name))
3308                        (push "expired cached article" actions))
3309                      (setf (nth 1 entry) nil)
3310                      )
3311
3312                    (when marker
3313                      (push "NOV entry removed" actions)
3314
3315                      (goto-char (if (markerp marker)
3316                                     marker
3317                                   (- marker position-offset)))
3318
3319                      (incf nov-entries-deleted)
3320
3321                      (let* ((from (point-at-bol))
3322                             (to (progn (forward-line 1) (point)))
3323                             (freed (- to from)))
3324                        (incf bytes-freed freed)
3325                        (incf position-offset freed)
3326                        (delete-region from to)))
3327
3328                    ;; If considering all articles is set, I can only
3329                    ;; expire article IDs that are no longer in the
3330                    ;; active range (That is, articles that preceed the
3331                    ;; first article in the new alist).
3332                    (if (and gnus-agent-consider-all-articles
3333                             (>= article-number (car active)))
3334                        ;; I have to keep this ID in the alist
3335                        (gnus-agent-append-to-list
3336                         tail-alist (cons article-number fetch-date))
3337                      (push (format "Removed %s article number from \
3338 article alist" type) actions))
3339
3340                    (when actions
3341                      (gnus-agent-message 8 "gnus-agent-expire: %s:%d: %s"
3342                                          group article-number
3343                                          (mapconcat 'identity actions ", ")))))
3344                 (t
3345                  (gnus-agent-message
3346                   10 "gnus-agent-expire: %s:%d: Article kept as \
3347 expiration tests failed." group article-number)
3348                  (gnus-agent-append-to-list
3349                   tail-alist (cons article-number fetch-date)))
3350                 )
3351
3352                ;; Remove markers as I intend to reuse this buffer again.
3353                (when (and marker
3354                           (markerp marker))
3355                  (set-marker marker nil))
3356
3357                (setq dlist (cdr dlist))))
3358
3359            (setq alist (cdr alist))
3360
3361            (let ((inhibit-quit t))
3362              (unless (equal alist gnus-agent-article-alist)
3363                (setq gnus-agent-article-alist alist)
3364                (gnus-agent-save-alist group))
3365
3366              (when (buffer-modified-p)
3367                (let ((coding-system-for-write
3368                       gnus-agent-file-coding-system))
3369                  (gnus-make-directory dir)
3370                  (write-region (point-min) (point-max) nov-file nil
3371                                'silent)
3372                  ;; clear the modified flag as that I'm not confused by
3373                  ;; its status on the next pass through this routine.
3374                  (set-buffer-modified-p nil)
3375                  (gnus-agent-update-view-total-fetched-for group t)))
3376
3377              (when (eq articles t)
3378                (gnus-summary-update-info))))
3379
3380          (when (boundp 'gnus-agent-expire-stats)
3381            (let ((stats (symbol-value 'gnus-agent-expire-stats)))
3382              (incf (nth 2 stats) bytes-freed)
3383              (incf (nth 1 stats) files-deleted)
3384              (incf (nth 0 stats) nov-entries-deleted)))
3385
3386          (gnus-agent-update-files-total-fetched-for group (- size-files-deleted)))))))
3387
3388 (defun gnus-agent-expire (&optional articles group force)
3389   "Expire all old articles.
3390 If you want to force expiring of certain articles, this function can
3391 take ARTICLES, GROUP and FORCE parameters as well.
3392
3393 The articles on which the expiration process runs are selected as follows:
3394   if ARTICLES is null, all read and unmarked articles.
3395   if ARTICLES is t, all articles.
3396   if ARTICLES is a list, just those articles.
3397 Setting GROUP will limit expiration to that group.
3398 FORCE is equivalent to setting the expiration predicates to true."
3399   (interactive)
3400
3401   (if group
3402       (gnus-agent-expire-group group articles force)
3403     (if (or (not (eq articles t))
3404             (yes-or-no-p "Are you sure that you want to expire all \
3405 articles in every agentized group? "))
3406         (let ((methods (gnus-agent-covered-methods))
3407               ;; Bind gnus-agent-expire-current-dirs to enable tracking
3408               ;; of agent directories.
3409               (gnus-agent-expire-current-dirs nil)
3410               ;; Bind gnus-agent-expire-stats to enable tracking of
3411               ;; expiration statistics across all groups
3412               (gnus-agent-expire-stats (list 0 0 0.0))
3413               gnus-command-method overview orig)
3414           (setq overview (gnus-get-buffer-create " *expire overview*"))
3415           (unwind-protect
3416               (while (setq gnus-command-method (pop methods))
3417                 (let ((active-file (gnus-agent-lib-file "active")))
3418                   (when (file-exists-p active-file)
3419                     (with-temp-buffer
3420                       (nnheader-insert-file-contents active-file)
3421                       (gnus-active-to-gnus-format
3422                        gnus-command-method
3423                        (setq orig (gnus-make-hashtable
3424                                    (count-lines (point-min) (point-max))))))
3425                     (dolist (expiring-group (gnus-groups-from-server
3426                                              gnus-command-method))
3427                       (let* ((active
3428                               (gnus-gethash-safe expiring-group orig)))
3429
3430                         (when active
3431                           (save-excursion
3432                             (gnus-agent-expire-group-1
3433                              expiring-group overview active articles force))))))))
3434             (kill-buffer overview))
3435           (gnus-agent-expire-unagentized-dirs)
3436           (gnus-message 4 (gnus-agent-expire-done-message))))))
3437
3438 (defun gnus-agent-expire-done-message ()
3439   (if (and (> gnus-verbose 4)
3440            (boundp 'gnus-agent-expire-stats))
3441       (let* ((stats (symbol-value 'gnus-agent-expire-stats))
3442              (size (nth 2 stats))
3443             (units '(B KB MB GB)))
3444         (while (and (> size 1024.0)
3445                     (cdr units))
3446           (setq size (/ size 1024.0)
3447                 units (cdr units)))
3448
3449         (format "Expiry recovered %d NOV entries, deleted %d files,\
3450  and freed %f %s."
3451                 (nth 0 stats)
3452                 (nth 1 stats)
3453                 size (car units)))
3454     "Expiry...done"))
3455
3456 (defun gnus-agent-expire-unagentized-dirs ()
3457   (when (and gnus-agent-expire-unagentized-dirs
3458              (boundp 'gnus-agent-expire-current-dirs))
3459     (let* ((keep (gnus-make-hashtable))
3460            ;; Formally bind gnus-agent-expire-current-dirs so that the
3461            ;; compiler will not complain about free references.
3462            (gnus-agent-expire-current-dirs
3463             (symbol-value 'gnus-agent-expire-current-dirs))
3464            dir)
3465
3466       (gnus-sethash gnus-agent-directory t keep)
3467       (while gnus-agent-expire-current-dirs
3468         (setq dir (pop gnus-agent-expire-current-dirs))
3469         (when (and (stringp dir)
3470                    (file-directory-p dir))
3471           (while (not (gnus-gethash dir keep))
3472             (gnus-sethash dir t keep)
3473             (setq dir (file-name-directory (directory-file-name dir))))))
3474
3475       (let* (to-remove
3476              checker
3477              (checker
3478               (function
3479                (lambda (d)
3480                  "Given a directory, check it and its subdirectories for
3481               membership in the keep hash.  If it isn't found, add
3482               it to to-remove."
3483                  (let ((files (directory-files d))
3484                        file)
3485                    (while (setq file (pop files))
3486                      (cond ((equal file ".") ; Ignore self
3487                             nil)
3488                            ((equal file "..") ; Ignore parent
3489                             nil)
3490                            ((equal file ".overview")
3491                             ;; Directory must contain .overview to be
3492                             ;; agent's cache of a group.
3493                             (let ((d (file-name-as-directory d))
3494                                   r)
3495                               ;; Search ancestor's for last directory NOT
3496                               ;; found in keep hash.
3497                               (while (not (gnus-gethash
3498                                            (setq d (file-name-directory d)) keep))
3499                                 (setq r d
3500                                       d (directory-file-name d)))
3501                               ;; if ANY ancestor was NOT in keep hash and
3502                               ;; it it's already in to-remove, add it to
3503                               ;; to-remove.
3504                               (if (and r
3505                                        (not (member r to-remove)))
3506                                   (push r to-remove))))
3507                            ((file-directory-p (setq file (nnheader-concat d file)))
3508                             (funcall checker file)))))))))
3509         (funcall checker (expand-file-name gnus-agent-directory))
3510
3511         (when (and to-remove
3512                    (or gnus-expert-user
3513                        (gnus-y-or-n-p
3514                         "gnus-agent-expire has identified local directories that are\
3515  not currently required by any agentized group.  Do you wish to consider\
3516  deleting them?")))
3517           (while to-remove
3518             (let ((dir (pop to-remove)))
3519               (if (gnus-y-or-n-p (format "Delete %s? " dir))
3520                   (let* (delete-recursive
3521                          (delete-recursive
3522                           (function
3523                            (lambda (f-or-d)
3524                              (ignore-errors
3525                                (if (file-directory-p f-or-d)
3526                                    (condition-case nil
3527                                        (delete-directory f-or-d)
3528                                      (file-error
3529                                       (mapcar (lambda (f)
3530                                                 (or (member f '("." ".."))
3531                                                     (funcall delete-recursive
3532                                                              (nnheader-concat
3533                                                               f-or-d f))))
3534                                               (directory-files f-or-d))
3535                                       (delete-directory f-or-d)))
3536                                  (delete-file f-or-d)))))))
3537                     (funcall delete-recursive dir))))))))))
3538
3539 ;;;###autoload
3540 (defun gnus-agent-batch ()
3541   "Start Gnus, send queue and fetch session."
3542   (interactive)
3543   (let ((init-file-user "")
3544         (gnus-always-read-dribble-file t))
3545     (gnus))
3546   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
3547     (gnus-group-send-queue)
3548     (gnus-agent-fetch-session)))
3549
3550 (defun gnus-agent-unread-articles (group)
3551   (let* ((read (gnus-info-read (gnus-get-info group)))
3552          (known (gnus-agent-load-alist group))
3553          (unread (list nil))
3554          (tail-unread unread))
3555     (while (and known read)
3556       (let ((candidate (car (pop known))))
3557         (while (let* ((range (car read))
3558                       (min   (if (numberp range) range (car range)))
3559                       (max   (if (numberp range) range (cdr range))))
3560                  (cond ((or (not min)
3561                             (< candidate min))
3562                         (gnus-agent-append-to-list tail-unread candidate)
3563                         nil)
3564                        ((> candidate max)
3565                         (setq read (cdr read))
3566                         ;; return t so that I always loop one more
3567                         ;; time.  If I just iterated off the end of
3568                         ;; read, min will become nil and the current
3569                         ;; candidate will be added to the unread list.
3570                         t))))))
3571     (while known
3572       (gnus-agent-append-to-list tail-unread (car (pop known))))
3573     (cdr unread)))
3574
3575 (defun gnus-agent-uncached-articles (articles group &optional cached-header)
3576   "Restrict ARTICLES to numbers already fetched.
3577 Returns a sublist of ARTICLES that excludes those article ids in GROUP
3578 that have already been fetched.
3579 If CACHED-HEADER is nil, articles are only excluded if the article itself
3580 has been fetched."
3581
3582   ;; Logically equivalent to: (gnus-sorted-difference articles (mapcar
3583   ;; 'car gnus-agent-article-alist))
3584
3585   ;; Functionally, I don't need to construct a temp list using mapcar.
3586
3587   (if (and (or gnus-agent-cache (not gnus-plugged))
3588            (gnus-agent-load-alist group))
3589     (let* ((ref gnus-agent-article-alist)
3590            (arts articles)
3591            (uncached (list nil))
3592            (tail-uncached uncached))
3593       (while (and ref arts)
3594         (let ((v1 (car arts))
3595               (v2 (caar ref)))
3596           (cond ((< v1 v2) ; v1 does not appear in the reference list
3597                  (gnus-agent-append-to-list tail-uncached v1)
3598                  (setq arts (cdr arts)))
3599                 ((= v1 v2)
3600                  (unless (or cached-header (cdar ref)) ; v1 is already cached
3601                    (gnus-agent-append-to-list tail-uncached v1))
3602                  (setq arts (cdr arts))
3603                  (setq ref (cdr ref)))
3604                 (t ; reference article (v2) preceeds the list being filtered
3605                  (setq ref (cdr ref))))))
3606       (while arts
3607         (gnus-agent-append-to-list tail-uncached (pop arts)))
3608       (cdr uncached))
3609     ;; if gnus-agent-load-alist fails, no articles are cached.
3610     articles))
3611
3612 (defun gnus-agent-retrieve-headers (articles group &optional fetch-old)
3613   (save-excursion
3614     (gnus-agent-create-buffer)
3615     (let ((gnus-decode-encoded-word-function 'identity)
3616           (file (gnus-agent-article-name ".overview" group))
3617           cached-articles uncached-articles)
3618       (gnus-make-directory (nnheader-translate-file-chars
3619                             (file-name-directory file) t))
3620
3621       ;; Populate temp buffer with known headers
3622       (when (file-exists-p file)
3623         (with-current-buffer gnus-agent-overview-buffer
3624           (erase-buffer)
3625           (let ((nnheader-file-coding-system
3626                  gnus-agent-file-coding-system))
3627             (nnheader-insert-nov-file file (car articles)))))
3628
3629       (if (setq uncached-articles (gnus-agent-uncached-articles articles group
3630                                                                 t))
3631           (progn
3632             ;; Populate nntp-server-buffer with uncached headers
3633             (set-buffer nntp-server-buffer)
3634             (erase-buffer)
3635             (cond ((not (eq 'nov (let (gnus-agent) ; Turn off agent
3636                                    (gnus-retrieve-headers
3637                                     uncached-articles group fetch-old))))
3638                    (nnvirtual-convert-headers))
3639                   ((eq 'nntp (car gnus-current-select-method))
3640                    ;; The author of gnus-get-newsgroup-headers-xover
3641                    ;; reports that the XOVER command is commonly
3642                    ;; unreliable. The problem is that recently
3643                    ;; posted articles may not be entered into the
3644                    ;; NOV database in time to respond to my XOVER
3645                    ;; query.
3646                    ;;
3647                    ;; I'm going to use his assumption that the NOV
3648                    ;; database is updated in order of ascending
3649                    ;; article ID.  Therefore, a response containing
3650                    ;; article ID N implies that all articles from 1
3651                    ;; to N-1 are up-to-date.  Therefore, missing
3652                    ;; articles in that range have expired.
3653
3654                    (set-buffer nntp-server-buffer)
3655                    (let* ((fetched-articles (list nil))
3656                           (tail-fetched-articles fetched-articles)
3657                           (min (cond ((numberp fetch-old)
3658                                       (max 1 (- (car articles) fetch-old)))
3659                                      (fetch-old
3660                                       1)
3661                                      (t
3662                                       (car articles))))
3663                           (max (car (last articles))))
3664
3665                      ;; Get the list of articles that were fetched
3666                      (goto-char (point-min))
3667                      (let ((pm (point-max))
3668                            art)
3669                        (while (< (point) pm)
3670                          (when (setq art (gnus-agent-read-article-number))
3671                            (gnus-agent-append-to-list tail-fetched-articles art))
3672                          (forward-line 1)))
3673
3674                      ;; Clip this list to the headers that will
3675                      ;; actually be returned
3676                      (setq fetched-articles (gnus-list-range-intersection
3677                                              (cdr fetched-articles)
3678                                              (cons min max)))
3679
3680                      ;; Clip the uncached articles list to exclude
3681                      ;; IDs after the last FETCHED header.  The
3682                      ;; excluded IDs may be fetchable using HEAD.
3683                      (if (car tail-fetched-articles)
3684                          (setq uncached-articles
3685                                (gnus-list-range-intersection
3686                                 uncached-articles
3687                                 (cons (car uncached-articles)
3688                                       (car tail-fetched-articles)))))
3689
3690                      ;; Create the list of articles that were
3691                      ;; "successfully" fetched.  Success, in this
3692                      ;; case, means that the ID should not be
3693                      ;; fetched again.  In the case of an expired
3694                      ;; article, the header will not be fetched.
3695                      (setq uncached-articles
3696                            (gnus-sorted-nunion fetched-articles
3697                                                uncached-articles))
3698                      )))
3699
3700             ;; Erase the temp buffer
3701             (set-buffer gnus-agent-overview-buffer)
3702             (erase-buffer)
3703
3704             ;; Copy the nntp-server-buffer to the temp buffer
3705             (set-buffer nntp-server-buffer)
3706             (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
3707
3708             ;; Merge the temp buffer with the known headers (found on
3709             ;; disk in FILE) into the nntp-server-buffer
3710             (when uncached-articles
3711               (gnus-agent-braid-nov group uncached-articles file))
3712
3713             ;; Save the new set of known headers to FILE
3714             (set-buffer nntp-server-buffer)
3715             (let ((coding-system-for-write
3716                    gnus-agent-file-coding-system))
3717               (gnus-agent-check-overview-buffer)
3718               (write-region (point-min) (point-max) file nil 'silent))
3719
3720             (gnus-agent-update-view-total-fetched-for group t)
3721
3722             ;; Update the group's article alist to include the newly
3723             ;; fetched articles.
3724             (gnus-agent-load-alist group)
3725             (gnus-agent-save-alist group uncached-articles nil)
3726             )
3727
3728         ;; Copy the temp buffer to the nntp-server-buffer
3729         (set-buffer nntp-server-buffer)
3730         (erase-buffer)
3731         (insert-buffer-substring gnus-agent-overview-buffer)))
3732
3733     (if (and fetch-old
3734              (not (numberp fetch-old)))
3735         t                               ; Don't remove anything.
3736       (nnheader-nov-delete-outside-range
3737        (if fetch-old (max 1 (- (car articles) fetch-old))
3738          (car articles))
3739        (car (last articles)))
3740       t)
3741
3742     'nov))
3743
3744 (defun gnus-agent-request-article (article group)
3745   "Retrieve ARTICLE in GROUP from the agent cache."
3746   (when (and gnus-agent
3747              (or gnus-agent-cache
3748                  (not gnus-plugged))
3749              (numberp article))
3750     (let* ((gnus-command-method (gnus-find-method-for-group group))
3751            (file (gnus-agent-article-name (number-to-string article) group))
3752            (buffer-read-only nil))
3753       (when (and (file-exists-p file)
3754                  (> (nth 7 (file-attributes file)) 0))
3755         (erase-buffer)
3756         (gnus-kill-all-overlays)
3757         (let ((coding-system-for-read gnus-cache-coding-system))
3758           (insert-file-contents file))
3759         t))))
3760
3761 (defun gnus-agent-regenerate-group (group &optional reread)
3762   "Regenerate GROUP.
3763 If REREAD is t, all articles in the .overview are marked as unread.
3764 If REREAD is a list, the specified articles will be marked as unread.
3765 In addition, their NOV entries in .overview will be refreshed using
3766 the articles' current headers.
3767 If REREAD is not nil, downloaded articles are marked as unread."
3768   (interactive
3769    (list (let ((def (or (gnus-group-group-name)
3770                         gnus-newsgroup-name)))
3771            (let ((select (read-string (if def
3772                                           (concat "Group Name ("
3773                                                   def "): ")
3774                                         "Group Name: "))))
3775              (if (and (equal "" select)
3776                       def)
3777                  def
3778                select)))
3779          (catch 'mark
3780            (while (let (c
3781                         (cursor-in-echo-area t)
3782                         (echo-keystrokes 0))
3783                     (message "Mark as unread: (n)one / (a)ll / all (d)ownloaded articles? (n) ")
3784                     (setq c (read-char-exclusive))
3785
3786                     (cond ((or (eq c ?\r) (eq c ?n) (eq c ?N))
3787                            (throw 'mark nil))
3788                           ((or (eq c ?a) (eq c ?A))
3789                            (throw 'mark t))
3790                           ((or (eq c ?d) (eq c ?D))
3791                            (throw 'mark 'some)))
3792                     (gnus-message 3 "Ignoring unexpected input")
3793                     (sit-for 1)
3794                     t)))))
3795   (when group
3796     (gnus-message 5 "Regenerating in %s" group)
3797     (let* ((gnus-command-method (or gnus-command-method
3798                                     (gnus-find-method-for-group group)))
3799            (file (gnus-agent-article-name ".overview" group))
3800            (dir (file-name-directory file))
3801            point
3802            (downloaded (if (file-exists-p dir)
3803                            (sort (mapcar (lambda (name) (string-to-number name))
3804                                          (directory-files dir nil "^[0-9]+$" t))
3805                                  '>)
3806                          (progn (gnus-make-directory dir) nil)))
3807            dl nov-arts
3808            alist header
3809            regenerated)
3810
3811       (mm-with-unibyte-buffer
3812         (if (file-exists-p file)
3813             (let ((nnheader-file-coding-system
3814                    gnus-agent-file-coding-system))
3815               (nnheader-insert-file-contents file)))
3816         (set-buffer-modified-p nil)
3817
3818         ;; Load the article IDs found in the overview file.  As a
3819         ;; side-effect, validate the file contents.
3820         (let ((load t))
3821           (while load
3822             (setq load nil)
3823             (goto-char (point-min))
3824             (while (< (point) (point-max))
3825               (cond ((and (looking-at "[0-9]+\t")
3826                           (<= (- (match-end 0) (match-beginning 0)) 9))
3827                      (push (read (current-buffer)) nov-arts)
3828                      (forward-line 1)
3829                      (let ((l1 (car nov-arts))
3830                            (l2 (cadr nov-arts)))
3831                        (cond ((and (listp reread) (memq l1 reread))
3832                               (gnus-delete-line)
3833                               (setq nov-arts (cdr nov-arts))
3834                               (gnus-message 4 "gnus-agent-regenerate-group: NOV\
3835  entry of article %s deleted." l1))
3836                              ((not l2)
3837                               nil)
3838                              ((< l1 l2)
3839                               (gnus-message 3 "gnus-agent-regenerate-group: NOV\
3840  entries are NOT in ascending order.")
3841                               ;; Don't sort now as I haven't verified
3842                               ;; that every line begins with a number
3843                               (setq load t))
3844                              ((= l1 l2)
3845                               (forward-line -1)
3846                               (gnus-message 4 "gnus-agent-regenerate-group: NOV\
3847  entries contained duplicate of article %s.      Duplicate deleted." l1)
3848                               (gnus-delete-line)
3849                               (setq nov-arts (cdr nov-arts))))))
3850                     (t
3851                      (gnus-message 1 "gnus-agent-regenerate-group: NOV\
3852  entries contained line that did not begin with an article number.  Deleted\
3853  line.")
3854                      (gnus-delete-line))))
3855             (when load
3856               (gnus-message 5 "gnus-agent-regenerate-group: Sorting NOV\
3857  entries into ascending order.")
3858               (sort-numeric-fields 1 (point-min) (point-max))
3859               (setq nov-arts nil))))
3860         (gnus-agent-check-overview-buffer)
3861
3862         ;; Construct a new article alist whose nodes match every header
3863         ;; in the .overview file.  As a side-effect, missing headers are
3864         ;; reconstructed from the downloaded article file.
3865         (while (or downloaded nov-arts)
3866           (cond ((and downloaded
3867                       (or (not nov-arts)
3868                           (> (car downloaded) (car nov-arts))))
3869                  ;; This entry is missing from the overview file
3870                  (gnus-message 3 "Regenerating NOV %s %d..." group
3871                                (car downloaded))
3872                  (let ((file (concat dir (number-to-string (car downloaded)))))
3873                    (mm-with-unibyte-buffer
3874                      (nnheader-insert-file-contents file)
3875                      (nnheader-remove-body)
3876                      (setq header (nnheader-parse-naked-head)))
3877                    (mail-header-set-number header (car downloaded))
3878                    (if nov-arts
3879                        (let ((key (concat "^" (int-to-string (car nov-arts))
3880                                           "\t")))
3881                          (or (re-search-backward key nil t)
3882                              (re-search-forward key))
3883                          (forward-line 1))
3884                      (goto-char (point-min)))
3885                    (nnheader-insert-nov header))
3886                  (setq nov-arts (cons (car downloaded) nov-arts)))
3887                 ((eq (car downloaded) (car nov-arts))
3888                  ;; This entry in the overview has been downloaded
3889                  (push (cons (car downloaded)
3890                              (time-to-days
3891                               (nth 5 (file-attributes
3892                                       (concat dir (number-to-string
3893                                                    (car downloaded))))))) alist)
3894                  (setq downloaded (cdr downloaded))
3895                  (setq nov-arts (cdr nov-arts)))
3896                 (t
3897                  ;; This entry in the overview has not been downloaded
3898                  (push (cons (car nov-arts) nil) alist)
3899                  (setq nov-arts (cdr nov-arts)))))
3900
3901         ;; When gnus-agent-consider-all-articles is set,
3902         ;; gnus-agent-regenerate-group should NOT remove article IDs from
3903         ;; the alist.  Those IDs serve as markers to indicate that an
3904         ;; attempt has been made to fetch that article's header.
3905
3906         ;; When gnus-agent-consider-all-articles is NOT set,
3907         ;; gnus-agent-regenerate-group can remove the article ID of every
3908         ;; article (with the exception of the last ID in the list - it's
3909         ;; special) that no longer appears in the overview.  In this
3910         ;; situtation, the last article ID in the list implies that it,
3911         ;; and every article ID preceeding it, have been fetched from the
3912         ;; server.
3913
3914         (if gnus-agent-consider-all-articles
3915             ;; Restore all article IDs that were not found in the overview file.
3916             (let* ((n (cons nil alist))
3917                    (merged n)
3918                    (o (gnus-agent-load-alist group)))
3919               (while o
3920                 (let ((nID (caadr n))
3921                       (oID (caar o)))
3922                   (cond ((not nID)
3923                          (setq n (setcdr n (list (list oID))))
3924                          (setq o (cdr o)))
3925                         ((< oID nID)
3926                          (setcdr n (cons (list oID) (cdr n)))
3927                          (setq o (cdr o)))
3928                         ((= oID nID)
3929                          (setq o (cdr o))
3930                          (setq n (cdr n)))
3931                         (t
3932                          (setq n (cdr n))))))
3933               (setq alist (cdr merged)))
3934           ;; Restore the last article ID if it is not already in the new alist
3935           (let ((n (last alist))
3936                 (o (last (gnus-agent-load-alist group))))
3937             (cond ((not o)
3938                    nil)
3939                   ((not n)
3940                    (push (cons (caar o) nil) alist))
3941                   ((< (caar n) (caar o))
3942                    (setcdr n (list (car o)))))))
3943
3944         (let ((inhibit-quit t))
3945           (if (setq regenerated (buffer-modified-p))
3946               (let ((coding-system-for-write gnus-agent-file-coding-system))
3947                 (write-region (point-min) (point-max) file nil 'silent)))
3948
3949           (setq regenerated (or regenerated
3950                                 (and reread gnus-agent-article-alist)
3951                                 (not (equal alist gnus-agent-article-alist))))
3952
3953           (setq gnus-agent-article-alist alist)
3954
3955           (when regenerated
3956             (gnus-agent-save-alist group)
3957
3958             ;; I have to alter the group's active range NOW as
3959             ;; gnus-make-ascending-articles-unread will use it to
3960             ;; recalculate the number of unread articles in the group
3961
3962             (let ((group (gnus-group-real-name group))
3963                   (group-active (or (gnus-active group)
3964                                     (gnus-activate-group group))))
3965               (gnus-agent-possibly-alter-active group group-active)))))
3966
3967       (when (and reread gnus-agent-article-alist)
3968         (gnus-agent-synchronize-group-flags 
3969          group 
3970          (list (list
3971                 (if (listp reread)
3972                     reread
3973                   (delq nil (mapcar (function (lambda (c)
3974                                                 (cond ((eq reread t)
3975                                                        (car c))
3976                                                       ((cdr c)
3977                                                        (car c)))))
3978                                     gnus-agent-article-alist)))
3979                 'del '(read)))
3980          gnus-command-method)
3981
3982         (when regenerated
3983           (gnus-agent-update-files-total-fetched-for group nil)))
3984
3985       (gnus-message 5 "")
3986       regenerated)))
3987
3988 ;;;###autoload
3989 (defun gnus-agent-regenerate (&optional clean reread)
3990   "Regenerate all agent covered files.
3991 If CLEAN, obsolete (ignore)."
3992   (interactive "P")
3993   (let (regenerated)
3994     (gnus-message 4 "Regenerating Gnus agent files...")
3995     (dolist (gnus-command-method (gnus-agent-covered-methods))
3996         (dolist (group (gnus-groups-from-server gnus-command-method))
3997           (setq regenerated (or (gnus-agent-regenerate-group group reread)
3998                                 regenerated))))
3999     (gnus-message 4 "Regenerating Gnus agent files...done")
4000
4001     regenerated))
4002
4003 (defun gnus-agent-go-online (&optional force)
4004   "Switch servers into online status."
4005   (interactive (list t))
4006   (dolist (server gnus-opened-servers)
4007     (when (eq (nth 1 server) 'offline)
4008       (if (if (eq force 'ask)
4009               (gnus-y-or-n-p
4010                (format "Switch %s:%s into online status? "
4011                        (caar server) (cadar server)))
4012             force)
4013           (setcar (nthcdr 1 server) 'close)))))
4014
4015 (defun gnus-agent-toggle-group-plugged (group)
4016   "Toggle the status of the server of the current group."
4017   (interactive (list (gnus-group-group-name)))
4018   (let* ((method (gnus-find-method-for-group group))
4019          (status (cadr (assoc method gnus-opened-servers))))
4020     (if (eq status 'offline)
4021         (gnus-server-set-status method 'closed)
4022       (gnus-close-server method)
4023       (gnus-server-set-status method 'offline))
4024     (message "Turn %s:%s from %s to %s." (car method) (cadr method)
4025              (if (eq status 'offline) 'offline 'online)
4026              (if (eq status 'offline) 'online 'offline))))
4027
4028 (defun gnus-agent-group-covered-p (group)
4029   (gnus-agent-method-p (gnus-group-method group)))
4030
4031 ;; Added to support XEmacs
4032 (eval-and-compile
4033   (unless (fboundp 'directory-files-and-attributes)
4034     (defun directory-files-and-attributes (directory
4035                                            &optional full match nosort)
4036       (let (result)
4037         (dolist (file (directory-files directory full match nosort))
4038           (push (cons file (file-attributes file)) result))
4039         (nreverse result)))))
4040
4041 (defun gnus-agent-update-files-total-fetched-for
4042   (group delta &optional method path)
4043   "Update, or set, the total disk space used by the articles that the
4044 agent has fetched."
4045   (when gnus-agent-total-fetched-hashtb
4046     (gnus-agent-with-refreshed-group
4047      group
4048      ;; if null, gnus-agent-group-pathname will calc method.
4049      (let* ((gnus-command-method method)
4050             (path (or path (gnus-agent-group-pathname group)))
4051             (entry (or (gnus-gethash path gnus-agent-total-fetched-hashtb)
4052                        (gnus-sethash path (make-list 3 0)
4053                                      gnus-agent-total-fetched-hashtb))))
4054        (when (listp delta)
4055          (if delta
4056              (let ((sum 0.0)
4057                    file)
4058                (while (setq file (pop delta))
4059                  (incf sum (float (or (nth 7 (file-attributes
4060                                               (nnheader-concat
4061                                                path
4062                                                (if (numberp file)
4063                                                    (number-to-string file)
4064                                                  file)))) 0))))
4065                (setq delta sum))
4066            (let ((sum (- (nth 2 entry)))
4067                  (info (directory-files-and-attributes path nil "^-?[0-9]+$" t))
4068                  file)
4069              (while (setq file (pop info))
4070                (incf sum (float (or (nth 8 file) 0))))
4071              (setq delta sum))))
4072
4073        (setq gnus-agent-need-update-total-fetched-for t)
4074        (incf (nth 2 entry) delta)))))
4075
4076 (defun gnus-agent-update-view-total-fetched-for
4077   (group agent-over &optional method path)
4078   "Update, or set, the total disk space used by the .agentview and
4079 .overview files.  These files are calculated separately as they can be
4080 modified."
4081   (when gnus-agent-total-fetched-hashtb
4082     (gnus-agent-with-refreshed-group
4083      group
4084      ;; if null, gnus-agent-group-pathname will calc method.
4085      (let* ((gnus-command-method method)
4086             (path (or path (gnus-agent-group-pathname group)))
4087             (entry (or (gnus-gethash path gnus-agent-total-fetched-hashtb)
4088                        (gnus-sethash path (make-list 3 0)
4089                                      gnus-agent-total-fetched-hashtb)))
4090             (size (or (nth 7 (file-attributes
4091                               (nnheader-concat
4092                                path (if agent-over
4093                                         ".overview"
4094                                       ".agentview"))))
4095                       0)))
4096        (setq gnus-agent-need-update-total-fetched-for t)
4097        (setf (nth (if agent-over 1 0) entry) size)))))
4098
4099 (defun gnus-agent-total-fetched-for (group &optional method no-inhibit)
4100   "Get the total disk space used by the specified GROUP."
4101   (unless gnus-agent-total-fetched-hashtb
4102     (setq gnus-agent-total-fetched-hashtb (gnus-make-hashtable 1024)))
4103
4104   ;; if null, gnus-agent-group-pathname will calc method.
4105   (let* ((gnus-command-method method)
4106          (path (gnus-agent-group-pathname group))
4107          (entry (gnus-gethash path gnus-agent-total-fetched-hashtb)))
4108     (if entry
4109         (apply '+ entry)
4110       (let ((gnus-agent-inhibit-update-total-fetched-for (not no-inhibit)))
4111         (+
4112          (gnus-agent-update-view-total-fetched-for  group nil method path)
4113          (gnus-agent-update-view-total-fetched-for  group t   method path)
4114          (gnus-agent-update-files-total-fetched-for group nil method path))))))
4115
4116 (provide 'gnus-agent)
4117
4118 ;;; arch-tag: b0ba4afc-5229-4cee-ad25-9956daa4e91e
4119 ;;; gnus-agent.el ends here