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