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