(gnus-agent-fetch-selected-article): Use
[gnus] / lisp / gnus-agent.el
1 ;;; gnus-agent.el --- unplugged support for Gnus
2 ;; Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; This file is part of GNU Emacs.
7
8 ;; GNU Emacs is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation; either version 2, or (at your option)
11 ;; any later version.
12
13 ;; GNU Emacs is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 ;; GNU General Public License for more details.
17
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
20 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 ;; Boston, MA 02111-1307, USA.
22
23 ;;; Commentary:
24
25 ;;; Code:
26
27 (require 'gnus)
28 (require 'gnus-cache)
29 (require 'nnvirtual)
30 (require 'gnus-sum)
31 (require 'gnus-score)
32 (require 'gnus-srvr)
33 (eval-when-compile
34   (if (featurep 'xemacs)
35       (require 'itimer)
36     (require 'timer))
37   (require 'cl))
38
39 (eval-and-compile
40   (autoload 'gnus-server-update-server "gnus-srvr"))
41
42 (defcustom gnus-agent-directory (nnheader-concat gnus-directory "agent/")
43   "Where the Gnus agent will store its files."
44   :group 'gnus-agent
45   :type 'directory)
46
47 (defcustom gnus-agent-plugged-hook nil
48   "Hook run when plugging into the network."
49   :group 'gnus-agent
50   :type 'hook)
51
52 (defcustom gnus-agent-unplugged-hook nil
53   "Hook run when unplugging from the network."
54   :group 'gnus-agent
55   :type 'hook)
56
57 (defcustom gnus-agent-handle-level gnus-level-subscribed
58   "Groups on levels higher than this variable will be ignored by the Agent."
59   :group 'gnus-agent
60   :type 'integer)
61
62 (defcustom gnus-agent-expire-days 7
63   "Read articles older than this will be expired.
64 This can also be a list of regexp/day pairs.  The regexps will
65 be matched against group names."
66   :group 'gnus-agent
67   :type 'integer)
68
69 (defcustom gnus-agent-expire-all nil
70   "If non-nil, also expire unread, ticked and dormant articles.
71 If nil, only read articles will be expired."
72   :group 'gnus-agent
73   :type 'boolean)
74
75 (defcustom gnus-agent-group-mode-hook nil
76   "Hook run in Agent group minor modes."
77   :group 'gnus-agent
78   :type 'hook)
79
80 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
81 (when (featurep 'xemacs)
82   (add-hook 'gnus-agent-group-mode-hook 'gnus-xmas-agent-group-menu-add))
83
84 (defcustom gnus-agent-summary-mode-hook nil
85   "Hook run in Agent summary minor modes."
86   :group 'gnus-agent
87   :type 'hook)
88
89 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
90 (when (featurep 'xemacs)
91   (add-hook 'gnus-agent-summary-mode-hook 'gnus-xmas-agent-summary-menu-add))
92
93 (defcustom gnus-agent-server-mode-hook nil
94   "Hook run in Agent summary minor modes."
95   :group 'gnus-agent
96   :type 'hook)
97
98 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
99 (when (featurep 'xemacs)
100   (add-hook 'gnus-agent-server-mode-hook 'gnus-xmas-agent-server-menu-add))
101
102 (defcustom gnus-agent-confirmation-function 'y-or-n-p
103   "Function to confirm when error happens."
104   :version "21.1"
105   :group 'gnus-agent
106   :type 'function)
107
108 (defcustom gnus-agent-synchronize-flags 'ask
109   "Indicate if flags are synchronized when you plug in.
110 If this is `ask' the hook will query the user."
111   :version "21.1"
112   :type '(choice (const :tag "Always" t)
113                  (const :tag "Never" nil)
114                  (const :tag "Ask" ask))
115   :group 'gnus-agent)
116
117 (defcustom gnus-agent-go-online 'ask
118   "Indicate if offline servers go online when you plug in.
119 If this is `ask' the hook will query the user."
120   :version "21.1"
121   :type '(choice (const :tag "Always" t)
122                  (const :tag "Never" nil)
123                  (const :tag "Ask" ask))
124   :group 'gnus-agent)
125
126 (defcustom gnus-agent-mark-unread-after-downloaded t
127   "Indicate whether to mark articles unread after downloaded."
128   :version "21.1"
129   :type 'boolean
130   :group 'gnus-agent)
131
132 (defcustom gnus-agent-download-marks '(download)
133   "Marks for downloading."
134   :version "21.1"
135   :type '(repeat (symbol :tag "Mark"))
136   :group 'gnus-agent)
137
138 (defcustom gnus-agent-consider-all-articles nil
139   "If non-nil, consider also the read articles for downloading."
140   :version "21.4"
141   :type 'boolean
142   :group 'gnus-agent)
143
144 (defcustom gnus-agent-max-fetch-size 10000000 ;; 10 Mb
145   "gnus-agent-fetch-session is required to split its article fetches into chunks smaller than this limit."
146   :group 'gnus-agent
147   :type 'integer)
148
149 ;;; Internal variables
150
151 (defvar gnus-agent-history-buffers nil)
152 (defvar gnus-agent-buffer-alist nil)
153 (defvar gnus-agent-article-alist nil
154 "An assoc list identifying the articles whose headers have been fetched.  
155  If successfully fetched, these headers will be stored in the group's overview file.
156  The key of each assoc pair is the article ID.
157  The value of each assoc pair is a flag indicating 
158  whether the identified article has been downloaded (gnus-agent-fetch-articles
159  sets the value to the day of the download).
160  NOTES:
161  1) The last element of this list can not be expired as some 
162     routines (for example, get-agent-fetch-headers) use the last
163     value to track which articles have had their headers retrieved.
164  2) The gnus-agent-regenerate may destructively modify the value.
165 ")
166 (defvar gnus-agent-group-alist nil)
167 (defvar gnus-category-alist nil)
168 (defvar gnus-agent-current-history nil)
169 (defvar gnus-agent-overview-buffer nil)
170 (defvar gnus-category-predicate-cache nil)
171 (defvar gnus-category-group-cache nil)
172 (defvar gnus-agent-spam-hashtb nil)
173 (defvar gnus-agent-file-name nil)
174 (defvar gnus-agent-send-mail-function nil)
175 (defvar gnus-agent-file-coding-system 'raw-text)
176 (defvar gnus-agent-file-loading-cache nil)
177 (defvar gnus-agent-file-header-cache nil)
178
179 (defvar gnus-agent-auto-agentize-methods '(nntp nnimap)
180   "Initially, all servers from these methods are agentized.
181 The user may remove or add servers using the Server buffer.  See Info
182 node `(gnus)Server Buffer'.")
183
184 ;; Dynamic variables
185 (defvar gnus-headers)
186 (defvar gnus-score)
187
188 ;;;
189 ;;; Setup
190 ;;;
191
192 (defun gnus-open-agent ()
193   (setq gnus-agent t)
194   (gnus-agent-read-servers)
195   (gnus-category-read)
196   (gnus-agent-create-buffer)
197   (add-hook 'gnus-group-mode-hook 'gnus-agent-mode)
198   (add-hook 'gnus-summary-mode-hook 'gnus-agent-mode)
199   (add-hook 'gnus-server-mode-hook 'gnus-agent-mode))
200
201 (defun gnus-agent-create-buffer ()
202   (if (gnus-buffer-live-p gnus-agent-overview-buffer)
203       t
204     (setq gnus-agent-overview-buffer
205           (gnus-get-buffer-create " *Gnus agent overview*"))
206     (with-current-buffer gnus-agent-overview-buffer
207       (mm-enable-multibyte))
208     nil))
209
210 (gnus-add-shutdown 'gnus-close-agent 'gnus)
211
212 (defun gnus-close-agent ()
213   (setq gnus-category-predicate-cache nil
214         gnus-category-group-cache nil
215         gnus-agent-spam-hashtb nil)
216   (gnus-kill-buffer gnus-agent-overview-buffer))
217
218 ;;;
219 ;;; Utility functions
220 ;;;
221
222 (defun gnus-agent-read-file (file)
223   "Load FILE and do a `read' there."
224   (with-temp-buffer
225     (ignore-errors
226       (nnheader-insert-file-contents file)
227       (goto-char (point-min))
228       (read (current-buffer)))))
229
230 (defsubst gnus-agent-method ()
231   (concat (symbol-name (car gnus-command-method)) "/"
232           (if (equal (cadr gnus-command-method) "")
233               "unnamed"
234             (cadr gnus-command-method))))
235
236 (defsubst gnus-agent-directory ()
237   "Path of the Gnus agent directory."
238   (nnheader-concat gnus-agent-directory
239                    (nnheader-translate-file-chars (gnus-agent-method)) "/"))
240
241 (defun gnus-agent-lib-file (file)
242   "The full path of the Gnus agent library FILE."
243   (expand-file-name file
244                     (file-name-as-directory
245                      (expand-file-name "agent.lib" (gnus-agent-directory)))))
246
247 ;;; Fetching setup functions.
248
249 (defun gnus-agent-start-fetch ()
250   "Initialize data structures for efficient fetching."
251   (gnus-agent-create-buffer))
252
253 (defun gnus-agent-stop-fetch ()
254   "Save all data structures and clean up."
255   (setq gnus-agent-spam-hashtb nil)
256   (save-excursion
257     (set-buffer nntp-server-buffer)
258     (widen)))
259
260 (defmacro gnus-agent-with-fetch (&rest forms)
261   "Do FORMS safely."
262   `(unwind-protect
263        (let ((gnus-agent-fetching t))
264          (gnus-agent-start-fetch)
265          ,@forms)
266      (gnus-agent-stop-fetch)))
267
268 (put 'gnus-agent-with-fetch 'lisp-indent-function 0)
269 (put 'gnus-agent-with-fetch 'edebug-form-spec '(body))
270
271 (defmacro gnus-agent-append-to-list (tail value)
272   `(setq ,tail (setcdr ,tail (cons ,value nil))))
273
274 ;;;
275 ;;; Mode infestation
276 ;;;
277
278 (defvar gnus-agent-mode-hook nil
279   "Hook run when installing agent mode.")
280
281 (defvar gnus-agent-mode nil)
282 (defvar gnus-agent-mode-status '(gnus-agent-mode " Plugged"))
283
284 (defun gnus-agent-mode ()
285   "Minor mode for providing a agent support in Gnus buffers."
286   (let* ((buffer (progn (string-match "^gnus-\\(.*\\)-mode$"
287                                       (symbol-name major-mode))
288                         (match-string 1 (symbol-name major-mode))))
289          (mode (intern (format "gnus-agent-%s-mode" buffer))))
290     (set (make-local-variable 'gnus-agent-mode) t)
291     (set mode nil)
292     (set (make-local-variable mode) t)
293     ;; Set up the menu.
294     (when (gnus-visual-p 'agent-menu 'menu)
295       (funcall (intern (format "gnus-agent-%s-make-menu-bar" buffer))))
296     (unless (assq 'gnus-agent-mode minor-mode-alist)
297       (push gnus-agent-mode-status minor-mode-alist))
298     (unless (assq mode minor-mode-map-alist)
299       (push (cons mode (symbol-value (intern (format "gnus-agent-%s-mode-map"
300                                                      buffer))))
301             minor-mode-map-alist))
302     (when (eq major-mode 'gnus-group-mode)
303       (gnus-agent-toggle-plugged gnus-plugged))
304     (gnus-run-hooks 'gnus-agent-mode-hook
305                     (intern (format "gnus-agent-%s-mode-hook" buffer)))))
306
307 (defvar gnus-agent-group-mode-map (make-sparse-keymap))
308 (gnus-define-keys gnus-agent-group-mode-map
309   "Ju" gnus-agent-fetch-groups
310   "Jc" gnus-enter-category-buffer
311   "Jj" gnus-agent-toggle-plugged
312   "Js" gnus-agent-fetch-session
313   "JY" gnus-agent-synchronize-flags
314   "JS" gnus-group-send-queue
315   "Ja" gnus-agent-add-group
316   "Jr" gnus-agent-remove-group
317   "Jo" gnus-agent-toggle-group-plugged)
318
319 (defun gnus-agent-group-make-menu-bar ()
320   (unless (boundp 'gnus-agent-group-menu)
321     (easy-menu-define
322      gnus-agent-group-menu gnus-agent-group-mode-map ""
323      '("Agent"
324        ["Toggle plugged" gnus-agent-toggle-plugged t]
325        ["Toggle group plugged" gnus-agent-toggle-group-plugged t]
326        ["List categories" gnus-enter-category-buffer t]
327        ["Send queue" gnus-group-send-queue gnus-plugged]
328        ("Fetch"
329         ["All" gnus-agent-fetch-session gnus-plugged]
330         ["Group" gnus-agent-fetch-group gnus-plugged])))))
331
332 (defvar gnus-agent-summary-mode-map (make-sparse-keymap))
333 (gnus-define-keys gnus-agent-summary-mode-map
334   "Jj" gnus-agent-toggle-plugged
335   "Ju" gnus-agent-summary-fetch-group
336   "JS" gnus-agent-fetch-group
337   "Js" gnus-agent-summary-fetch-series
338   "J#" gnus-agent-mark-article
339   "J\M-#" gnus-agent-unmark-article
340   "@" gnus-agent-toggle-mark
341   "Jc" gnus-agent-catchup)
342
343 (defun gnus-agent-summary-make-menu-bar ()
344   (unless (boundp 'gnus-agent-summary-menu)
345     (easy-menu-define
346      gnus-agent-summary-menu gnus-agent-summary-mode-map ""
347      '("Agent"
348        ["Toggle plugged" gnus-agent-toggle-plugged t]
349        ["Mark as downloadable" gnus-agent-mark-article t]
350        ["Unmark as downloadable" gnus-agent-unmark-article t]
351        ["Toggle mark" gnus-agent-toggle-mark t]
352        ["Fetch downloadable" gnus-agent-summary-fetch-group t]
353        ["Catchup undownloaded" gnus-agent-catchup t]))))
354
355 (defvar gnus-agent-server-mode-map (make-sparse-keymap))
356 (gnus-define-keys gnus-agent-server-mode-map
357   "Jj" gnus-agent-toggle-plugged
358   "Ja" gnus-agent-add-server
359   "Jr" gnus-agent-remove-server)
360
361 (defun gnus-agent-server-make-menu-bar ()
362   (unless (boundp 'gnus-agent-server-menu)
363     (easy-menu-define
364      gnus-agent-server-menu gnus-agent-server-mode-map ""
365      '("Agent"
366        ["Toggle plugged" gnus-agent-toggle-plugged t]
367        ["Add" gnus-agent-add-server t]
368        ["Remove" gnus-agent-remove-server t]))))
369
370 (defun gnus-agent-make-mode-line-string (string mouse-button mouse-func)
371   (if (and (fboundp 'propertize)
372            (fboundp 'make-mode-line-mouse-map))
373       (propertize string 'local-map
374                   (make-mode-line-mouse-map mouse-button mouse-func))
375     string))
376
377 (defun gnus-agent-toggle-plugged (plugged)
378   "Toggle whether Gnus is unplugged or not."
379   (interactive (list (not gnus-plugged)))
380   (if plugged
381       (progn
382         (setq gnus-plugged plugged)
383         (gnus-run-hooks 'gnus-agent-plugged-hook)
384         (setcar (cdr gnus-agent-mode-status)
385                 (gnus-agent-make-mode-line-string " Plugged"
386                                                   'mouse-2
387                                                   'gnus-agent-toggle-plugged))
388         (gnus-agent-go-online gnus-agent-go-online)
389         (gnus-agent-possibly-synchronize-flags))
390     (gnus-agent-close-connections)
391     (setq gnus-plugged plugged)
392     (gnus-run-hooks 'gnus-agent-unplugged-hook)
393     (setcar (cdr gnus-agent-mode-status)
394             (gnus-agent-make-mode-line-string " Unplugged"
395                                               'mouse-2
396                                               'gnus-agent-toggle-plugged)))
397   (set-buffer-modified-p t))
398
399 (defun gnus-agent-close-connections ()
400   "Close all methods covered by the Gnus agent."
401   (let ((methods gnus-agent-covered-methods))
402     (while methods
403       (gnus-close-server (pop methods)))))
404
405 ;;;###autoload
406 (defun gnus-unplugged ()
407   "Start Gnus unplugged."
408   (interactive)
409   (setq gnus-plugged nil)
410   (gnus))
411
412 ;;;###autoload
413 (defun gnus-plugged ()
414   "Start Gnus plugged."
415   (interactive)
416   (setq gnus-plugged t)
417   (gnus))
418
419 ;;;###autoload
420 (defun gnus-slave-unplugged (&optional arg)
421   "Read news as a slave unplugged."
422   (interactive "P")
423   (setq gnus-plugged nil)
424   (gnus arg nil 'slave))
425
426 ;;;###autoload
427 (defun gnus-agentize ()
428   "Allow Gnus to be an offline newsreader.
429 The normal usage of this command is to put the following as the
430 last form in your `.gnus.el' file:
431
432 \(gnus-agentize)
433
434 This will modify the `gnus-setup-news-hook', and
435 `message-send-mail-real-function' variables, and install the Gnus agent
436 minor mode in all Gnus buffers."
437   (interactive)
438   (gnus-open-agent)
439   (add-hook 'gnus-setup-news-hook 'gnus-agent-queue-setup)
440   (unless gnus-agent-send-mail-function
441     (setq gnus-agent-send-mail-function (or
442                                          message-send-mail-real-function
443                                          message-send-mail-function)
444           message-send-mail-real-function 'gnus-agent-send-mail))
445   (unless gnus-agent-covered-methods
446     (mapcar
447      (lambda (server)
448        (if (memq (car (gnus-server-to-method server)) 
449                  gnus-agent-auto-agentize-methods)
450            (setq gnus-agent-covered-methods 
451                  (cons (gnus-server-to-method server)
452                        gnus-agent-covered-methods ))))
453      (append (list gnus-select-method) gnus-secondary-select-methods))))
454
455 (defun gnus-agent-queue-setup ()
456   "Make sure the queue group exists."
457   (unless (gnus-gethash "nndraft:queue" gnus-newsrc-hashtb)
458     (gnus-request-create-group "queue" '(nndraft ""))
459     (let ((gnus-level-default-subscribed 1))
460       (gnus-subscribe-group "nndraft:queue" nil '(nndraft "")))
461     (gnus-group-set-parameter
462      "nndraft:queue" 'gnus-dummy '((gnus-draft-mode)))))
463
464 (defun gnus-agent-send-mail ()
465   (if gnus-plugged
466       (funcall gnus-agent-send-mail-function)
467     (goto-char (point-min))
468     (re-search-forward
469      (concat "^" (regexp-quote mail-header-separator) "\n"))
470     (replace-match "\n")
471     (gnus-agent-insert-meta-information 'mail)
472     (gnus-request-accept-article "nndraft:queue" nil t t)))
473
474 (defun gnus-agent-insert-meta-information (type &optional method)
475   "Insert meta-information into the message that says how it's to be posted.
476 TYPE can be either `mail' or `news'.  If the latter, then METHOD can
477 be a select method."
478   (save-excursion
479     (message-remove-header gnus-agent-meta-information-header)
480     (goto-char (point-min))
481     (insert gnus-agent-meta-information-header ": "
482             (symbol-name type) " " (format "%S" method)
483             "\n")
484     (forward-char -1)
485     (while (search-backward "\n" nil t)
486       (replace-match "\\n" t t))))
487
488 (defun gnus-agent-restore-gcc ()
489   "Restore GCC field from saved header."
490   (save-excursion
491     (goto-char (point-min))
492     (while (re-search-forward (concat gnus-agent-gcc-header ":") nil t)
493       (replace-match "Gcc:" 'fixedcase))))
494
495 (defun gnus-agent-any-covered-gcc ()
496   (save-restriction
497     (message-narrow-to-headers)
498     (let* ((gcc (mail-fetch-field "gcc" nil t))
499            (methods (and gcc
500                          (mapcar 'gnus-inews-group-method
501                                  (message-unquote-tokens
502                                   (message-tokenize-header
503                                    gcc " ,")))))
504            covered)
505       (while (and (not covered) methods)
506         (setq covered (gnus-agent-method-p (car methods))
507               methods (cdr methods)))
508       covered)))
509
510 ;;;###autoload
511 (defun gnus-agent-possibly-save-gcc ()
512   "Save GCC if Gnus is unplugged."
513   (when (and (not gnus-plugged) (gnus-agent-any-covered-gcc))
514     (save-excursion
515       (goto-char (point-min))
516       (let ((case-fold-search t))
517         (while (re-search-forward "^gcc:" nil t)
518           (replace-match (concat gnus-agent-gcc-header ":") 'fixedcase))))))
519
520 (defun gnus-agent-possibly-do-gcc ()
521   "Do GCC if Gnus is plugged."
522   (when (or gnus-plugged (not (gnus-agent-any-covered-gcc)))
523     (gnus-inews-do-gcc)))
524
525 ;;;
526 ;;; Group mode commands
527 ;;;
528
529 (defun gnus-agent-fetch-groups (n)
530   "Put all new articles in the current groups into the Agent."
531   (interactive "P")
532   (unless gnus-plugged
533     (error "Groups can't be fetched when Gnus is unplugged"))
534   (gnus-group-iterate n 'gnus-agent-fetch-group))
535
536 (defun gnus-agent-fetch-group (&optional group)
537   "Put all new articles in GROUP into the Agent."
538   (interactive (list (gnus-group-group-name)))
539   (let ((state gnus-plugged))
540     (unwind-protect
541         (progn
542           (setq group (or group gnus-newsgroup-name))
543           (unless group
544             (error "No group on the current line"))
545           (unless state
546             (gnus-agent-toggle-plugged gnus-plugged))
547           (let ((gnus-command-method (gnus-find-method-for-group group)))
548             (gnus-agent-with-fetch
549               (gnus-agent-fetch-group-1 group gnus-command-method)
550               (gnus-message 5 "Fetching %s...done" group))))
551       (when (and (not state)
552                  gnus-plugged)
553         (gnus-agent-toggle-plugged gnus-plugged)))))
554
555 (defun gnus-agent-add-group (category arg)
556   "Add the current group to an agent category."
557   (interactive
558    (list
559     (intern
560      (completing-read
561       "Add to category: "
562       (mapcar (lambda (cat) (list (symbol-name (car cat))))
563               gnus-category-alist)
564       nil t))
565     current-prefix-arg))
566   (let ((cat (assq category gnus-category-alist))
567         c groups)
568     (gnus-group-iterate arg
569       (lambda (group)
570         (when (cadddr (setq c (gnus-group-category group)))
571           (setf (cadddr c) (delete group (cadddr c))))
572         (push group groups)))
573     (setf (cadddr cat) (nconc (cadddr cat) groups))
574     (gnus-category-write)))
575
576 (defun gnus-agent-remove-group (arg)
577   "Remove the current group from its agent category, if any."
578   (interactive "P")
579   (let (c)
580     (gnus-group-iterate arg
581       (lambda (group)
582         (when (cadddr (setq c (gnus-group-category group)))
583           (setf (cadddr c) (delete group (cadddr c))))))
584     (gnus-category-write)))
585
586 (defun gnus-agent-synchronize-flags ()
587   "Synchronize unplugged flags with servers."
588   (interactive)
589   (save-excursion
590     (dolist (gnus-command-method gnus-agent-covered-methods)
591       (when (file-exists-p (gnus-agent-lib-file "flags"))
592         (gnus-agent-synchronize-flags-server gnus-command-method)))))
593
594 (defun gnus-agent-possibly-synchronize-flags ()
595   "Synchronize flags according to `gnus-agent-synchronize-flags'."
596   (interactive)
597   (save-excursion
598     (dolist (gnus-command-method gnus-agent-covered-methods)
599       (when (file-exists-p (gnus-agent-lib-file "flags"))
600         (gnus-agent-possibly-synchronize-flags-server gnus-command-method)))))
601
602 (defun gnus-agent-synchronize-flags-server (method)
603   "Synchronize flags set when unplugged for server."
604   (let ((gnus-command-method method))
605     (when (file-exists-p (gnus-agent-lib-file "flags"))
606       (set-buffer (get-buffer-create " *Gnus Agent flag synchronize*"))
607       (erase-buffer)
608       (nnheader-insert-file-contents (gnus-agent-lib-file "flags"))
609       (if (null (gnus-check-server gnus-command-method))
610           (gnus-message 1 "Couldn't open server %s" (nth 1 gnus-command-method))
611         (while (not (eobp))
612           (if (null (eval (read (current-buffer))))
613               (progn (forward-line)
614                      (kill-line -1))
615             (write-file (gnus-agent-lib-file "flags"))
616             (error "Couldn't set flags from file %s"
617                    (gnus-agent-lib-file "flags"))))
618         (delete-file (gnus-agent-lib-file "flags")))
619       (kill-buffer nil))))
620
621 (defun gnus-agent-possibly-synchronize-flags-server (method)
622   "Synchronize flags for server according to `gnus-agent-synchronize-flags'."
623   (when (or (and gnus-agent-synchronize-flags
624                  (not (eq gnus-agent-synchronize-flags 'ask)))
625             (and (eq gnus-agent-synchronize-flags 'ask)
626                  (gnus-y-or-n-p (format "Synchronize flags on server `%s'? "
627                                         (cadr method)))))
628     (gnus-agent-synchronize-flags-server method)))
629
630 ;;;
631 ;;; Server mode commands
632 ;;;
633
634 (defun gnus-agent-add-server (server)
635   "Enroll SERVER in the agent program."
636   (interactive (list (gnus-server-server-name)))
637   (unless server
638     (error "No server on the current line"))
639   (let ((method (gnus-server-get-method nil (gnus-server-server-name))))
640     (when (gnus-agent-method-p method)
641       (error "Server already in the agent program"))
642     (push method gnus-agent-covered-methods)
643     (gnus-server-update-server server)
644     (gnus-agent-write-servers)
645     (gnus-message 1 "Entered %s into the Agent" server)))
646
647 (defun gnus-agent-remove-server (server)
648   "Remove SERVER from the agent program."
649   (interactive (list (gnus-server-server-name)))
650   (unless server
651     (error "No server on the current line"))
652   (let ((method (gnus-server-get-method nil (gnus-server-server-name))))
653     (unless (gnus-agent-method-p method)
654       (error "Server not in the agent program"))
655     (setq gnus-agent-covered-methods
656           (delete method gnus-agent-covered-methods))
657     (gnus-server-update-server server)
658     (gnus-agent-write-servers)
659     (gnus-message 1 "Removed %s from the agent" server)))
660
661 (defun gnus-agent-read-servers ()
662   "Read the alist of covered servers."
663   (mapcar (lambda (m)
664             (let ((method (gnus-server-get-method
665                            nil
666                            (or m "native"))))
667               (if method
668                   (unless (member method gnus-agent-covered-methods)
669                     (push method gnus-agent-covered-methods))
670                 (gnus-message 1 "Ignoring disappeared server `%s'" m)
671                 (sit-for 1))))
672           (gnus-agent-read-file
673            (nnheader-concat gnus-agent-directory "lib/servers"))))
674
675 (defun gnus-agent-write-servers ()
676   "Write the alist of covered servers."
677   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
678   (let ((coding-system-for-write nnheader-file-coding-system)
679         (file-name-coding-system nnmail-pathname-coding-system))
680     (with-temp-file (nnheader-concat gnus-agent-directory "lib/servers")
681       (prin1 (mapcar 'gnus-method-simplify gnus-agent-covered-methods)
682              (current-buffer)))))
683
684 ;;;
685 ;;; Summary commands
686 ;;;
687
688 (defun gnus-agent-mark-article (n &optional unmark)
689   "Mark the next N articles as downloadable.
690 If N is negative, mark backward instead.  If UNMARK is non-nil, remove
691 the mark instead.  The difference between N and the actual number of
692 articles marked is returned."
693   (interactive "p")
694   (let ((backward (< n 0))
695         (n (abs n)))
696     (while (and
697             (> n 0)
698             (progn
699               (gnus-summary-set-agent-mark
700                (gnus-summary-article-number) unmark)
701               (zerop (gnus-summary-next-subject (if backward -1 1) nil t))))
702       (setq n (1- n)))
703     (when (/= 0 n)
704       (gnus-message 7 "No more articles"))
705     (gnus-summary-recenter)
706     (gnus-summary-position-point)
707     n))
708
709 (defun gnus-agent-unmark-article (n)
710   "Remove the downloadable mark from the next N articles.
711 If N is negative, unmark backward instead.  The difference between N and
712 the actual number of articles unmarked is returned."
713   (interactive "p")
714   (gnus-agent-mark-article n t))
715
716 (defun gnus-agent-toggle-mark (n)
717   "Toggle the downloadable mark from the next N articles.
718 If N is negative, toggle backward instead.  The difference between N and
719 the actual number of articles toggled is returned."
720   (interactive "p")
721   (gnus-agent-mark-article n 'toggle))
722
723 (defun gnus-summary-set-agent-mark (article &optional unmark)
724   "Mark ARTICLE as downloadable.  If UNMARK is nil, article is marked.
725 When UNMARK is t, the article is unmarked.  For any other value, the
726 article's mark is toggled."
727   (let ((unmark (cond ((eq nil unmark)
728                        nil)
729                       ((eq t unmark)
730                        t)
731                       (t
732                        (memq article gnus-newsgroup-downloadable)))))
733     (gnus-summary-update-mark
734     (if unmark
735          (progn
736           (setq gnus-newsgroup-downloadable
737                 (delq article gnus-newsgroup-downloadable))
738            (gnus-article-mark article))
739        (progn
740       (setq gnus-newsgroup-downloadable
741                (gnus-add-to-sorted-list gnus-newsgroup-downloadable article))
742          gnus-downloadable-mark)
743        )
744      'unread)))
745
746 (defun gnus-agent-get-undownloaded-list ()
747   "Construct list of articles that have not been downloaded."
748   (let ((gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name)))
749     (when (set (make-local-variable 'gnus-newsgroup-agentized) (gnus-agent-method-p gnus-command-method))
750       (let* ((alist (gnus-agent-load-alist gnus-newsgroup-name))
751             (headers gnus-newsgroup-headers)
752             (undownloaded (list nil))
753             (tail undownloaded))
754         (while (and alist headers)
755           (let ((a (caar alist))
756                 (h (mail-header-number (car headers))))
757             (cond ((< a h)
758                    (pop alist)) ; ignore IDs in the alist that are not being displayed in the summary
759                   ((> a h)
760                    (pop headers)) ; ignore headers that are not in the alist as these should be fictious (see nnagent-retrieve-headers).
761                   ((cdar alist)
762                    (pop alist)
763                    (pop headers)
764                    nil; ignore already downloaded
765                    )
766                   (t
767                    (pop alist)
768                    (pop headers)
769                    (gnus-agent-append-to-list tail a)))))
770         (setq gnus-newsgroup-undownloaded (cdr undownloaded))))))
771
772 (defun gnus-agent-catchup ()
773   "Mark all undownloaded articles as read."
774   (interactive)
775   (save-excursion
776     (while gnus-newsgroup-undownloaded
777       (gnus-summary-mark-article
778        (pop gnus-newsgroup-undownloaded) gnus-catchup-mark)))
779   (gnus-summary-position-point))
780
781 (defun gnus-agent-summary-fetch-series ()
782   (interactive)
783   (when gnus-newsgroup-processable
784     (setq gnus-newsgroup-downloadable
785           (let* ((dl gnus-newsgroup-downloadable)
786                  (gnus-newsgroup-downloadable (sort gnus-newsgroup-processable '<))
787                  (fetched-articles (gnus-agent-summary-fetch-group)))
788             (dolist (article fetched-articles)
789               (gnus-summary-remove-process-mark article))
790             (gnus-sorted-ndifference dl fetched-articles)))))
791
792 (defun gnus-agent-summary-fetch-group (&optional all)
793   "Fetch the downloadable articles in the group.
794 Optional arg ALL, if non-nil, means to fetch all articles."
795   (interactive "P")
796   (let ((articles
797          (if all gnus-newsgroup-articles
798            gnus-newsgroup-downloadable))
799         (gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name))
800         (state gnus-plugged)
801         fetched-articles)
802     (unwind-protect
803         (progn
804           (unless state
805             (gnus-agent-toggle-plugged t))
806           (unless articles
807             (error "No articles to download"))
808           (gnus-agent-with-fetch
809             (setq gnus-newsgroup-undownloaded
810                   (gnus-sorted-ndifference gnus-newsgroup-undownloaded
811                                            (setq fetched-articles (gnus-agent-fetch-articles gnus-newsgroup-name articles)))))
812           (save-excursion
813
814 (dolist (article articles)
815               (setq gnus-newsgroup-downloadable
816                     (delq article gnus-newsgroup-downloadable))
817               (if gnus-agent-mark-unread-after-downloaded
818                   (gnus-summary-mark-article article gnus-unread-mark))
819               (when (gnus-summary-goto-subject article nil t)
820                 (gnus-summary-update-download-mark article)))))
821       (when (and (not state)
822                  gnus-plugged)
823         (gnus-agent-toggle-plugged nil)))
824     fetched-articles))
825
826 (defun gnus-agent-fetch-selected-article ()
827   "Fetch the current article as it is selected.
828 This can be added to `gnus-select-article-hook' or
829 `gnus-mark-article-hook'."
830   (let ((gnus-command-method gnus-current-select-method))
831     (when (and gnus-plugged (gnus-agent-method-p gnus-command-method))
832       (when (gnus-agent-fetch-articles
833              gnus-newsgroup-name
834              (list gnus-current-article))
835         (setq gnus-newsgroup-undownloaded
836               (delq gnus-current-article gnus-newsgroup-undownloaded))
837         (gnus-summary-update-article-line
838          gnus-current-article
839          (gnus-summary-article-header gnus-current-article))))))
840
841 ;;;
842 ;;; Internal functions
843 ;;;
844
845 (defun gnus-agent-save-active (method)
846   (gnus-agent-save-active-1 method 'gnus-active-to-gnus-format))
847
848 (defun gnus-agent-save-active-1 (method function)
849   (when (gnus-agent-method-p method)
850     (let* ((gnus-command-method method)
851            (new (gnus-make-hashtable (count-lines (point-min) (point-max))))
852            (file (gnus-agent-lib-file "active")))
853       (funcall function nil new)
854       (gnus-agent-write-active file new)
855       (erase-buffer)
856       (nnheader-insert-file-contents file))))
857
858 (defun gnus-agent-write-active (file new)
859   (let ((orig (gnus-make-hashtable (count-lines (point-min) (point-max))))
860         (file (gnus-agent-lib-file "active"))
861         elem osym)
862     (when (file-exists-p file)
863       (with-temp-buffer
864         (nnheader-insert-file-contents file)
865         (gnus-active-to-gnus-format nil orig))
866       (mapatoms
867        (lambda (sym)
868          (when (and sym (boundp sym))
869            (if (and (boundp (setq osym (intern (symbol-name sym) orig)))
870                     (setq elem (symbol-value osym)))
871                (progn
872                  (if (and (integerp (car (symbol-value sym)))
873                           (> (car elem) (car (symbol-value sym))))
874                      (setcar elem (car (symbol-value sym))))
875                  (if (integerp (cdr (symbol-value sym)))
876                      (setcdr elem (cdr (symbol-value sym)))))
877              (set (intern (symbol-name sym) orig) (symbol-value sym)))))
878        new))
879     (gnus-make-directory (file-name-directory file))
880     (let ((nnmail-active-file-coding-system gnus-agent-file-coding-system))
881       ;; The hashtable contains real names of groups,  no more prefix
882       ;; removing, so set `full' to `t'.
883       (gnus-write-active-file file orig t))))
884
885 (defun gnus-agent-save-groups (method)
886   (gnus-agent-save-active-1 method 'gnus-groups-to-gnus-format))
887
888 (defun gnus-agent-save-group-info (method group active)
889   (when (gnus-agent-method-p method)
890     (let* ((gnus-command-method method)
891            (coding-system-for-write nnheader-file-coding-system)
892            (file-name-coding-system nnmail-pathname-coding-system)
893            (file (gnus-agent-lib-file "active"))
894            oactive-min)
895       (gnus-make-directory (file-name-directory file))
896       (with-temp-file file
897         ;; Emacs got problem to match non-ASCII group in multibyte buffer.
898         (mm-disable-multibyte)
899         (when (file-exists-p file)
900           (nnheader-insert-file-contents file))
901         (goto-char (point-min))
902         (when (re-search-forward
903                (concat "^" (regexp-quote group) " ") nil t)
904           (save-excursion
905             (read (current-buffer))                      ;; max
906             (setq oactive-min (read (current-buffer))))  ;; min
907           (gnus-delete-line))
908         (insert (format "%S %d %d y\n" (intern group)
909                         (cdr active)
910                         (or oactive-min (car active))))
911         (goto-char (point-max))
912         (while (search-backward "\\." nil t)
913           (delete-char 1))))))
914
915 (defun gnus-agent-group-path (group)
916   "Translate GROUP into a path."
917   (if nnmail-use-long-file-names
918       (gnus-group-real-name group)
919     (nnheader-translate-file-chars
920      (nnheader-replace-chars-in-string
921       (nnheader-replace-duplicate-chars-in-string
922        (nnheader-replace-chars-in-string
923         (gnus-group-real-name group)
924         ?/ ?_)
925        ?. ?_)
926       ?. ?/))))
927
928 (defun gnus-agent-get-function (method)
929   (if (gnus-online method)
930       (car method)
931     (require 'nnagent)
932     'nnagent))
933
934 ;;; History functions
935
936 (defun gnus-agent-history-buffer ()
937   (cdr (assoc (gnus-agent-method) gnus-agent-history-buffers)))
938
939 (defun gnus-agent-open-history ()
940   (save-excursion
941     (push (cons (gnus-agent-method)
942                 (set-buffer (gnus-get-buffer-create
943                              (format " *Gnus agent %s history*"
944                                      (gnus-agent-method)))))
945           gnus-agent-history-buffers)
946     (mm-disable-multibyte) ;; everything is binary
947     (erase-buffer)
948     (insert "\n")
949     (let ((file (gnus-agent-lib-file "history")))
950       (when (file-exists-p file)
951         (nnheader-insert-file-contents file))
952       (set (make-local-variable 'gnus-agent-file-name) file))))
953
954 (defun gnus-agent-close-history ()
955   (when (gnus-buffer-live-p gnus-agent-current-history)
956     (kill-buffer gnus-agent-current-history)
957     (setq gnus-agent-history-buffers
958           (delq (assoc (gnus-agent-method) gnus-agent-history-buffers)
959                 gnus-agent-history-buffers))))
960
961 ;;;
962 ;;; Fetching
963 ;;;
964
965 (defun gnus-agent-fetch-articles (group articles)
966   "Fetch ARTICLES from GROUP and put them into the Agent."
967   (when articles
968     (gnus-agent-load-alist group)
969     (let* ((alist   gnus-agent-article-alist)
970            (headers (if (< (length articles) 2) nil gnus-newsgroup-headers))
971            (selected-sets (list nil))
972            (current-set-size 0)
973            article
974            header-number)
975       ;; Check each article
976       (while (setq article (pop articles))
977         ;; Skip alist entries preceeding this article
978         (while (> article (or (caar alist) (1+ article)))
979           (setq alist (cdr alist)))
980
981         ;; Prune off articles that we have already fetched.
982         (unless (and (eq article (caar alist))
983                      (cdar alist))
984           ;; Skip headers preceeding this article
985           (while (> article 
986                     (setq header-number
987                           (let* ((header (car headers)))
988                             (if header
989                                 (mail-header-number header)
990                               (1+ article)))))
991             (setq headers (cdr headers)))
992
993           ;; Add this article to the current set
994           (setcar selected-sets (cons article (car selected-sets)))
995
996           ;; Update the set size, when the set is too large start a
997           ;; new one.  I do this after adding the article as I want at
998           ;; least one article in each set.
999           (when (< gnus-agent-max-fetch-size
1000                    (setq current-set-size (+ current-set-size (if (= header-number article)
1001                                                                   (mail-header-chars (car headers))
1002                                                                 0))))
1003             (setcar selected-sets (nreverse (car selected-sets)))
1004             (setq selected-sets (cons nil selected-sets)
1005                   current-set-size 0))))
1006
1007       (when (or (cdr selected-sets) (car selected-sets))
1008         (let* ((fetched-articles (list nil))
1009                (tail-fetched-articles fetched-articles)
1010                (dir (concat
1011                      (gnus-agent-directory)
1012                      (gnus-agent-group-path group) "/"))
1013                (date (time-to-days (current-time)))
1014                (case-fold-search t)
1015                pos crosses id)
1016
1017           (setcar selected-sets (nreverse (car selected-sets)))
1018           (setq selected-sets (nreverse selected-sets))
1019
1020           (gnus-make-directory dir)
1021           (gnus-message 7 "Fetching articles for %s..." group)
1022           
1023           (unwind-protect
1024               (while (setq articles (pop selected-sets))
1025                 ;; Fetch the articles from the backend.
1026                 (if (gnus-check-backend-function 'retrieve-articles group)
1027                     (setq pos (gnus-retrieve-articles articles group))
1028                   (with-temp-buffer
1029                     (let (article)
1030                       (while (setq article (pop articles))
1031                         (gnus-message 10 "Fetching article %s for %s..."
1032                                       article group)
1033                         (when (or
1034                                (gnus-backlog-request-article group article
1035                                                              nntp-server-buffer)
1036                                (gnus-request-article article group))
1037                           (goto-char (point-max))
1038                           (push (cons article (point)) pos)
1039                           (insert-buffer-substring nntp-server-buffer)))
1040                       (copy-to-buffer nntp-server-buffer (point-min) (point-max))
1041                       (setq pos (nreverse pos)))))
1042                 ;; Then save these articles into the Agent.
1043                 (save-excursion
1044                   (set-buffer nntp-server-buffer)
1045                   (while pos
1046                     (narrow-to-region (cdar pos) (or (cdadr pos) (point-max)))
1047                     (goto-char (point-min))
1048                     (unless (eobp) ;; Don't save empty articles.
1049                       (when (search-forward "\n\n" nil t)
1050                         (when (search-backward "\nXrefs: " nil t)
1051                           ;; Handle cross posting.
1052                           (goto-char (match-end 0)) ; move to end of header name
1053                           (skip-chars-forward "^ ") ; skip server name
1054                           (skip-chars-forward " ")
1055                           (setq crosses nil)
1056                           (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) *")
1057                             (push (cons (buffer-substring (match-beginning 1)
1058                                                           (match-end 1))
1059                                         (string-to-int (buffer-substring (match-beginning 2)
1060                                                                          (match-end 2))))
1061                                   crosses)
1062                             (goto-char (match-end 0)))
1063                           (gnus-agent-crosspost crosses (caar pos) date)))
1064                       (goto-char (point-min))
1065                       (if (not (re-search-forward
1066                                 "^Message-ID: *<\\([^>\n]+\\)>" nil t))
1067                           (setq id "No-Message-ID-in-article")
1068                         (setq id (buffer-substring (match-beginning 1) (match-end 1))))
1069                       (let ((coding-system-for-write
1070                              gnus-agent-file-coding-system))
1071                         (write-region (point-min) (point-max)
1072                                       (concat dir (number-to-string (caar pos)))
1073                                       nil 'silent))
1074
1075                       (gnus-agent-append-to-list tail-fetched-articles (caar pos)))
1076                     (widen)
1077                     (pop pos))))
1078
1079             (gnus-agent-save-alist group (cdr fetched-articles) date))
1080           (cdr fetched-articles))))))
1081
1082 (defun gnus-agent-crosspost (crosses article &optional date)
1083   (setq date (or date t))
1084
1085   (let (gnus-agent-article-alist group alist beg end)
1086     (save-excursion
1087       (set-buffer gnus-agent-overview-buffer)
1088       (when (nnheader-find-nov-line article)
1089         (forward-word 1)
1090         (setq beg (point))
1091         (setq end (progn (forward-line 1) (point)))))
1092     (while crosses
1093       (setq group (caar crosses))
1094       (unless (setq alist (assoc group gnus-agent-group-alist))
1095         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
1096               gnus-agent-group-alist))
1097       (setcdr alist (cons (cons (cdar crosses) date) (cdr alist)))
1098       (save-excursion
1099         (set-buffer (gnus-get-buffer-create (format " *Gnus agent overview %s*"
1100                                                     group)))
1101         (when (= (point-max) (point-min))
1102           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
1103           (ignore-errors
1104             (nnheader-insert-file-contents
1105              (gnus-agent-article-name ".overview" group))))
1106         (nnheader-find-nov-line (string-to-number (cdar crosses)))
1107         (insert (string-to-number (cdar crosses)))
1108         (insert-buffer-substring gnus-agent-overview-buffer beg end)
1109         (gnus-agent-check-overview-buffer))
1110       (pop crosses))))
1111
1112 (defun gnus-agent-check-overview-buffer (&optional buffer)
1113   "Check the overview file given for sanity.
1114 In particular, checks that the file is sorted by article number
1115 and that there are no duplicates."
1116   (let ((prev-num -1))
1117     (save-excursion
1118       (when buffer
1119         (set-buffer buffer))
1120       (save-restriction
1121         (widen)
1122         (goto-char (point-min))
1123
1124         (while (< (point) (point-max))
1125           (let ((p (point))
1126                 (cur (condition-case nil
1127                          (read (current-buffer))
1128                        (error nil))))
1129             (cond
1130              ((or (not (integerp cur))
1131                   (not (eq (char-after) ?\t)))
1132               (gnus-message 1
1133                             "Overview buffer contains garbage '%s'."
1134                             (buffer-substring
1135                              p (gnus-point-at-eol))))
1136              ((= cur prev-num)
1137               (gnus-message 1
1138                             "Duplicate overview line for %d" cur)
1139               (delete-region (point) (progn (forward-line 1) (point))))
1140              ((< cur 0)
1141               (gnus-message 1 "Junk article number %d" cur)
1142               (delete-region (point) (progn (forward-line 1) (point))))
1143              ((< cur prev-num)
1144               (sort-numeric-fields 1 (point-min) (point-max))
1145               (goto-char (point-min))
1146               (setq prev-num -1)
1147               (gnus-message 1 "Overview buffer not sorted!"))
1148              (t
1149               (setq prev-num cur)))
1150             (forward-line 1)))))))
1151
1152 (defun gnus-agent-flush-cache ()
1153   (save-excursion
1154     (while gnus-agent-buffer-alist
1155       (set-buffer (cdar gnus-agent-buffer-alist))
1156       (let ((coding-system-for-write
1157              gnus-agent-file-coding-system))
1158         (write-region (point-min) (point-max)
1159                       (gnus-agent-article-name ".overview"
1160                                                (caar gnus-agent-buffer-alist))
1161                       nil 'silent))
1162       (pop gnus-agent-buffer-alist))
1163     (while gnus-agent-group-alist
1164       (with-temp-file (gnus-agent-article-name ".agentview" (caar gnus-agent-group-alist))
1165         (princ (cdar gnus-agent-group-alist))
1166         (insert "\n")
1167         (princ 1 (current-buffer))
1168         (insert "\n"))
1169       (pop gnus-agent-group-alist))))
1170
1171 (defun gnus-agent-fetch-headers (group &optional force)
1172   "Fetch interesting headers into the agent.  The group's overview
1173 file will be updated to include the headers while a list of available
1174 article numbers will be returned."
1175   (let* ((fetch-all (and gnus-agent-consider-all-articles
1176                          ;; Do not fetch all headers if the predicate
1177                          ;; implies that we only consider unread articles.
1178                          (not (gnus-predicate-implies-unread
1179                                (or (gnus-group-find-parameter
1180                                     group 'agent-predicate t)
1181                                    (cadr (gnus-group-category group)))))))
1182          (articles (if fetch-all
1183                        (gnus-uncompress-range (gnus-active group))
1184                      (gnus-list-of-unread-articles group)))
1185          (gnus-decode-encoded-word-function 'identity)
1186          (file (gnus-agent-article-name ".overview" group))
1187          gnus-agent-cache)
1188
1189     (unless fetch-all
1190       ;; Add articles with marks to the list of article headers we want to
1191       ;; fetch.  Don't fetch articles solely on the basis of a recent or seen
1192       ;; mark, but do fetch recent or seen articles if they have other, more
1193       ;; interesting marks.  (We have to fetch articles with boring marks
1194       ;; because otherwise the agent will remove their marks.)
1195       (dolist (arts (gnus-info-marks (gnus-get-info group)))
1196         (unless (memq (car arts) '(seen recent killed cache))
1197           (setq articles (gnus-range-add articles (cdr arts)))))
1198       (setq articles (sort (gnus-uncompress-sequence articles) '<)))
1199
1200     ;; At this point, I have the list of articles to consider for fetching.  
1201     ;; This is the list that I'll return to my caller. Some of these articles may have already 
1202     ;; been fetched.  That's OK as the fetch article code will filter those out.
1203     ;; Internally, I'll filter this list to just those articles whose headers need to be fetched.
1204     (let ((articles articles))
1205       ;; Remove known articles.
1206       (when (gnus-agent-load-alist group)
1207         ;; Remove articles marked as downloaded.
1208         (if fetch-all
1209             ;; I want to fetch all headers in the active range.  
1210             ;; Therefore, exclude only those headers that are in the article alist.
1211             ;; NOTE: This is probably NOT what I want to do after agent expiration in this group.
1212             (setq articles (gnus-agent-uncached-articles articles group))
1213
1214           ;; I want to only fetch those headers that have never been fetched. 
1215           ;; Therefore, exclude all headers that are, or WERE, in the article alist.
1216           (let ((low (1+ (caar (last gnus-agent-article-alist))))
1217                 (high (cdr (gnus-active group))))
1218             ;; Low can be greater than High when the same group is fetched twice
1219             ;; in the same session {The first fetch will fill the article alist 
1220             ;; such that (last gnus-agent-article-alist) equals (cdr (gnus-active group))}.  
1221             ;; The addition of one(the 1+ above) then forces Low to be greater than High.  
1222             ;; When this happens, gnus-list-range-intersection returns nil which indicates 
1223             ;; that no headers need to be fetched. -- Kevin
1224             (setq articles (gnus-list-range-intersection
1225                             articles (list (cons low high)))))))
1226       (save-excursion
1227         (set-buffer nntp-server-buffer)
1228
1229         (if articles
1230             (progn
1231               (gnus-message 7 "Fetching headers for %s..." group)
1232
1233               ;; Fetch them.
1234               (gnus-make-directory (nnheader-translate-file-chars
1235                                     (file-name-directory file) t))
1236
1237               (unless (eq 'nov (gnus-retrieve-headers articles group))
1238                 (nnvirtual-convert-headers))
1239               (gnus-agent-check-overview-buffer)
1240               ;; Move these headers to the overview buffer so that gnus-agent-braid-nov can merge them
1241               ;; with the contents of FILE.
1242               (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
1243               (when (file-exists-p file)
1244                 (gnus-agent-braid-nov group articles file))
1245               (let ((coding-system-for-write
1246                      gnus-agent-file-coding-system))
1247                 (gnus-agent-check-overview-buffer)
1248                 (write-region (point-min) (point-max) file nil 'silent))
1249               (gnus-agent-save-alist group articles nil)
1250               articles)
1251           (ignore-errors
1252             (erase-buffer)
1253             (nnheader-insert-file-contents file))))
1254       )
1255     articles))
1256
1257 (defsubst gnus-agent-copy-nov-line (article)
1258   (let (art b e)
1259     (set-buffer gnus-agent-overview-buffer)
1260     (while (and (not (eobp))
1261                 (< (setq art (read (current-buffer))) article))
1262       (forward-line 1))
1263     (beginning-of-line)
1264     (if (or (eobp)
1265             (not (eq article art)))
1266         (set-buffer nntp-server-buffer)
1267       (setq b (point))
1268       (setq e (progn (forward-line 1) (point)))
1269       (set-buffer nntp-server-buffer)
1270       (insert-buffer-substring gnus-agent-overview-buffer b e))))
1271
1272 (defun gnus-agent-braid-nov (group articles file)
1273   "Merges the article headers identified by ARTICLES from gnus-agent-overview-buffer with the contents
1274 of FILE placing the combined headers in nntp-server-buffer."
1275   (let (start last)
1276     (set-buffer gnus-agent-overview-buffer)
1277     (goto-char (point-min))
1278     (set-buffer nntp-server-buffer)
1279     (erase-buffer)
1280     (nnheader-insert-file-contents file)
1281     (goto-char (point-max))
1282     (forward-line -1)
1283     (unless (looking-at "[0-9]+\t")
1284       ;; Remove corrupted lines
1285       (gnus-message 1 "Overview %s is corrupted. Removing corrupted lines..." file)
1286       (goto-char (point-min))
1287       (while (not (eobp))
1288         (if (looking-at "[0-9]+\t")
1289             (forward-line 1)
1290           (delete-region (point) (progn (forward-line 1) (point)))))
1291       (forward-line -1))
1292     (unless (or (= (point-min) (point-max))
1293                 (< (setq last (read (current-buffer))) (car articles)))
1294       ;; We do it the hard way.
1295       (when (nnheader-find-nov-line (car articles))
1296         ;; Replacing existing NOV entry
1297         (delete-region (point) (progn (forward-line 1) (point))))
1298       (gnus-agent-copy-nov-line (pop articles))
1299
1300       (ignore-errors
1301         (while articles
1302           (while (let ((art (read (current-buffer))))
1303                    (cond ((< art (car articles))
1304                           (forward-line 1)
1305                           t)
1306                          ((= art (car articles))
1307                           (beginning-of-line)
1308                           (delete-region (point) (progn (forward-line 1) (point)))
1309                           nil)
1310                          (t
1311                           (beginning-of-line)
1312                           nil))))
1313             
1314           (gnus-agent-copy-nov-line (pop articles)))))
1315
1316     ;; Copy the rest lines
1317     (set-buffer nntp-server-buffer)
1318     (goto-char (point-max))
1319     (when articles
1320       (when last
1321         (set-buffer gnus-agent-overview-buffer)
1322         (ignore-errors
1323           (while (<= (read (current-buffer)) last)
1324             (forward-line 1)))
1325         (beginning-of-line)
1326         (setq start (point))
1327         (set-buffer nntp-server-buffer))
1328       (insert-buffer-substring gnus-agent-overview-buffer start))))
1329
1330 (eval-when-compile ; Keeps the compiler from warning about the free variable in gnus-agent-read-agentview
1331   (defvar gnus-agent-read-agentview))
1332
1333 (defun gnus-agent-load-alist (group)
1334   (let ((gnus-agent-read-agentview group)) ; Binds free variable that's used in gnus-agent-read-agentview
1335     "Load the article-state alist for GROUP."
1336     (setq gnus-agent-article-alist
1337           (gnus-cache-file-contents
1338            (gnus-agent-article-name ".agentview" group)
1339            'gnus-agent-file-loading-cache
1340            'gnus-agent-read-agentview))))
1341
1342 ;; Save format may be either 1 or 2.  Two is the new, compressed format that is still being tested.  Format 1 is uncompressed but known to be reliable.
1343 (defconst gnus-agent-article-alist-save-format 2)
1344
1345 (defun gnus-agent-read-agentview (file)
1346   "Load FILE and do a `read' there."
1347   (with-temp-buffer
1348     (ignore-errors
1349       (nnheader-insert-file-contents file)
1350       (goto-char (point-min))
1351       (let ((alist (read (current-buffer)))
1352             (version (condition-case nil (read (current-buffer))
1353                        (end-of-file 0)))
1354             changed-version)
1355
1356         (cond ((= version 0)
1357                (let ((inhibit-quit t)
1358                      entry)
1359                  (gnus-agent-open-history)
1360                  (set-buffer (gnus-agent-history-buffer))
1361                  (goto-char (point-min))
1362                  (while (not (eobp))
1363                    (if (and (looking-at
1364                              "[^\t\n]+\t\\([0-9]+\\)\t\\([^ \n]+\\) \\([0-9]+\\)")
1365                             (string= (match-string 2)
1366                                      gnus-agent-read-agentview)
1367                             (setq entry (assoc (string-to-number (match-string 3)) alist)))
1368                        (setcdr entry (string-to-number (match-string 1))))
1369                    (forward-line 1))
1370                  (gnus-agent-close-history)
1371                  (setq changed-version t)))
1372               ((= version 1)
1373                (setq changed-version (not (= 1 gnus-agent-article-alist-save-format))))
1374               ((= version 2)
1375                (let (uncomp)
1376                  (mapcar (lambda (comp-list)
1377                            (let ((state (car comp-list))
1378                                  (sequence (gnus-uncompress-sequence (cdr comp-list))))
1379                              (mapcar (lambda (article-id)
1380                                        (setq uncomp (cons (cons article-id state) uncomp))) sequence))) alist)
1381                  (setq alist (sort uncomp (lambda (first second) (< (car first) (car second)))))
1382                  )
1383                ))
1384         (when changed-version
1385           (let ((gnus-agent-article-alist alist))
1386             (gnus-agent-save-alist gnus-agent-read-agentview)))
1387         alist))))
1388
1389 (defun gnus-agent-save-alist (group &optional articles state dir)
1390   "Save the article-state alist for GROUP."
1391   (let* ((file-name-coding-system nnmail-pathname-coding-system)
1392          (prev (cons nil gnus-agent-article-alist))
1393          (all prev)
1394          print-level print-length item article)
1395     (while (setq article (pop articles))
1396       (while (and (cdr prev)
1397                   (< (caadr prev) article))
1398         (setq prev (cdr prev)))
1399       (cond
1400        ((not (cdr prev))
1401         (setcdr prev (list (cons article state))))
1402        ((> (caadr prev) article)
1403         (setcdr prev (cons (cons article state) (cdr prev))))
1404        ((= (caadr prev) article)
1405         (setcdr (cadr prev) state)))
1406       (setq prev (cdr prev)))
1407     (setq gnus-agent-article-alist (cdr all))
1408     (if dir
1409         (gnus-make-directory dir)
1410       (gnus-make-directory (gnus-agent-article-name "" group)))
1411     (with-temp-file (if dir
1412                         (expand-file-name ".agentview" dir)
1413                       (gnus-agent-article-name ".agentview" group))
1414       (cond ((eq gnus-agent-article-alist-save-format 1)
1415              (princ gnus-agent-article-alist (current-buffer)))
1416             ((eq gnus-agent-article-alist-save-format 2)
1417              (let ((compressed nil))
1418                (mapcar (lambda (pair)
1419                          (let* ((article-id (car pair))
1420                                 (day-of-download (cdr pair))
1421                                 (comp-list (assq day-of-download compressed)))
1422                            (if comp-list
1423                                (setcdr comp-list (cons article-id (cdr comp-list)))
1424                              (setq compressed (cons (list day-of-download article-id) compressed)))
1425                            nil)) gnus-agent-article-alist)
1426                (mapcar (lambda (comp-list) (setcdr comp-list (gnus-compress-sequence (nreverse (cdr comp-list))))) compressed)
1427                (princ compressed (current-buffer))
1428                )
1429              )
1430             )
1431       (insert "\n")
1432       (princ gnus-agent-article-alist-save-format (current-buffer))
1433       (insert "\n"))))
1434
1435 (defun gnus-agent-article-name (article group)
1436   (expand-file-name (if (stringp article) article (string-to-number article))
1437                     (file-name-as-directory
1438                      (expand-file-name (gnus-agent-group-path group)
1439                                        (gnus-agent-directory)))))
1440
1441 (defun gnus-agent-batch-confirmation (msg)
1442   "Show error message and return t."
1443   (gnus-message 1 msg)
1444   t)
1445
1446 ;;;###autoload
1447 (defun gnus-agent-batch-fetch ()
1448   "Start Gnus and fetch session."
1449   (interactive)
1450   (gnus)
1451   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1452     (gnus-agent-fetch-session))
1453   (gnus-group-exit))
1454
1455 (defun gnus-agent-fetch-session ()
1456   "Fetch all articles and headers that are eligible for fetching."
1457   (interactive)
1458   (unless gnus-agent-covered-methods
1459     (error "No servers are covered by the Gnus agent"))
1460   (unless gnus-plugged
1461     (error "Can't fetch articles while Gnus is unplugged"))
1462   (let ((methods gnus-agent-covered-methods)
1463         groups group gnus-command-method)
1464     (save-excursion
1465       (while methods
1466         (condition-case err
1467             (progn
1468               (setq gnus-command-method (car methods))
1469               (when (and (or (gnus-server-opened gnus-command-method)
1470                              (gnus-open-server gnus-command-method))
1471                          (gnus-online gnus-command-method))
1472                 (setq groups (gnus-groups-from-server (car methods)))
1473                 (gnus-agent-with-fetch
1474                   (while (setq group (pop groups))
1475                     (when (<= (gnus-group-level group) gnus-agent-handle-level)
1476                       (gnus-agent-fetch-group-1 group gnus-command-method))))))
1477           (error
1478            (unless (funcall gnus-agent-confirmation-function
1479                             (format "Error %s.  Continue? " (cdr err)))
1480              (error "Cannot fetch articles into the Gnus agent")))
1481           (quit
1482            (unless (funcall gnus-agent-confirmation-function
1483                             (format "Quit fetching session %s.  Continue? "
1484                                     (cdr err)))
1485              (signal 'quit "Cannot fetch articles into the Gnus agent"))))
1486         (pop methods))
1487       (run-hooks 'gnus-agent-fetch-hook)
1488       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
1489
1490 (defun gnus-agent-fetch-group-1 (group method)
1491   "Fetch GROUP."
1492   (let ((gnus-command-method method)
1493         (gnus-newsgroup-name group)
1494         (gnus-newsgroup-dependencies gnus-newsgroup-dependencies)
1495         (gnus-newsgroup-headers gnus-newsgroup-headers)
1496         (gnus-newsgroup-scored gnus-newsgroup-scored)
1497         (gnus-use-cache gnus-use-cache)
1498         (gnus-summary-expunge-below gnus-summary-expunge-below)
1499         (gnus-summary-mark-below gnus-summary-mark-below)
1500         (gnus-orphan-score gnus-orphan-score)
1501         ;; Maybe some other gnus-summary local variables should also
1502         ;; be put here.
1503
1504         gnus-headers
1505         gnus-score
1506         articles arts
1507         category predicate info marks score-param
1508         )
1509     (unless (gnus-check-group group)
1510       (error "Can't open server for %s" group))
1511
1512     ;; Fetch headers.
1513     (when (or gnus-newsgroup-active
1514               (gnus-active group)
1515               (gnus-activate-group group))
1516       (let ((marked-articles gnus-newsgroup-downloadable))
1517         ;; Identify the articles marked for download
1518         (unless gnus-newsgroup-active ;; This needs to be a
1519           ;; gnus-summary local variable
1520           ;; that is NOT bound to any
1521           ;; value above (It's global
1522           ;; value should default to nil).
1523           (dolist (mark gnus-agent-download-marks)
1524             (let ((arts (cdr (assq mark (gnus-info-marks
1525                                          (setq info (gnus-get-info group)))))))
1526               (when arts
1527                 (setq marked-articles (nconc (gnus-uncompress-range arts)
1528                                              marked-articles))
1529                 ))))
1530         (setq marked-articles (sort marked-articles '<))
1531
1532         ;; Fetch any new articles from the server
1533         (setq articles (gnus-agent-fetch-headers group))
1534
1535         ;; Merge new articles with marked
1536         (setq articles (sort (append marked-articles articles) '<))
1537
1538         (when articles
1539           ;; Parse them and see which articles we want to fetch.
1540           (setq gnus-newsgroup-dependencies
1541                 (or gnus-newsgroup-dependencies
1542                     (make-vector (length articles) 0)))
1543
1544           (setq gnus-newsgroup-headers
1545                 (or gnus-newsgroup-headers
1546                     (gnus-get-newsgroup-headers-xover articles nil nil
1547                                                       group)))
1548           ;; `gnus-agent-overview-buffer' may be killed for
1549           ;; timeout reason.  If so, recreate it.
1550           (gnus-agent-create-buffer)
1551
1552           ;; Figure out how to select articles in this group
1553           (setq category (gnus-group-category group))
1554
1555           (setq predicate
1556                 (gnus-get-predicate
1557                  (or (gnus-group-find-parameter group 'agent-predicate t)
1558                      (cadr category))))
1559
1560           ;; If the selection predicate requires scoring, score each header
1561           (unless (memq predicate '(gnus-agent-true gnus-agent-false))
1562             (let ((score-param
1563                    (or (gnus-group-get-parameter group 'agent-score t)
1564                        (caddr category))))
1565               ;; Translate score-param into real one
1566               (cond
1567                ((not score-param))
1568                ((eq score-param 'file)
1569                 (setq score-param (gnus-all-score-files group)))
1570                ((stringp (car score-param)))
1571                (t
1572                 (setq score-param (list (list score-param)))))
1573               (when score-param
1574                 (gnus-score-headers score-param))))
1575
1576           (unless (and (eq predicate 'gnus-agent-false)
1577                        (not marked-articles))
1578             (let* ((arts (list nil))
1579                    (arts-tail arts)
1580                    (alist (gnus-agent-load-alist group))
1581                    (chunk-size 0)
1582                    (marked-articles marked-articles)
1583                    fetched-articles)
1584               (while (setq gnus-headers (pop gnus-newsgroup-headers))
1585                 (let ((num (mail-header-number gnus-headers)))
1586                   ;; Determine if this article is already in the cache
1587                   (while (and alist
1588                               (> num (caar alist)))
1589                     (setq alist (cdr alist)))
1590
1591                   (unless (and (eq num (caar alist))
1592                                (cdar alist))
1593
1594                     ;; Determine if this article was marked for download.
1595                     (while (and marked-articles
1596                                 (> num (car marked-articles)))
1597                       (setq marked-articles
1598                             (cdr marked-articles)))
1599
1600                     ;; When this article is marked, or selected by the
1601                     ;; predicate, add it to the download list
1602                     (when (or (eq num (car marked-articles))
1603                               (let ((gnus-score
1604                                      (or (cdr (assq num gnus-newsgroup-scored))
1605                                          gnus-summary-default-score)))
1606                                 (funcall predicate)))
1607                       (gnus-agent-append-to-list arts-tail num)))))
1608
1609               ;; Fetch all selected articles
1610               (when (cdr arts)
1611                 (setq gnus-newsgroup-undownloaded
1612                       (gnus-sorted-ndifference gnus-newsgroup-undownloaded
1613                                                (setq fetched-articles (gnus-agent-fetch-articles group (cdr arts)))))
1614
1615                 (let ((unfetched-articles (gnus-sorted-ndifference (cdr arts) fetched-articles)))
1616                   (if gnus-newsgroup-active
1617                       (progn
1618                         (dolist (article (cdr arts))
1619                           (setq gnus-newsgroup-downloadable
1620                                 (delq article gnus-newsgroup-downloadable))
1621                           (when (gnus-summary-goto-subject article nil t)
1622                             (gnus-summary-update-download-mark article)))
1623                         (dolist (article fetched-articles)
1624                           (if gnus-agent-mark-unread-after-downloaded
1625                               (gnus-summary-mark-article article gnus-unread-mark)))
1626                         (dolist (article unfetched-articles)
1627                           (gnus-summary-mark-article article gnus-canceled-mark)))
1628                     ;; When some, or all, of the marked articles came
1629                     ;; from the download mark.  Remove that mark.  I
1630                     ;; didn't do this earlier as I only want to remove
1631                     ;; the marks after the fetch is completed.
1632
1633                     (dolist (mark gnus-agent-download-marks)
1634                       (when (eq mark 'download)
1635                         (let ((marked-arts (assq mark (gnus-info-marks
1636                                                        (setq info (gnus-get-info group))))))
1637                           (when (cdr marked-arts)
1638                             (setq marks (delq marked-arts (gnus-info-marks info)))
1639                             (gnus-info-set-marks info marks)))))
1640                     (let ((read (gnus-info-read (or info (setq info (gnus-get-info group))))))
1641                       (gnus-info-set-read info (gnus-add-to-range read unfetched-articles)))
1642
1643                     (gnus-group-update-group group t)
1644                     (sit-for 0)
1645
1646                     (gnus-dribble-enter
1647                      (concat "(gnus-group-set-info '"
1648                              (gnus-prin1-to-string info)
1649                              ")"))))))))))))
1650
1651 ;;;
1652 ;;; Agent Category Mode
1653 ;;;
1654
1655 (defvar gnus-category-mode-hook nil
1656   "Hook run in `gnus-category-mode' buffers.")
1657
1658 (defvar gnus-category-line-format "     %(%20c%): %g\n"
1659   "Format of category lines.
1660
1661 Valid specifiers include:
1662 %c  Topic name (string)
1663 %g  The number of groups in the topic (integer)
1664
1665 General format specifiers can also be used.  See Info node
1666 `(gnus)Formatting Variables'.")
1667
1668 (defvar gnus-category-mode-line-format "Gnus: %%b"
1669   "The format specification for the category mode line.")
1670
1671 (defvar gnus-agent-short-article 100
1672   "Articles that have fewer lines than this are short.")
1673
1674 (defvar gnus-agent-long-article 200
1675   "Articles that have more lines than this are long.")
1676
1677 (defvar gnus-agent-low-score 0
1678   "Articles that have a score lower than this have a low score.")
1679
1680 (defvar gnus-agent-high-score 0
1681   "Articles that have a score higher than this have a high score.")
1682
1683
1684 ;;; Internal variables.
1685
1686 (defvar gnus-category-buffer "*Agent Category*")
1687
1688 (defvar gnus-category-line-format-alist
1689   `((?c gnus-tmp-name ?s)
1690     (?g gnus-tmp-groups ?d)))
1691
1692 (defvar gnus-category-mode-line-format-alist
1693   `((?u user-defined ?s)))
1694
1695 (defvar gnus-category-line-format-spec nil)
1696 (defvar gnus-category-mode-line-format-spec nil)
1697
1698 (defvar gnus-category-mode-map nil)
1699 (put 'gnus-category-mode 'mode-class 'special)
1700
1701 (unless gnus-category-mode-map
1702   (setq gnus-category-mode-map (make-sparse-keymap))
1703   (suppress-keymap gnus-category-mode-map)
1704
1705   (gnus-define-keys gnus-category-mode-map
1706     "q" gnus-category-exit
1707     "k" gnus-category-kill
1708     "c" gnus-category-copy
1709     "a" gnus-category-add
1710     "p" gnus-category-edit-predicate
1711     "g" gnus-category-edit-groups
1712     "s" gnus-category-edit-score
1713     "l" gnus-category-list
1714
1715     "\C-c\C-i" gnus-info-find-node
1716     "\C-c\C-b" gnus-bug))
1717
1718 (defvar gnus-category-menu-hook nil
1719   "*Hook run after the creation of the menu.")
1720
1721 (defun gnus-category-make-menu-bar ()
1722   (gnus-turn-off-edit-menu 'category)
1723   (unless (boundp 'gnus-category-menu)
1724     (easy-menu-define
1725      gnus-category-menu gnus-category-mode-map ""
1726      '("Categories"
1727        ["Add" gnus-category-add t]
1728        ["Kill" gnus-category-kill t]
1729        ["Copy" gnus-category-copy t]
1730        ["Edit predicate" gnus-category-edit-predicate t]
1731        ["Edit score" gnus-category-edit-score t]
1732        ["Edit groups" gnus-category-edit-groups t]
1733        ["Exit" gnus-category-exit t]))
1734
1735     (gnus-run-hooks 'gnus-category-menu-hook)))
1736
1737 (defun gnus-category-mode ()
1738   "Major mode for listing and editing agent categories.
1739
1740 All normal editing commands are switched off.
1741 \\<gnus-category-mode-map>
1742 For more in-depth information on this mode, read the manual
1743 \(`\\[gnus-info-find-node]').
1744
1745 The following commands are available:
1746
1747 \\{gnus-category-mode-map}"
1748   (interactive)
1749   (when (gnus-visual-p 'category-menu 'menu)
1750     (gnus-category-make-menu-bar))
1751   (kill-all-local-variables)
1752   (gnus-simplify-mode-line)
1753   (setq major-mode 'gnus-category-mode)
1754   (setq mode-name "Category")
1755   (gnus-set-default-directory)
1756   (setq mode-line-process nil)
1757   (use-local-map gnus-category-mode-map)
1758   (buffer-disable-undo)
1759   (setq truncate-lines t)
1760   (setq buffer-read-only t)
1761   (gnus-run-hooks 'gnus-category-mode-hook))
1762
1763 (defalias 'gnus-category-position-point 'gnus-goto-colon)
1764
1765 (defun gnus-category-insert-line (category)
1766   (let* ((gnus-tmp-name (format "%s" (car category)))
1767          (gnus-tmp-groups (length (cadddr category))))
1768     (beginning-of-line)
1769     (gnus-add-text-properties
1770      (point)
1771      (prog1 (1+ (point))
1772        ;; Insert the text.
1773        (eval gnus-category-line-format-spec))
1774      (list 'gnus-category gnus-tmp-name))))
1775
1776 (defun gnus-enter-category-buffer ()
1777   "Go to the Category buffer."
1778   (interactive)
1779   (gnus-category-setup-buffer)
1780   (gnus-configure-windows 'category)
1781   (gnus-category-prepare))
1782
1783 (defun gnus-category-setup-buffer ()
1784   (unless (get-buffer gnus-category-buffer)
1785     (save-excursion
1786       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
1787       (gnus-category-mode))))
1788
1789 (defun gnus-category-prepare ()
1790   (gnus-set-format 'category-mode)
1791   (gnus-set-format 'category t)
1792   (let ((alist gnus-category-alist)
1793         (buffer-read-only nil))
1794     (erase-buffer)
1795     (while alist
1796       (gnus-category-insert-line (pop alist)))
1797     (goto-char (point-min))
1798     (gnus-category-position-point)))
1799
1800 (defun gnus-category-name ()
1801   (or (intern (get-text-property (gnus-point-at-bol) 'gnus-category))
1802       (error "No category on the current line")))
1803
1804 (defun gnus-category-read ()
1805   "Read the category alist."
1806   (setq gnus-category-alist
1807         (or (gnus-agent-read-file
1808              (nnheader-concat gnus-agent-directory "lib/categories"))
1809             (list (list 'default 'short nil nil)))))
1810
1811 (defun gnus-category-write ()
1812   "Write the category alist."
1813   (setq gnus-category-predicate-cache nil
1814         gnus-category-group-cache nil)
1815   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
1816   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
1817     (prin1 gnus-category-alist (current-buffer))))
1818
1819 (defun gnus-category-edit-predicate (category)
1820   "Edit the predicate for CATEGORY."
1821   (interactive (list (gnus-category-name)))
1822   (let ((info (assq category gnus-category-alist)))
1823     (gnus-edit-form
1824      (cadr info) (format "Editing the predicate for category %s" category)
1825      `(lambda (predicate)
1826         (setcar (cdr (assq ',category gnus-category-alist)) predicate)
1827         (gnus-category-write)
1828         (gnus-category-list)))))
1829
1830 (defun gnus-category-edit-score (category)
1831   "Edit the score expression for CATEGORY."
1832   (interactive (list (gnus-category-name)))
1833   (let ((info (assq category gnus-category-alist)))
1834     (gnus-edit-form
1835      (caddr info)
1836      (format "Editing the score expression for category %s" category)
1837      `(lambda (groups)
1838         (setcar (cddr (assq ',category gnus-category-alist)) groups)
1839         (gnus-category-write)
1840         (gnus-category-list)))))
1841
1842 (defun gnus-category-edit-groups (category)
1843   "Edit the group list for CATEGORY."
1844   (interactive (list (gnus-category-name)))
1845   (let ((info (assq category gnus-category-alist)))
1846     (gnus-edit-form
1847      (cadddr info) (format "Editing the group list for category %s" category)
1848      `(lambda (groups)
1849         (setcar (nthcdr 3 (assq ',category gnus-category-alist)) groups)
1850         (gnus-category-write)
1851         (gnus-category-list)))))
1852
1853 (defun gnus-category-kill (category)
1854   "Kill the current category."
1855   (interactive (list (gnus-category-name)))
1856   (let ((info (assq category gnus-category-alist))
1857         (buffer-read-only nil))
1858     (gnus-delete-line)
1859     (setq gnus-category-alist (delq info gnus-category-alist))
1860     (gnus-category-write)))
1861
1862 (defun gnus-category-copy (category to)
1863   "Copy the current category."
1864   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
1865   (let ((info (assq category gnus-category-alist)))
1866     (push (list to (gnus-copy-sequence (cadr info))
1867                 (gnus-copy-sequence (caddr info)) nil)
1868           gnus-category-alist)
1869     (gnus-category-write)
1870     (gnus-category-list)))
1871
1872 (defun gnus-category-add (category)
1873   "Create a new category."
1874   (interactive "SCategory name: ")
1875   (when (assq category gnus-category-alist)
1876     (error "Category %s already exists" category))
1877   (push (list category 'false nil nil)
1878         gnus-category-alist)
1879   (gnus-category-write)
1880   (gnus-category-list))
1881
1882 (defun gnus-category-list ()
1883   "List all categories."
1884   (interactive)
1885   (gnus-category-prepare))
1886
1887 (defun gnus-category-exit ()
1888   "Return to the group buffer."
1889   (interactive)
1890   (kill-buffer (current-buffer))
1891   (gnus-configure-windows 'group t))
1892
1893 ;; To avoid having 8-bit characters in the source file.
1894 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
1895
1896 (defvar gnus-category-predicate-alist
1897   '((spam . gnus-agent-spam-p)
1898     (short . gnus-agent-short-p)
1899     (long . gnus-agent-long-p)
1900     (low . gnus-agent-low-scored-p)
1901     (high . gnus-agent-high-scored-p)
1902     (read . gnus-agent-read-p)
1903     (true . gnus-agent-true)
1904     (false . gnus-agent-false))
1905   "Mapping from short score predicate symbols to predicate functions.")
1906
1907 (defun gnus-agent-spam-p ()
1908   "Say whether an article is spam or not."
1909   (unless gnus-agent-spam-hashtb
1910     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
1911   (if (not (equal (mail-header-references gnus-headers) ""))
1912       nil
1913     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
1914       (prog1
1915           (gnus-gethash string gnus-agent-spam-hashtb)
1916         (gnus-sethash string t gnus-agent-spam-hashtb)))))
1917
1918 (defun gnus-agent-short-p ()
1919   "Say whether an article is short or not."
1920   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
1921
1922 (defun gnus-agent-long-p ()
1923   "Say whether an article is long or not."
1924   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
1925
1926 (defun gnus-agent-low-scored-p ()
1927   "Say whether an article has a low score or not."
1928   (< gnus-score gnus-agent-low-score))
1929
1930 (defun gnus-agent-high-scored-p ()
1931   "Say whether an article has a high score or not."
1932   (> gnus-score gnus-agent-high-score))
1933
1934 (defun gnus-agent-read-p ()
1935   "Say whether an article is read or not."
1936   (gnus-member-of-range (mail-header-number gnus-headers)
1937                         (gnus-info-read (gnus-get-info gnus-newsgroup-name))))
1938
1939 (defun gnus-category-make-function (cat)
1940   "Make a function from category CAT."
1941   (let ((func (gnus-category-make-function-1 cat)))
1942     (if (and (= (length func) 1)
1943              (symbolp (car func)))
1944         (car func)
1945       (gnus-byte-compile `(lambda () ,func)))))
1946
1947 (defun gnus-agent-true ()
1948   "Return t."
1949   t)
1950
1951 (defun gnus-agent-false ()
1952   "Return nil."
1953   nil)
1954
1955 (defun gnus-category-make-function-1 (cat)
1956   "Make a function from category CAT."
1957   (cond
1958    ;; Functions are just returned as is.
1959    ((or (symbolp cat)
1960         (gnus-functionp cat))
1961     `(,(or (cdr (assq cat gnus-category-predicate-alist))
1962            cat)))
1963    ;; More complex category.
1964    ((consp cat)
1965     `(,(cond
1966         ((memq (car cat) '(& and))
1967          'and)
1968         ((memq (car cat) '(| or))
1969          'or)
1970         ((memq (car cat) gnus-category-not)
1971          'not))
1972       ,@(mapcar 'gnus-category-make-function-1 (cdr cat))))
1973    (t
1974     (error "Unknown category type: %s" cat))))
1975
1976 (defun gnus-get-predicate (predicate)
1977   "Return the predicate for CATEGORY."
1978   (or (cdr (assoc predicate gnus-category-predicate-cache))
1979       (let ((func (gnus-category-make-function predicate)))
1980         (setq gnus-category-predicate-cache
1981               (nconc gnus-category-predicate-cache
1982                      (list (cons predicate func))))
1983         func)))
1984
1985 (defun gnus-predicate-implies-unread (predicate)
1986   "Say whether PREDICATE implies unread articles only.
1987 It is okay to miss some cases, but there must be no false positives.
1988 That is, if this function returns true, then indeed the predicate must
1989 return only unread articles."
1990   ;; Todo: make this work in more cases.
1991   (equal predicate '(not read)))
1992
1993 (defun gnus-group-category (group)
1994   "Return the category GROUP belongs to."
1995   (unless gnus-category-group-cache
1996     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
1997     (let ((cs gnus-category-alist)
1998           groups cat)
1999       (while (setq cat (pop cs))
2000         (setq groups (cadddr cat))
2001         (while groups
2002           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
2003   (or (gnus-gethash group gnus-category-group-cache)
2004       (assq 'default gnus-category-alist)))
2005
2006 (defun gnus-agent-expire (&optional articles group force)
2007   "Expire all old articles.
2008 If you want to force expiring of certain articles, this function can
2009 take ARTICLES, GROUP and FORCE parameters as well.
2010
2011 The articles on which the expiration process runs are selected as follows:
2012   if ARTICLES is null, all read and unmarked articles.
2013   if ARTICLES is t, all articles.
2014   if ARTICLES is a list, just those articles.
2015 Setting GROUP will limit expiration to that group.
2016 FORCE is equivalent to setting gnus-agent-expire-days to zero(0)."
2017   (interactive)
2018
2019   (if (or (not (eq articles t))
2020           (yes-or-no-p (concat "Are you sure that you want to expire all articles in " (if group group "every agentized group") ".")))
2021       (let ((methods (if group
2022                          (list (gnus-find-method-for-group group))
2023                        gnus-agent-covered-methods))
2024             (day (if (numberp gnus-agent-expire-days)
2025                      (- (time-to-days (current-time)) gnus-agent-expire-days)
2026                    nil))
2027             gnus-command-method sym arts pos
2028             history overview file histories elem art nov-file low info
2029             unreads marked article orig lowest highest found days)
2030         (save-excursion
2031           (setq overview (gnus-get-buffer-create " *expire overview*"))
2032           (unwind-protect
2033               (while (setq gnus-command-method (pop methods))
2034                 (when (file-exists-p (gnus-agent-lib-file "active"))
2035                   (with-temp-buffer
2036                     (nnheader-insert-file-contents (gnus-agent-lib-file "active"))
2037                     (gnus-active-to-gnus-format
2038                      gnus-command-method
2039                      (setq orig (gnus-make-hashtable
2040                                  (count-lines (point-min) (point-max))))))
2041                   (dolist (expiring-group (gnus-groups-from-server gnus-command-method))
2042                     (if (or (not group)
2043                             (equal group expiring-group))
2044                         (let* ((dir (concat
2045                                      (gnus-agent-directory)
2046                                      (gnus-agent-group-path expiring-group) "/"))
2047                                (active
2048                                 (gnus-gethash-safe expiring-group orig)))
2049                           (when active
2050                             (gnus-agent-load-alist expiring-group)
2051                             (gnus-message 5 "Expiring articles in %s" expiring-group)
2052                             (let* ((info (gnus-get-info expiring-group))
2053                                    (alist gnus-agent-article-alist)
2054                                    (specials (if alist
2055                                                  (list (caar (last alist)))))
2056                                    (unreads ;; Articles that are excluded from the expiration process
2057                                     (cond (gnus-agent-expire-all
2058                                            ;; All articles are marked read by global decree
2059                                            nil)
2060                                           ((eq articles t)
2061                                            ;; All articles are marked read by function parameter
2062                                            nil)
2063                                           ((not articles)
2064                                            ;; Unread articles are marked protected from expiration
2065                                            ;; Don't call gnus-list-of-unread-articles as it returns articles that have not been fetched into the agent.
2066                                            (ignore-errors (gnus-agent-unread-articles expiring-group)))
2067                                           (t
2068                                            ;; All articles EXCEPT those named by the caller are protected from expiration
2069                                            (gnus-sorted-difference (gnus-uncompress-range (cons (caar alist) (caar (last alist)))) (sort articles '<)))))
2070                                    (marked ;; More articles that are exluded from the expiration process
2071                                     (cond (gnus-agent-expire-all
2072                                            ;; All articles are unmarked by global decree
2073                                            nil)
2074                                           ((eq articles t)
2075                                            ;; All articles are unmarked by function parameter
2076                                            nil)
2077                                           (articles
2078                                            ;; All articles may as well be unmarked as the unreads list already names the articles we are going to keep
2079                                            nil)
2080                                           (t
2081                                            ;; Ticked and/or dormant articles are excluded from expiration
2082                                            (nconc
2083                                             (gnus-uncompress-range
2084                                              (cdr (assq 'tick (gnus-info-marks info))))
2085                                             (gnus-uncompress-range
2086                                              (cdr (assq 'dormant
2087                                                         (gnus-info-marks info))))))))
2088                                    (nov-file (concat dir ".overview"))
2089                                    (cnt 0)
2090                                    (completed -1)
2091                                    dlist
2092                                    type)
2093
2094                               ;; The normal article alist contains elements that look like (article# . fetch_date)
2095                               ;; I need to combine other information with this list.  For example, a flag indicating that a particular article MUST BE KEPT.
2096                               ;; To do this, I'm going to transform the elements to look like (article# fetch_date keep_flag NOV_entry_marker)
2097                               ;; Later, I'll reverse the process to generate the expired article alist.
2098
2099                               ;; Convert the alist elements to (article# fetch_date nil nil).
2100                               (setq dlist (mapcar (lambda (e) (list (car e) (cdr e) nil nil)) alist))
2101
2102                               ;; Convert the keep lists to elements that look like (article# nil keep_flag nil) then append it to the expanded dlist
2103                               ;; These statements are sorted by ascending precidence of the keep_flag.
2104                               (setq dlist (nconc dlist
2105                                                  (mapcar (lambda (e) (list e nil 'unread  nil)) unreads)))
2106                               (setq dlist (nconc dlist
2107                                                  (mapcar (lambda (e) (list e nil 'marked  nil)) marked)))
2108                               (setq dlist (nconc dlist
2109                                                  (mapcar (lambda (e) (list e nil 'special nil)) specials)))
2110
2111                               (set-buffer overview)
2112                               (erase-buffer)
2113                               (when (file-exists-p nov-file)
2114                                 (gnus-message 7 "gnus-agent-expire: Loading overview...")
2115                                 (nnheader-insert-file-contents nov-file)
2116                                 (goto-char (point-min))
2117                          
2118                                 (let (p)
2119                                   (while (< (setq p (point)) (point-max))
2120                                     (condition-case nil
2121                                         ;; If I successfully read an integer (the plus zero ensures a numeric type), prepend a marker entry to the list
2122                                         (push (list (+ 0 (read (current-buffer))) nil nil (set-marker (make-marker) p)) dlist)
2123                                       (error
2124                                        (gnus-message 1 "gnus-agent-expire: read error occurred when reading expression at %s in %s.  Skipping to next line." (point) nov-file)))
2125                                     ;; Whether I succeeded, or failed, it doesn't matter.  Move to the next line then try again.
2126                                     (forward-line 1)))
2127                                 (gnus-message 7 "gnus-agent-expire: Loading overview... Done"))
2128                               (set-buffer-modified-p nil)
2129
2130                               ;; At this point, all of the information is in dlist.  The only problem is that much of it is spread across multiple entries.  Sort then MERGE!!
2131                               (gnus-message 7 "gnus-agent-expire: Sorting entries... ")
2132                               (let ((special 0) ; If two entries have the same article-number then sort by ascending keep_flag.
2133                                     (marked 1)
2134                                     (unread 2))
2135                                 (setq dlist
2136                                       (sort dlist
2137                                             (lambda (a b)
2138                                               (cond ((< (nth 0 a) (nth 0 b))
2139                                                      t)
2140                                                     ((> (nth 0 a) (nth 0 b))
2141                                                      nil)
2142                                                     (t
2143                                                      (let ((a (or (symbol-value (nth 2 a)) 3))
2144                                                            (b (or (symbol-value (nth 2 b)) 3)))
2145                                                        (<= a b))))))))
2146                               (gnus-message 7 "gnus-agent-expire: Sorting entries... Done")
2147                               (gnus-message 7 "gnus-agent-expire: Merging entries... ")
2148                               (let ((dlist dlist))
2149                                 (while (cdr dlist) ; I'm not at the end-of-list
2150                                   (if (eq (caar dlist) (caadr dlist))
2151                                       (let ((first (cdr (car dlist)))
2152                                             (secnd (cdr (cadr dlist))))
2153                                         (setcar first (or (car first) (car secnd))) ; fetch_date
2154                                         (setq first (cdr first)
2155                                               secnd (cdr secnd))
2156                                         (setcar first (or (car first) (car secnd))) ; Keep_flag
2157                                         (setq first (cdr first)
2158                                               secnd (cdr secnd))
2159                                         (setcar first (or (car first) (car secnd))) ; NOV_entry_marker
2160
2161                                         (setcdr dlist (cddr dlist)))
2162                                     (setq dlist (cdr dlist)))))
2163                               (gnus-message 7 "gnus-agent-expire: Merging entries... Done")
2164
2165                               (let* ((len (float (length dlist)))
2166                                      (alist (list nil))
2167                                      (tail-alist alist))
2168                                 (while dlist
2169                                   (let ((new-completed (* 100.0 (/ (setq cnt (1+ cnt)) len))))
2170                                     (when (> new-completed completed)
2171                                       (setq completed new-completed)
2172                                       (gnus-message 9 "%3d%% completed..."  completed)))
2173                                   (let* ((entry (car dlist))
2174                                          (article-number (nth 0 entry))
2175                                          (fetch-date (nth 1 entry))
2176                                          (keep (nth 2 entry))
2177                                          (marker (nth 3 entry)))
2178
2179                                     (cond
2180                                      ;; Kept articles are unread, marked, or special.
2181                                      (keep
2182                                       (when fetch-date
2183                                         (unless (file-exists-p (concat dir (number-to-string article-number)))
2184                                           (setf (nth 1 entry) nil)
2185                                           (gnus-message 3 "gnus-agent-expire cleared download flag on article %d as the cached article file is missing." (caar dlist)))
2186                                         (unless marker
2187                                           (gnus-message 1 "gnus-agent-expire detected a missing NOV entry.  Run gnus-agent-regenerate-group to restore it.")))
2188                                       (gnus-agent-append-to-list tail-alist (cons article-number fetch-date)))
2189
2190                                      ;; The following articles are READ, UNMARKED, and ORDINARY.
2191                                      ;; See if they can be EXPIRED!!!
2192                                      ((setq type
2193                                             (cond
2194                                              ((not (integerp fetch-date))
2195                                               'read) ;; never fetched article (may expire right now)
2196                                              ((not (file-exists-p (concat dir (number-to-string article-number))))
2197                                               (setf (nth 1 entry) nil)
2198                                               'externally-expired) ;; Can't find the cached article.  Handle case as though this article was never fetched.
2199
2200                                              ;; We now have the arrival day, so we see
2201                                              ;; whether it's old enough to be expired.
2202                                              ((< fetch-date
2203                                                  (if (numberp day)
2204                                                      day
2205                                                    (let (found
2206                                                          (days gnus-agent-expire-days))
2207                                                      (while (and (not found)
2208                                                                  days)
2209                                                        (when (eq 0 (string-match (caar days) expiring-group))
2210                                                          (setq found (cadar days)))
2211                                                        (pop days))
2212                                                      found)))
2213                                               'expired)
2214                                              (force
2215                                               'forced)))
2216                                           
2217                                       ;; I found some reason to expire this entry.
2218
2219                                       (let ((actions nil))
2220                                         (when (memq type '(forced expired))
2221                                           (ignore-errors ; Just being paranoid.
2222                                             (delete-file (concat dir (number-to-string article-number)))
2223                                             (push "expired cached article" actions))
2224                                           (setf (nth 1 entry) nil)
2225                                           )
2226
2227                                         (when marker
2228                                           (push "NOV entry removed" article)
2229                                           (goto-char marker)
2230                                           (gnus-delete-line))
2231
2232                                         ;; If considering all articles is set, I can only expire article IDs that are no longer in the active range.
2233                                         (if (and gnus-agent-consider-all-articles
2234                                                  (>= article-number (car active)))
2235                                             ;; I have to keep this ID in the alist
2236                                             (gnus-agent-append-to-list tail-alist (cons article-number fetch-date))
2237                                           (push (format "Removed %s article number from article alist" type) actions))
2238
2239                                         (gnus-message 7 "gnus-agent-expire: Article %d: %s" article-number (mapconcat 'identity actions ", "))))
2240                                      )
2241
2242                                     ;; Clean up markers as I want to recycle this buffer over several groups.
2243                                     (when marker
2244                                       (set-marker marker nil))
2245
2246                                     (setq dlist (cdr dlist))))
2247
2248                                 (setq alist (cdr alist))
2249
2250                                 (let ((inhibit-quit t))
2251                                   (unless (equal alist gnus-agent-article-alist)
2252                                     (setq gnus-agent-article-alist alist)
2253                                     (gnus-agent-save-alist expiring-group))
2254
2255                                   (when (buffer-modified-p)
2256                                     (let ((coding-system-for-write
2257                                            gnus-agent-file-coding-system))
2258                                       (gnus-make-directory dir)
2259                                       (write-region (point-min) (point-max) nov-file nil 'silent)
2260                                       ;; clear the modified flag as that I'm not confused by its status on the next pass through this routine.
2261                                       (set-buffer-modified-p nil)))
2262
2263                                   (when (eq articles t)
2264                                     (gnus-summary-update-info)))))))))))
2265             (kill-buffer overview)))))
2266   (gnus-message 4 "Expiry...done"))
2267
2268 ;;;###autoload
2269 (defun gnus-agent-batch ()
2270   "Start Gnus, send queue and fetch session."
2271   (interactive)
2272   (let ((init-file-user "")
2273         (gnus-always-read-dribble-file t))
2274     (gnus))
2275   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
2276     (gnus-group-send-queue)
2277     (gnus-agent-fetch-session)))
2278
2279 (defun gnus-agent-unread-articles (group)
2280   (let* ((read (gnus-info-read (gnus-get-info group)))
2281          (known (gnus-agent-load-alist group))
2282          (unread (list nil))
2283          (tail-unread unread))
2284     (while (and known read)
2285       (let ((candidate (car (pop known))))
2286         (while (let* ((range (car read))
2287                       (min   (if (numberp range) range (car range)))
2288                       (max   (if (numberp range) range (cdr range))))
2289                  (cond ((or (not min)
2290                             (< candidate min))
2291                         (gnus-agent-append-to-list tail-unread candidate)
2292                         nil)
2293                        ((> candidate max)
2294                         (pop read)))))))
2295     (while known
2296       (gnus-agent-append-to-list tail-unread (car (pop known))))
2297     (cdr unread)))
2298
2299 (defun gnus-agent-uncached-articles (articles group &optional cached-header)
2300   "Constructs sublist of ARTICLES that excludes those articles ids in GROUP that have already been fetched.
2301  If CACHED-HEADER is nil, articles are only excluded if the article itself has been fetched."
2302
2303 ;; Logically equivalent to: (gnus-sorted-difference articles (mapcar 'car gnus-agent-article-alist))
2304 ;; Functionally, I don't need to construct a temp list using mapcar.
2305
2306   (if (gnus-agent-load-alist group)
2307     (let* ((ref gnus-agent-article-alist)
2308            (arts articles)
2309            (uncached (list nil))
2310            (tail-uncached uncached))
2311       (while (and ref arts)
2312         (let ((v1 (car arts))
2313               (v2 (caar ref)))
2314           (cond ((< v1 v2) ; the article (v1) does not appear in the reference list
2315                  (gnus-agent-append-to-list tail-uncached v1)
2316                  (pop arts))
2317                 ((= v1 v2)
2318                  (unless (or cached-header (cdar ref)) ; the article (v1) is already cached
2319                    (gnus-agent-append-to-list tail-uncached v1))
2320                  (pop arts)
2321                  (pop ref))
2322                 (t ; the reference article (v2) preceeds the list being filtered
2323                  (pop ref)))))
2324       (while arts
2325         (gnus-agent-append-to-list tail-uncached (pop arts)))
2326       (cdr uncached))
2327     ;; if gnus-agent-load-alist fails, no articles are cached.
2328     articles))
2329
2330 (defun gnus-agent-retrieve-headers (articles group &optional fetch-old)
2331   (save-excursion
2332     (gnus-agent-create-buffer)
2333     (let ((gnus-decode-encoded-word-function 'identity)
2334           (file (gnus-agent-article-name ".overview" group))
2335           cached-articles uncached-articles)
2336       (gnus-make-directory (nnheader-translate-file-chars
2337                             (file-name-directory file) t))
2338
2339       ;; Populate temp buffer with known headers
2340       (when (file-exists-p file)
2341         (with-current-buffer gnus-agent-overview-buffer
2342           (erase-buffer)
2343           (let ((nnheader-file-coding-system
2344                  gnus-agent-file-coding-system))
2345             (nnheader-insert-nov-file file (car articles)))))
2346
2347       (if (setq uncached-articles (gnus-agent-uncached-articles articles group t))
2348           (progn
2349             ;; Populate nntp-server-buffer with uncached headers
2350             (set-buffer nntp-server-buffer)
2351             (erase-buffer)
2352             (let (gnus-agent-cache)     ; Turn off agent cache
2353               (cond ((not (eq 'nov (gnus-retrieve-headers
2354                                     uncached-articles group fetch-old)))
2355                      (nnvirtual-convert-headers))
2356                     ((eq 'nntp (car gnus-current-select-method))
2357                      ;; The author of gnus-get-newsgroup-headers-xover reports that the XOVER command
2358                      ;; is commonly unreliable. The problem is that recently posted articles may not 
2359                      ;; be entered into the NOV database in time to respond to my XOVER query.
2360                      ;;
2361                      ;; I'm going to use his assumption that the NOV database is updated in order 
2362                      ;; of ascending article ID.  Therefore, a response containing article ID N 
2363                      ;; implies that all articles from 1 to N-1 are up-to-date.  Therefore, 
2364                      ;; missing articles in that range have expired.
2365                      
2366                      (set-buffer nntp-server-buffer)
2367                      (let* ((fetched-articles (list nil))
2368                             (tail-fetched-articles fetched-articles)
2369                             (min (cond ((numberp fetch-old)
2370                                         (max 1 (- (car articles) fetch-old)))
2371                                        (fetch-old
2372                                         1)
2373                                        (t
2374                                         (car articles))))
2375                             (max (car (last articles))))
2376                        
2377                        ;; Get the list of articles that were fetched
2378                        (goto-char (point-min))
2379                        (ignore-errors 
2380                          (while t
2381                            (gnus-agent-append-to-list tail-fetched-articles (read (current-buffer)))
2382                            (forward-line 1)))
2383                        
2384                        ;; Clip this list to the headers that will actually be returned
2385                        (setq fetched-articles (gnus-list-range-intersection
2386                                                (cdr fetched-articles)
2387                                                (cons min max)))
2388
2389                        ;; Clip the uncached articles list to exclude IDs after the last FETCHED header.  
2390                        ;; The excluded IDs may be fetchable using HEAD.
2391                        (if (car tail-fetched-articles)
2392                            (setq uncached-articles (gnus-list-range-intersection 
2393                                                     uncached-articles 
2394                                                     (cons (car uncached-articles) (car tail-fetched-articles)))))
2395
2396                        ;; Create the list of articles that were "successfully" fetched.  Success, in
2397                        ;; this case, means that the ID should not be fetched again.  In the case of 
2398                        ;; an expired article, the header will not be fetched.
2399                        (setq uncached-articles (gnus-sorted-nunion fetched-articles uncached-articles))
2400                        ))))
2401
2402             ;; Erase the temp buffer
2403             (set-buffer gnus-agent-overview-buffer)
2404             (erase-buffer)
2405
2406             ;; Copy the nntp-server-buffer to the temp buffer
2407             (set-buffer nntp-server-buffer)
2408             (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
2409
2410             ;; Merge the temp buffer with the known headers (found on disk in FILE) into the nntp-server-buffer
2411             (when (and uncached-articles (file-exists-p file))
2412               (gnus-agent-braid-nov group uncached-articles file))
2413
2414             ;; Save the new set of known headers to FILE
2415             (set-buffer nntp-server-buffer)
2416             (let ((coding-system-for-write
2417                    gnus-agent-file-coding-system))
2418               (gnus-agent-check-overview-buffer)
2419               (write-region (point-min) (point-max) file nil 'silent))
2420             
2421             ;; Update the group's article alist to include the newly fetched articles.
2422             (gnus-agent-load-alist group)
2423             (gnus-agent-save-alist group uncached-articles nil)
2424             )
2425         
2426         ;; Copy the temp buffer to the nntp-server-buffer
2427         (set-buffer nntp-server-buffer)
2428         (erase-buffer)
2429         (insert-buffer-substring gnus-agent-overview-buffer)))
2430
2431     (if (and fetch-old
2432              (not (numberp fetch-old)))
2433         t                               ; Don't remove anything.
2434       (nnheader-nov-delete-outside-range
2435        (if fetch-old (max 1 (- (car articles) fetch-old))
2436          (car articles))
2437        (car (last articles)))
2438       t)
2439
2440     'nov))
2441
2442 (defun gnus-agent-request-article (article group)
2443   "Retrieve ARTICLE in GROUP from the agent cache."
2444   (let* ((gnus-command-method (gnus-find-method-for-group group))
2445          (file (concat
2446                   (gnus-agent-directory)
2447                   (gnus-agent-group-path group) "/"
2448                   (number-to-string article)))
2449          (buffer-read-only nil))
2450     (when (and (file-exists-p file)
2451                (> (nth 7 (file-attributes file)) 0))
2452       (erase-buffer)
2453       (gnus-kill-all-overlays)
2454       (let ((coding-system-for-read gnus-cache-coding-system))
2455         (insert-file-contents file))
2456       t)))
2457
2458 (defun gnus-agent-regenerate-group (group &optional reread)
2459   "Regenerate GROUP.  If REREAD is t, all articles in the .overview are marked as unread.  If REREAD is not nil, downloaded articles are marked as unread."
2460   (gnus-message 5 "Regenerating in %s" group)
2461   (let* ((gnus-command-method (or gnus-command-method
2462                                   (gnus-find-method-for-group group)))
2463          (file (gnus-agent-article-name ".overview" group))
2464          (dir (file-name-directory file))
2465          point
2466          (downloaded (if (file-exists-p dir)
2467                          (sort (mapcar (lambda (name) (string-to-int name))
2468                                        (directory-files dir nil "^[0-9]+$" t))
2469                                '>)
2470                        (progn (gnus-make-directory dir) nil)))
2471          dl nov-arts
2472          alist header
2473          regenerated)
2474
2475     (mm-with-unibyte-buffer
2476      (if (file-exists-p file)
2477          (let ((nnheader-file-coding-system
2478                 gnus-agent-file-coding-system))
2479            (nnheader-insert-file-contents file)))
2480      (set-buffer-modified-p nil)
2481
2482      ;; Load the article IDs found in the overview file.  As a side-effect, validate the file contents.
2483      (let ((load t))
2484        (while load
2485          (setq load nil)
2486          (goto-char (point-min))
2487          (while (< (point) (point-max))
2488            (cond ((looking-at "[0-9]+\t")
2489                   (push (read (current-buffer)) nov-arts)
2490                   (forward-line 1)
2491                   (let ((l1 (car nov-arts))
2492                         (l2 (cadr nov-arts)))
2493                     (cond ((not l2)
2494                            nil)
2495                           ((< l1 l2)
2496                            (gnus-message 3 "gnus-agent-regenerate-group: NOV entries are NOT in ascending order.")
2497                            ;; Don't sort now as I haven't verified that every line begins with a number
2498                            (setq load t))
2499                           ((= l1 l2)
2500                            (forward-line -1)
2501                            (gnus-message 4 "gnus-agent-regenerate-group: NOV entries contained duplicate of article %s.  Duplicate deleted." l1)
2502                            (gnus-delete-line)
2503                            (pop nov-arts)))))
2504                  (t
2505                   (gnus-message 1 "gnus-agent-regenerate-group: NOV entries contained line that did not begin with an article number.  Deleted line.")
2506                   (gnus-delete-line))))
2507          (if load
2508              (progn
2509                (gnus-message 5 "gnus-agent-regenerate-group: Sorting NOV entries into ascending order.")
2510                (sort-numeric-fields 1 (point-min) (point-max))
2511                     (setq nov-arts nil)))))
2512      (gnus-agent-check-overview-buffer)
2513
2514      ;; Construct a new article alist whose nodes match every header in the .overview file.  
2515      ;; As a side-effect, missing headers are reconstructed from the downloaded article file.
2516      (while (or downloaded nov-arts)
2517        (cond ((and downloaded 
2518                    (or (not nov-arts)
2519                        (> (car downloaded) (car nov-arts))))
2520               ;; This entry is missing from the overview file
2521               (gnus-message 3 "Regenerating NOV %s %d..." group (car downloaded))
2522               (let ((file (concat dir (number-to-string (car downloaded)))))
2523                 (mm-with-unibyte-buffer
2524                  (nnheader-insert-file-contents file)
2525                  (nnheader-remove-body)
2526                  (setq header (nnheader-parse-naked-head)))
2527                 (mail-header-set-number header (car downloaded))
2528                 (if nov-arts
2529                     (let ((key (concat "^" (int-to-string (car nov-arts)) "\t")))
2530                       (or (re-search-backward key nil t)
2531                           (re-search-forward key))
2532                       (forward-line 1))
2533                   (goto-char (point-min)))
2534                 (nnheader-insert-nov header))
2535               (setq nov-arts (cons (car downloaded) nov-arts)))
2536              ((eq (car downloaded) (car nov-arts))
2537               ;; This entry in the overview has been downloaded
2538               (push (cons (car downloaded) (time-to-days (nth 5 (file-attributes (concat dir (number-to-string (car downloaded))))))) alist)
2539               (pop downloaded)
2540               (pop nov-arts))
2541              (t
2542               ;; This entry in the overview has not been downloaded
2543               (push (cons (car nov-arts) nil) alist)
2544               (pop nov-arts))))
2545
2546      ;; When gnus-agent-consider-all-articles is set, gnus-agent-regenerate-group should NOT remove article IDs 
2547      ;; from the alist.  Those IDs serve as markers to indicate that an attempt has been made to fetch that 
2548      ;; article's header.
2549
2550      ;; When gnus-agent-consider-all-articles is NOT set, gnus-agent-regenerate-group can remove the article
2551      ;; ID of every article (with the exception of the last ID in the list - it's special) that no longer appears in the overview.
2552      ;; In this situtation, the last article ID in the list implies that it, and every article ID preceeding it, 
2553      ;; have been fetched from the server.
2554      (if gnus-agent-consider-all-articles
2555          ;; Restore all article IDs that were not found in the overview file.
2556          (let* ((n (cons nil alist))
2557                 (merged n)
2558                 (o (gnus-agent-load-alist group)))
2559            (while o
2560              (let ((nID (caadr n))
2561                    (oID (caar o)))
2562                (cond ((not nID)
2563                       (setq n (setcdr n (list (list oID))))
2564                       (pop o))
2565                      ((< oID nID)
2566                       (setcdr n (cons (list oID) (cdr n)))
2567                       (pop o))
2568                      ((= oID nID)
2569                       (pop o)
2570                       (pop n))
2571                      (t
2572                       (pop n)))))
2573            (setq alist (cdr merged)))
2574        ;; Restore the last article ID if it is not already in the new alist
2575        (let ((n (last alist))
2576              (o (last (gnus-agent-load-alist group))))
2577          (cond ((not n)
2578                 (when o
2579                   (push (cons (caar o) nil) alist)))
2580                ((< (caar n) (caar o))
2581                 (setcdr n (list (car o)))))))
2582                      
2583      (let ((inhibit-quit t))
2584      (if (setq regenerated (buffer-modified-p))
2585          (let ((coding-system-for-write gnus-agent-file-coding-system))
2586            (write-region (point-min) (point-max) file nil 'silent)))
2587
2588     (setq regenerated (or regenerated
2589                           (and reread gnus-agent-article-alist)
2590                           (not (equal alist gnus-agent-article-alist)))
2591           )
2592
2593     (setq gnus-agent-article-alist alist)
2594  
2595     (when regenerated
2596          (gnus-agent-save-alist group)))
2597      )
2598
2599     (when (and reread gnus-agent-article-alist)
2600       (gnus-make-ascending-articles-unread
2601        group
2602        (delq nil (mapcar (function (lambda (c)
2603                                      (cond ((eq reread t)
2604                                             (car c))
2605                                            ((cdr c)
2606                                             (car c)))))
2607                          gnus-agent-article-alist)))
2608
2609       (when (gnus-buffer-live-p gnus-group-buffer)
2610         (gnus-group-update-group group t)
2611         (sit-for 0))
2612       )
2613
2614     regenerated))
2615
2616 ;;;###autoload
2617 (defun gnus-agent-regenerate (&optional clean reread)
2618   "Regenerate all agent covered files.
2619 If CLEAN, don't read existing active files."
2620   (interactive "P")
2621   (let (regenerated)
2622     (gnus-message 4 "Regenerating Gnus agent files...")
2623     (dolist (gnus-command-method gnus-agent-covered-methods)
2624       (let ((active-file (gnus-agent-lib-file "active"))
2625             active-hashtb active-changed
2626             point)
2627         (gnus-make-directory (file-name-directory active-file))
2628         (if clean
2629             (setq active-hashtb (gnus-make-hashtable 1000))
2630           (mm-with-unibyte-buffer
2631            (if (file-exists-p active-file)
2632                (let ((nnheader-file-coding-system
2633                       gnus-agent-file-coding-system))
2634                  (nnheader-insert-file-contents active-file))
2635              (setq active-changed t))
2636            (gnus-active-to-gnus-format
2637             nil (setq active-hashtb
2638                       (gnus-make-hashtable
2639                        (count-lines (point-min) (point-max)))))))
2640         (dolist (group (gnus-groups-from-server gnus-command-method))
2641           (setq regenerated (or (gnus-agent-regenerate-group group reread)
2642                                 regenerated))
2643           (let ((min (or (caar gnus-agent-article-alist) 1))
2644                 (max (or (caar (last gnus-agent-article-alist)) 0))
2645                 (active (gnus-gethash-safe (gnus-group-real-name group)
2646                                            active-hashtb))
2647                 (read (gnus-info-read (gnus-get-info group))))
2648             (if (not active)
2649                 (progn
2650                   (setq active (cons min max)
2651                         active-changed t)
2652                   (gnus-sethash group active active-hashtb))
2653               (when (> (car active) min)
2654                 (setcar active min)
2655                 (setq active-changed t))
2656               (when (< (cdr active) max)
2657                 (setcdr active max)
2658                 (setq active-changed t)))))
2659         (when active-changed
2660           (setq regenerated t)
2661           (gnus-message 4 "Regenerate %s" active-file)
2662           (let ((nnmail-active-file-coding-system gnus-agent-file-coding-system))
2663             (gnus-write-active-file active-file active-hashtb)))))
2664     (gnus-message 4 "Regenerating Gnus agent files...done")
2665     regenerated))
2666
2667 (defun gnus-agent-go-online (&optional force)
2668   "Switch servers into online status."
2669   (interactive (list t))
2670   (dolist (server gnus-opened-servers)
2671     (when (eq (nth 1 server) 'offline)
2672       (if (if (eq force 'ask)
2673               (gnus-y-or-n-p
2674                (format "Switch %s:%s into online status? "
2675                        (caar server) (cadar server)))
2676             force)
2677           (setcar (nthcdr 1 server) 'close)))))
2678
2679 (defun gnus-agent-toggle-group-plugged (group)
2680   "Toggle the status of the server of the current group."
2681   (interactive (list (gnus-group-group-name)))
2682   (let* ((method (gnus-find-method-for-group group))
2683          (status (cadr (assoc method gnus-opened-servers))))
2684     (if (eq status 'offline)
2685         (gnus-server-set-status method 'closed)
2686       (gnus-close-server method)
2687       (gnus-server-set-status method 'offline))
2688     (message "Turn %s:%s from %s to %s." (car method) (cadr method)
2689              (if (eq status 'offline) 'offline 'online)
2690              (if (eq status 'offline) 'online 'offline))))
2691
2692 (defun gnus-agent-group-covered-p (group)
2693   (member (gnus-group-method group)
2694           gnus-agent-covered-methods))
2695
2696 (provide 'gnus-agent)
2697
2698 ;;; gnus-agent.el ends here