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