5ab22515c73f5127e9fbf61f2757c1851601afe5
[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-fetched-hook nil
58   "Hook run after finishing fetching articles."
59   :group 'gnus-agent
60   :type 'hook)
61
62 (defcustom gnus-agent-handle-level gnus-level-subscribed
63   "Groups on levels higher than this variable will be ignored by the Agent."
64   :group 'gnus-agent
65   :type 'integer)
66
67 (defcustom gnus-agent-expire-days 7
68   "Read articles older than this will be expired.
69 This can also be a list of regexp/day pairs.  The regexps will
70 be matched against group names."
71   :group 'gnus-agent
72   :type 'integer)
73
74 (defcustom gnus-agent-expire-all nil
75   "If non-nil, also expire unread, ticked and dormant articles.
76 If nil, only read articles will be expired."
77   :group 'gnus-agent
78   :type 'boolean)
79
80 (defcustom gnus-agent-group-mode-hook nil
81   "Hook run in Agent group minor modes."
82   :group 'gnus-agent
83   :type 'hook)
84
85 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
86 (when (featurep 'xemacs)
87   (add-hook 'gnus-agent-group-mode-hook 'gnus-xmas-agent-group-menu-add))
88
89 (defcustom gnus-agent-summary-mode-hook nil
90   "Hook run in Agent summary minor modes."
91   :group 'gnus-agent
92   :type 'hook)
93
94 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
95 (when (featurep 'xemacs)
96   (add-hook 'gnus-agent-summary-mode-hook 'gnus-xmas-agent-summary-menu-add))
97
98 (defcustom gnus-agent-server-mode-hook nil
99   "Hook run in Agent summary minor modes."
100   :group 'gnus-agent
101   :type 'hook)
102
103 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
104 (when (featurep 'xemacs)
105   (add-hook 'gnus-agent-server-mode-hook 'gnus-xmas-agent-server-menu-add))
106
107 (defcustom gnus-agent-confirmation-function 'y-or-n-p
108   "Function to confirm when error happens."
109   :version "21.1"
110   :group 'gnus-agent
111   :type 'function)
112
113 (defcustom gnus-agent-synchronize-flags 'ask
114   "Indicate if flags are synchronized when you plug in.
115 If this is `ask' the hook will query the user."
116   :version "21.1"
117   :type '(choice (const :tag "Always" t)
118                  (const :tag "Never" nil)
119                  (const :tag "Ask" ask))
120   :group 'gnus-agent)
121
122 (defcustom gnus-agent-go-online 'ask
123   "Indicate if offline servers go online when you plug in.
124 If this is `ask' the hook will query the user."
125   :version "21.1"
126   :type '(choice (const :tag "Always" t)
127                  (const :tag "Never" nil)
128                  (const :tag "Ask" ask))
129   :group 'gnus-agent)
130
131 (defcustom gnus-agent-mark-unread-after-downloaded t
132   "Indicate whether to mark articles unread after downloaded."
133   :version "21.1"
134   :type 'boolean
135   :group 'gnus-agent)
136
137 (defcustom gnus-agent-download-marks '(download)
138   "Marks for downloading."
139   :version "21.1"
140   :type '(repeat (symbol :tag "Mark"))
141   :group 'gnus-agent)
142
143 (defcustom gnus-agent-consider-all-articles nil
144   "If non-nil, consider also the read articles for downloading."
145   :version "21.4"
146   :type 'boolean
147   :group 'gnus-agent)
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 (defvar gnus-agent-fetched-headers nil)
155 (defvar gnus-agent-group-alist nil)
156 (defvar gnus-category-alist nil)
157 (defvar gnus-agent-current-history nil)
158 (defvar gnus-agent-overview-buffer nil)
159 (defvar gnus-category-predicate-cache nil)
160 (defvar gnus-category-group-cache nil)
161 (defvar gnus-agent-spam-hashtb nil)
162 (defvar gnus-agent-file-name nil)
163 (defvar gnus-agent-send-mail-function nil)
164 (defvar gnus-agent-file-coding-system 'raw-text)
165 (defvar gnus-agent-file-loading-cache nil)
166 (defvar gnus-agent-file-header-cache nil)
167
168 (defvar gnus-agent-auto-agentize-methods '(nntp nnimap)
169   "Initially, all servers from these methods are agentized.
170 The user may remove or add servers using the Server buffer.  See Info
171 node `(gnus)Server Buffer'.")
172
173 ;; Dynamic variables
174 (defvar gnus-headers)
175 (defvar gnus-score)
176
177 ;;;
178 ;;; Setup
179 ;;;
180
181 (defun gnus-open-agent ()
182   (setq gnus-agent t)
183   (gnus-agent-read-servers)
184   (gnus-category-read)
185   (gnus-agent-create-buffer)
186   (add-hook 'gnus-group-mode-hook 'gnus-agent-mode)
187   (add-hook 'gnus-summary-mode-hook 'gnus-agent-mode)
188   (add-hook 'gnus-server-mode-hook 'gnus-agent-mode))
189
190 (defun gnus-agent-create-buffer ()
191   (if (gnus-buffer-live-p gnus-agent-overview-buffer)
192       t
193     (setq gnus-agent-overview-buffer
194           (gnus-get-buffer-create " *Gnus agent overview*"))
195     (with-current-buffer gnus-agent-overview-buffer
196       (mm-enable-multibyte))
197     nil))
198
199 (gnus-add-shutdown 'gnus-close-agent 'gnus)
200
201 (defun gnus-close-agent ()
202   (setq gnus-agent-covered-methods nil
203         gnus-category-predicate-cache nil
204         gnus-category-group-cache nil
205         gnus-agent-spam-hashtb nil)
206   (gnus-kill-buffer gnus-agent-overview-buffer))
207
208 ;;;
209 ;;; Utility functions
210 ;;;
211
212 (defun gnus-agent-read-file (file)
213   "Load FILE and do a `read' there."
214   (with-temp-buffer
215     (ignore-errors
216       (nnheader-insert-file-contents file)
217       (goto-char (point-min))
218       (read (current-buffer)))))
219
220 (defsubst gnus-agent-method ()
221   (concat (symbol-name (car gnus-command-method)) "/"
222           (if (equal (cadr gnus-command-method) "")
223               "unnamed"
224             (cadr gnus-command-method))))
225
226 (defsubst gnus-agent-directory ()
227   "Path of the Gnus agent directory."
228   (nnheader-concat gnus-agent-directory
229                    (nnheader-translate-file-chars (gnus-agent-method)) "/"))
230
231 (defun gnus-agent-lib-file (file)
232   "The full path of the Gnus agent library FILE."
233   (expand-file-name file
234                     (file-name-as-directory
235                      (expand-file-name "agent.lib" (gnus-agent-directory)))))
236
237 ;;; Fetching setup functions.
238
239 (defun gnus-agent-start-fetch ()
240   "Initialize data structures for efficient fetching."
241   (gnus-agent-open-history)
242   (setq gnus-agent-current-history (gnus-agent-history-buffer))
243   (gnus-agent-create-buffer))
244
245 (defun gnus-agent-stop-fetch ()
246   "Save all data structures and clean up."
247   (gnus-agent-save-history)
248   (gnus-agent-close-history)
249   (setq gnus-agent-spam-hashtb nil)
250   (save-excursion
251     (set-buffer nntp-server-buffer)
252     (widen)))
253
254 (defmacro gnus-agent-with-fetch (&rest forms)
255   "Do FORMS safely."
256   `(unwind-protect
257        (let ((gnus-agent-fetching t))
258          (gnus-agent-start-fetch)
259          ,@forms)
260      (gnus-agent-stop-fetch)))
261
262 (put 'gnus-agent-with-fetch 'lisp-indent-function 0)
263 (put 'gnus-agent-with-fetch 'edebug-form-spec '(body))
264
265 ;;;
266 ;;; Mode infestation
267 ;;;
268
269 (defvar gnus-agent-mode-hook nil
270   "Hook run when installing agent mode.")
271
272 (defvar gnus-agent-mode nil)
273 (defvar gnus-agent-mode-status '(gnus-agent-mode " Plugged"))
274
275 (defun gnus-agent-mode ()
276   "Minor mode for providing a agent support in Gnus buffers."
277   (let* ((buffer (progn (string-match "^gnus-\\(.*\\)-mode$"
278                                       (symbol-name major-mode))
279                         (match-string 1 (symbol-name major-mode))))
280          (mode (intern (format "gnus-agent-%s-mode" buffer))))
281     (set (make-local-variable 'gnus-agent-mode) t)
282     (set mode nil)
283     (set (make-local-variable mode) t)
284     ;; Set up the menu.
285     (when (gnus-visual-p 'agent-menu 'menu)
286       (funcall (intern (format "gnus-agent-%s-make-menu-bar" buffer))))
287     (unless (assq 'gnus-agent-mode minor-mode-alist)
288       (push gnus-agent-mode-status minor-mode-alist))
289     (unless (assq mode minor-mode-map-alist)
290       (push (cons mode (symbol-value (intern (format "gnus-agent-%s-mode-map"
291                                                      buffer))))
292             minor-mode-map-alist))
293     (when (eq major-mode 'gnus-group-mode)
294       (gnus-agent-toggle-plugged gnus-plugged))
295     (gnus-run-hooks 'gnus-agent-mode-hook
296                     (intern (format "gnus-agent-%s-mode-hook" buffer)))))
297
298 (defvar gnus-agent-group-mode-map (make-sparse-keymap))
299 (gnus-define-keys gnus-agent-group-mode-map
300   "Ju" gnus-agent-fetch-groups
301   "Jc" gnus-enter-category-buffer
302   "Jj" gnus-agent-toggle-plugged
303   "Js" gnus-agent-fetch-session
304   "JY" gnus-agent-synchronize-flags
305   "JS" gnus-group-send-queue
306   "Ja" gnus-agent-add-group
307   "Jr" gnus-agent-remove-group
308   "Jo" gnus-agent-toggle-group-plugged)
309
310 (defun gnus-agent-group-make-menu-bar ()
311   (unless (boundp 'gnus-agent-group-menu)
312     (easy-menu-define
313      gnus-agent-group-menu gnus-agent-group-mode-map ""
314      '("Agent"
315        ["Toggle plugged" gnus-agent-toggle-plugged t]
316        ["Toggle group plugged" gnus-agent-toggle-group-plugged t]
317        ["List categories" gnus-enter-category-buffer t]
318        ["Send queue" gnus-group-send-queue gnus-plugged]
319        ("Fetch"
320         ["All" gnus-agent-fetch-session gnus-plugged]
321         ["Group" gnus-agent-fetch-group gnus-plugged])))))
322
323 (defvar gnus-agent-summary-mode-map (make-sparse-keymap))
324 (gnus-define-keys gnus-agent-summary-mode-map
325   "Jj" gnus-agent-toggle-plugged
326   "Ju" gnus-agent-summary-fetch-group
327   "J#" gnus-agent-mark-article
328   "J\M-#" gnus-agent-unmark-article
329   "@" gnus-agent-toggle-mark
330   "Jc" gnus-agent-catchup)
331
332 (defun gnus-agent-summary-make-menu-bar ()
333   (unless (boundp 'gnus-agent-summary-menu)
334     (easy-menu-define
335      gnus-agent-summary-menu gnus-agent-summary-mode-map ""
336      '("Agent"
337        ["Toggle plugged" gnus-agent-toggle-plugged t]
338        ["Mark as downloadable" gnus-agent-mark-article t]
339        ["Unmark as downloadable" gnus-agent-unmark-article t]
340        ["Toggle mark" gnus-agent-toggle-mark t]
341        ["Fetch downloadable" gnus-agent-summary-fetch-group t]
342        ["Catchup undownloaded" gnus-agent-catchup t]))))
343
344 (defvar gnus-agent-server-mode-map (make-sparse-keymap))
345 (gnus-define-keys gnus-agent-server-mode-map
346   "Jj" gnus-agent-toggle-plugged
347   "Ja" gnus-agent-add-server
348   "Jr" gnus-agent-remove-server)
349
350 (defun gnus-agent-server-make-menu-bar ()
351   (unless (boundp 'gnus-agent-server-menu)
352     (easy-menu-define
353      gnus-agent-server-menu gnus-agent-server-mode-map ""
354      '("Agent"
355        ["Toggle plugged" gnus-agent-toggle-plugged t]
356        ["Add" gnus-agent-add-server t]
357        ["Remove" gnus-agent-remove-server t]))))
358
359 (defun gnus-agent-make-mode-line-string (string mouse-button mouse-func)
360   (if (and (fboundp 'propertize)
361            (fboundp 'make-mode-line-mouse-map))
362       (propertize string 'local-map
363                   (make-mode-line-mouse-map mouse-button mouse-func))
364     string))
365
366 (defun gnus-agent-toggle-plugged (plugged)
367   "Toggle whether Gnus is unplugged or not."
368   (interactive (list (not gnus-plugged)))
369   (if plugged
370       (progn
371         (setq gnus-plugged plugged)
372         (gnus-run-hooks 'gnus-agent-plugged-hook)
373         (setcar (cdr gnus-agent-mode-status)
374                 (gnus-agent-make-mode-line-string " Plugged"
375                                                   'mouse-2
376                                                   'gnus-agent-toggle-plugged))
377         (gnus-agent-go-online gnus-agent-go-online)
378         (gnus-agent-possibly-synchronize-flags))
379     (gnus-agent-close-connections)
380     (setq gnus-plugged plugged)
381     (gnus-run-hooks 'gnus-agent-unplugged-hook)
382     (setcar (cdr gnus-agent-mode-status)
383             (gnus-agent-make-mode-line-string " Unplugged"
384                                               'mouse-2
385                                               'gnus-agent-toggle-plugged)))
386   (set-buffer-modified-p t))
387
388 (defun gnus-agent-close-connections ()
389   "Close all methods covered by the Gnus agent."
390   (let ((methods gnus-agent-covered-methods))
391     (while methods
392       (gnus-close-server (pop methods)))))
393
394 ;;;###autoload
395 (defun gnus-unplugged ()
396   "Start Gnus unplugged."
397   (interactive)
398   (setq gnus-plugged nil)
399   (gnus))
400
401 ;;;###autoload
402 (defun gnus-plugged ()
403   "Start Gnus plugged."
404   (interactive)
405   (setq gnus-plugged t)
406   (gnus))
407
408 ;;;###autoload
409 (defun gnus-slave-unplugged (&optional arg)
410   "Read news as a slave unplugged."
411   (interactive "P")
412   (setq gnus-plugged nil)
413   (gnus arg nil 'slave))
414
415 ;;;###autoload
416 (defun gnus-agentize ()
417   "Allow Gnus to be an offline newsreader.
418 The normal usage of this command is to put the following as the
419 last form in your `.gnus.el' file:
420
421 \(gnus-agentize)
422
423 This will modify the `gnus-setup-news-hook', and
424 `message-send-mail-real-function' variables, and install the Gnus agent
425 minor mode in all Gnus buffers."
426   (interactive)
427   (gnus-open-agent)
428   (add-hook 'gnus-setup-news-hook 'gnus-agent-queue-setup)
429   (unless gnus-agent-send-mail-function
430     (setq gnus-agent-send-mail-function (or
431                                          message-send-mail-real-function
432                                          message-send-mail-function)
433           message-send-mail-real-function 'gnus-agent-send-mail))
434   (unless gnus-agent-covered-methods
435     (mapcar
436      (lambda (server)
437        (if (memq (car (gnus-server-to-method server)) 
438                  gnus-agent-auto-agentize-methods)
439            (setq gnus-agent-covered-methods 
440                  (cons (gnus-server-to-method server)
441                        gnus-agent-covered-methods ))))
442      (append (list gnus-select-method) gnus-secondary-select-methods))))
443
444 (defun gnus-agent-queue-setup ()
445   "Make sure the queue group exists."
446   (unless (gnus-gethash "nndraft:queue" gnus-newsrc-hashtb)
447     (gnus-request-create-group "queue" '(nndraft ""))
448     (let ((gnus-level-default-subscribed 1))
449       (gnus-subscribe-group "nndraft:queue" nil '(nndraft "")))
450     (gnus-group-set-parameter
451      "nndraft:queue" 'gnus-dummy '((gnus-draft-mode)))))
452
453 (defun gnus-agent-send-mail ()
454   (if gnus-plugged
455       (funcall gnus-agent-send-mail-function)
456     (goto-char (point-min))
457     (re-search-forward
458      (concat "^" (regexp-quote mail-header-separator) "\n"))
459     (replace-match "\n")
460     (gnus-agent-insert-meta-information 'mail)
461     (gnus-request-accept-article "nndraft:queue" nil t t)))
462
463 (defun gnus-agent-insert-meta-information (type &optional method)
464   "Insert meta-information into the message that says how it's to be posted.
465 TYPE can be either `mail' or `news'.  If the latter, then METHOD can
466 be a select method."
467   (save-excursion
468     (message-remove-header gnus-agent-meta-information-header)
469     (goto-char (point-min))
470     (insert gnus-agent-meta-information-header ": "
471             (symbol-name type) " " (format "%S" method)
472             "\n")
473     (forward-char -1)
474     (while (search-backward "\n" nil t)
475       (replace-match "\\n" t t))))
476
477 (defun gnus-agent-restore-gcc ()
478   "Restore GCC field from saved header."
479   (save-excursion
480     (goto-char (point-min))
481     (while (re-search-forward (concat gnus-agent-gcc-header ":") nil t)
482       (replace-match "Gcc:" 'fixedcase))))
483
484 (defun gnus-agent-any-covered-gcc ()
485   (save-restriction
486     (message-narrow-to-headers)
487     (let* ((gcc (mail-fetch-field "gcc" nil t))
488            (methods (and gcc
489                          (mapcar 'gnus-inews-group-method
490                                  (message-unquote-tokens
491                                   (message-tokenize-header
492                                    gcc " ,")))))
493            covered)
494       (while (and (not covered) methods)
495         (setq covered (gnus-agent-method-p (car methods))
496               methods (cdr methods)))
497       covered)))
498
499 ;;;###autoload
500 (defun gnus-agent-possibly-save-gcc ()
501   "Save GCC if Gnus is unplugged."
502   (when (and (not gnus-plugged) (gnus-agent-any-covered-gcc))
503     (save-excursion
504       (goto-char (point-min))
505       (let ((case-fold-search t))
506         (while (re-search-forward "^gcc:" nil t)
507           (replace-match (concat gnus-agent-gcc-header ":") 'fixedcase))))))
508
509 (defun gnus-agent-possibly-do-gcc ()
510   "Do GCC if Gnus is plugged."
511   (when (or gnus-plugged (not (gnus-agent-any-covered-gcc)))
512     (gnus-inews-do-gcc)))
513
514 ;;;
515 ;;; Group mode commands
516 ;;;
517
518 (defun gnus-agent-fetch-groups (n)
519   "Put all new articles in the current groups into the Agent."
520   (interactive "P")
521   (unless gnus-plugged
522     (error "Groups can't be fetched when Gnus is unplugged"))
523   (gnus-group-iterate n 'gnus-agent-fetch-group))
524
525 (defun gnus-agent-fetch-group (group)
526   "Put all new articles in GROUP into the Agent."
527   (interactive (list (gnus-group-group-name)))
528   (let ((state gnus-plugged))
529     (unwind-protect
530         (progn
531           (unless group
532             (error "No group on the current line"))
533           (unless state
534             (gnus-agent-toggle-plugged gnus-plugged))
535           (let ((gnus-command-method (gnus-find-method-for-group group)))
536             (gnus-agent-with-fetch
537               (gnus-agent-fetch-group-1 group gnus-command-method)
538               (gnus-message 5 "Fetching %s...done" group))))
539       (when (and (not state)
540                  gnus-plugged)
541         (gnus-agent-toggle-plugged gnus-plugged)))))
542
543 (defun gnus-agent-add-group (category arg)
544   "Add the current group to an agent category."
545   (interactive
546    (list
547     (intern
548      (completing-read
549       "Add to category: "
550       (mapcar (lambda (cat) (list (symbol-name (car cat))))
551               gnus-category-alist)
552       nil t))
553     current-prefix-arg))
554   (let ((cat (assq category gnus-category-alist))
555         c groups)
556     (gnus-group-iterate arg
557       (lambda (group)
558         (when (cadddr (setq c (gnus-group-category group)))
559           (setf (cadddr c) (delete group (cadddr c))))
560         (push group groups)))
561     (setf (cadddr cat) (nconc (cadddr cat) groups))
562     (gnus-category-write)))
563
564 (defun gnus-agent-remove-group (arg)
565   "Remove the current group from its agent category, if any."
566   (interactive "P")
567   (let (c)
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     (gnus-category-write)))
573
574 (defun gnus-agent-synchronize-flags ()
575   "Synchronize unplugged flags with servers."
576   (interactive)
577   (save-excursion
578     (dolist (gnus-command-method gnus-agent-covered-methods)
579       (when (file-exists-p (gnus-agent-lib-file "flags"))
580         (gnus-agent-synchronize-flags-server gnus-command-method)))))
581
582 (defun gnus-agent-possibly-synchronize-flags ()
583   "Synchronize flags according to `gnus-agent-synchronize-flags'."
584   (interactive)
585   (save-excursion
586     (dolist (gnus-command-method gnus-agent-covered-methods)
587       (when (file-exists-p (gnus-agent-lib-file "flags"))
588         (gnus-agent-possibly-synchronize-flags-server gnus-command-method)))))
589
590 (defun gnus-agent-synchronize-flags-server (method)
591   "Synchronize flags set when unplugged for server."
592   (let ((gnus-command-method method))
593     (when (file-exists-p (gnus-agent-lib-file "flags"))
594       (set-buffer (get-buffer-create " *Gnus Agent flag synchronize*"))
595       (erase-buffer)
596       (nnheader-insert-file-contents (gnus-agent-lib-file "flags"))
597       (if (null (gnus-check-server gnus-command-method))
598           (message "Couldn't open server %s" (nth 1 gnus-command-method))
599         (while (not (eobp))
600           (if (null (eval (read (current-buffer))))
601               (progn (forward-line)
602                      (kill-line -1))
603             (write-file (gnus-agent-lib-file "flags"))
604             (error "Couldn't set flags from file %s"
605                    (gnus-agent-lib-file "flags"))))
606         (delete-file (gnus-agent-lib-file "flags")))
607       (kill-buffer nil))))
608
609 (defun gnus-agent-possibly-synchronize-flags-server (method)
610   "Synchronize flags for server according to `gnus-agent-synchronize-flags'."
611   (when (or (and gnus-agent-synchronize-flags
612                  (not (eq gnus-agent-synchronize-flags 'ask)))
613             (and (eq gnus-agent-synchronize-flags 'ask)
614                  (gnus-y-or-n-p (format "Synchronize flags on server `%s'? "
615                                         (cadr method)))))
616     (gnus-agent-synchronize-flags-server method)))
617
618 ;;;
619 ;;; Server mode commands
620 ;;;
621
622 (defun gnus-agent-add-server (server)
623   "Enroll SERVER in the agent program."
624   (interactive (list (gnus-server-server-name)))
625   (unless server
626     (error "No server on the current line"))
627   (let ((method (gnus-server-get-method nil (gnus-server-server-name))))
628     (when (gnus-agent-method-p method)
629       (error "Server already in the agent program"))
630     (push method gnus-agent-covered-methods)
631     (gnus-server-update-server server)
632     (gnus-agent-write-servers)
633     (message "Entered %s into the Agent" server)))
634
635 (defun gnus-agent-remove-server (server)
636   "Remove SERVER from the agent program."
637   (interactive (list (gnus-server-server-name)))
638   (unless server
639     (error "No server on the current line"))
640   (let ((method (gnus-server-get-method nil (gnus-server-server-name))))
641     (unless (gnus-agent-method-p method)
642       (error "Server not in the agent program"))
643     (setq gnus-agent-covered-methods
644           (delete method gnus-agent-covered-methods))
645     (gnus-server-update-server server)
646     (gnus-agent-write-servers)
647     (message "Removed %s from the agent" server)))
648
649 (defun gnus-agent-read-servers ()
650   "Read the alist of covered servers."
651   (mapcar (lambda (m)
652             (let ((server (gnus-server-get-method
653                            nil
654                            (or m "native"))))
655               (if server
656                   (push server gnus-agent-covered-methods)
657                 (message "Ignoring disappeared server `%s'" m)
658                 (sit-for 1))))
659           (gnus-agent-read-file
660            (nnheader-concat gnus-agent-directory "lib/servers"))))
661
662 (defun gnus-agent-write-servers ()
663   "Write the alist of covered servers."
664   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
665   (let ((coding-system-for-write nnheader-file-coding-system)
666         (file-name-coding-system nnmail-pathname-coding-system))
667     (with-temp-file (nnheader-concat gnus-agent-directory "lib/servers")
668       (prin1 (mapcar 'gnus-method-simplify gnus-agent-covered-methods)
669              (current-buffer)))))
670
671 ;;;
672 ;;; Summary commands
673 ;;;
674
675 (defun gnus-agent-mark-article (n &optional unmark)
676   "Mark the next N articles as downloadable.
677 If N is negative, mark backward instead.  If UNMARK is non-nil, remove
678 the mark instead.  The difference between N and the actual number of
679 articles marked is returned."
680   (interactive "p")
681   (let ((backward (< n 0))
682         (n (abs n)))
683     (while (and
684             (> n 0)
685             (progn
686               (gnus-summary-set-agent-mark
687                (gnus-summary-article-number) unmark)
688               (zerop (gnus-summary-next-subject (if backward -1 1) nil t))))
689       (setq n (1- n)))
690     (when (/= 0 n)
691       (gnus-message 7 "No more articles"))
692     (gnus-summary-recenter)
693     (gnus-summary-position-point)
694     n))
695
696 (defun gnus-agent-unmark-article (n)
697   "Remove the downloadable mark from the next N articles.
698 If N is negative, unmark backward instead.  The difference between N and
699 the actual number of articles unmarked is returned."
700   (interactive "p")
701   (gnus-agent-mark-article n t))
702
703 (defun gnus-agent-toggle-mark (n)
704   "Toggle the downloadable mark from the next N articles.
705 If N is negative, toggle backward instead.  The difference between N and
706 the actual number of articles toggled is returned."
707   (interactive "p")
708   (gnus-agent-mark-article n 'toggle))
709
710 (defun gnus-summary-set-agent-mark (article &optional unmark)
711   "Mark ARTICLE as downloadable."
712   (let ((unmark (if (and (not (null unmark)) (not (eq t unmark)))
713                     (memq article gnus-newsgroup-downloadable)
714                   unmark)))
715     (if unmark
716         (progn
717           (setq gnus-newsgroup-downloadable
718                 (delq article gnus-newsgroup-downloadable))
719           (push article gnus-newsgroup-undownloaded))
720       (setq gnus-newsgroup-undownloaded
721             (delq article gnus-newsgroup-undownloaded))
722       (setq gnus-newsgroup-downloadable
723             (gnus-add-to-sorted-list gnus-newsgroup-downloadable article)))
724     (gnus-summary-update-mark
725      (if unmark gnus-undownloaded-mark gnus-downloadable-mark)
726      'unread)))
727
728 (defun gnus-agent-get-undownloaded-list ()
729   "Mark all unfetched articles as read."
730   (let ((gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name)))
731     (when (and (not (gnus-online gnus-command-method))
732                (gnus-agent-method-p gnus-command-method))
733       (gnus-agent-load-alist gnus-newsgroup-name)
734       ;; First mark all undownloaded articles as undownloaded.
735       ;; CCC kaig: Maybe change here to consider all headers.
736       (let ((articles (mapcar (lambda (header) (mail-header-number header))
737                               gnus-newsgroup-headers))
738             (agent-articles gnus-agent-article-alist)
739             candidates article)
740         (while (setq article (pop articles))
741           (while (and agent-articles
742                       (< (caar agent-articles) article))
743             (setq agent-articles (cdr agent-articles)))
744           (when (or (not (cdar agent-articles))
745                     (not (= (caar agent-articles) article)))
746             (push article candidates)))
747         (dolist (article candidates)
748           (unless (or (memq article gnus-newsgroup-downloadable)
749                       (memq article gnus-newsgroup-cached))
750             (push article gnus-newsgroup-undownloaded))))
751       ;; Then mark downloaded downloadable as not-downloadable,
752       ;; if you get my drift.
753       (dolist (article gnus-newsgroup-downloadable)
754         (when (cdr (assq article gnus-agent-article-alist))
755           (setq gnus-newsgroup-downloadable
756                 (delq article gnus-newsgroup-downloadable)))))))
757
758 (defun gnus-agent-catchup ()
759   "Mark all undownloaded articles as read."
760   (interactive)
761   (save-excursion
762     (while gnus-newsgroup-undownloaded
763       (gnus-summary-mark-article
764        (pop gnus-newsgroup-undownloaded) gnus-catchup-mark)))
765   (gnus-summary-position-point))
766
767 (defun gnus-agent-summary-fetch-group (&optional all)
768   "Fetch the downloadable articles in the group.
769 Optional arg ALL, if non-nil, means to fetch all articles."
770   (interactive "P")
771   (let ((articles
772          (if all gnus-newsgroup-articles
773            gnus-newsgroup-downloadable))
774         (gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name))
775         (state gnus-plugged))
776     (unwind-protect
777         (progn
778           (unless state
779             (gnus-agent-toggle-plugged t))
780           (unless articles
781             (error "No articles to download"))
782           (gnus-agent-with-fetch
783             (gnus-agent-fetch-articles gnus-newsgroup-name articles))
784           (save-excursion
785             (dolist (article articles)
786               (setq gnus-newsgroup-downloadable
787                     (delq article gnus-newsgroup-downloadable))
788               (if gnus-agent-mark-unread-after-downloaded
789                   (gnus-summary-mark-article article gnus-unread-mark)))))
790       (when (and (not state)
791                  gnus-plugged)
792         (gnus-agent-toggle-plugged nil)))))
793
794 (defun gnus-agent-fetch-selected-article ()
795   "Fetch the current article as it is selected.
796 This can be added to `gnus-select-article-hook' or
797 `gnus-mark-article-hook'."
798   (let ((gnus-command-method gnus-current-select-method))
799     (when (and gnus-plugged (gnus-agent-method-p gnus-command-method))
800       (let ((gnus-agent-current-history
801              (gnus-agent-history-buffer)))
802         (unless (and gnus-agent-current-history
803                      (buffer-live-p gnus-agent-current-history))
804           (gnus-agent-open-history)
805           (setq gnus-agent-current-history
806                 (gnus-agent-history-buffer)))
807         (gnus-agent-fetch-articles
808          gnus-newsgroup-name
809          (list gnus-current-article))))))
810
811 ;;;
812 ;;; Internal functions
813 ;;;
814
815 (defun gnus-agent-save-active (method)
816   (gnus-agent-save-active-1 method 'gnus-active-to-gnus-format))
817
818 (defun gnus-agent-save-active-1 (method function)
819   (when (gnus-agent-method-p method)
820     (let* ((gnus-command-method method)
821            (new (gnus-make-hashtable (count-lines (point-min) (point-max))))
822            (file (gnus-agent-lib-file "active")))
823       (funcall function nil new)
824       (gnus-agent-write-active file new)
825       (erase-buffer)
826       (nnheader-insert-file-contents file))))
827
828 (defun gnus-agent-write-active (file new)
829   (let ((orig (gnus-make-hashtable (count-lines (point-min) (point-max))))
830         (file (gnus-agent-lib-file "active"))
831         elem osym)
832     (when (file-exists-p file)
833       (with-temp-buffer
834         (nnheader-insert-file-contents file)
835         (gnus-active-to-gnus-format nil orig))
836       (mapatoms
837        (lambda (sym)
838          (when (and sym (boundp sym))
839            (if (and (boundp (setq osym (intern (symbol-name sym) orig)))
840                     (setq elem (symbol-value osym)))
841                (progn
842                  (if (and (integerp (car (symbol-value sym)))
843                           (> (car elem) (car (symbol-value sym))))
844                      (setcar elem (car (symbol-value sym))))
845                  (if (integerp (cdr (symbol-value sym)))
846                      (setcdr elem (cdr (symbol-value sym)))))
847              (set (intern (symbol-name sym) orig) (symbol-value sym)))))
848        new))
849     (gnus-make-directory (file-name-directory file))
850     (let ((nnmail-active-file-coding-system gnus-agent-file-coding-system))
851       ;; The hashtable contains real names of groups,  no more prefix
852       ;; removing, so set `full' to `t'.
853       (gnus-write-active-file file orig t))))
854
855 (defun gnus-agent-save-groups (method)
856   (gnus-agent-save-active-1 method 'gnus-groups-to-gnus-format))
857
858 (defun gnus-agent-save-group-info (method group active)
859   (when (gnus-agent-method-p method)
860     (let* ((gnus-command-method method)
861            (coding-system-for-write nnheader-file-coding-system)
862            (file-name-coding-system nnmail-pathname-coding-system)
863            (file (gnus-agent-lib-file "active"))
864            oactive-min)
865       (gnus-make-directory (file-name-directory file))
866       (with-temp-file file
867         ;; Emacs got problem to match non-ASCII group in multibyte buffer.
868         (mm-disable-multibyte)
869         (when (file-exists-p file)
870           (nnheader-insert-file-contents file))
871         (goto-char (point-min))
872         (when (re-search-forward
873                (concat "^" (regexp-quote group) " ") nil t)
874           (save-excursion
875             (read (current-buffer))                      ;; max
876             (setq oactive-min (read (current-buffer))))  ;; min
877           (gnus-delete-line))
878         (insert (format "%S %d %d y\n" (intern group)
879                         (cdr active)
880                         (or oactive-min (car active))))
881         (goto-char (point-max))
882         (while (search-backward "\\." nil t)
883           (delete-char 1))))))
884
885 (defun gnus-agent-group-path (group)
886   "Translate GROUP into a path."
887   (if nnmail-use-long-file-names
888       (gnus-group-real-name group)
889     (nnheader-translate-file-chars
890      (nnheader-replace-chars-in-string
891       (nnheader-replace-duplicate-chars-in-string
892        (nnheader-replace-chars-in-string
893         (gnus-group-real-name group)
894         ?/ ?_)
895        ?. ?_)
896       ?. ?/))))
897
898 \f
899
900 (defun gnus-agent-get-function (method)
901   (if (gnus-online method)
902       (car method)
903     (require 'nnagent)
904     'nnagent))
905
906 ;;; History functions
907
908 (defun gnus-agent-history-buffer ()
909   (cdr (assoc (gnus-agent-method) gnus-agent-history-buffers)))
910
911 (defun gnus-agent-open-history ()
912   (save-excursion
913     (push (cons (gnus-agent-method)
914                 (set-buffer (gnus-get-buffer-create
915                              (format " *Gnus agent %s history*"
916                                      (gnus-agent-method)))))
917           gnus-agent-history-buffers)
918     (mm-disable-multibyte) ;; everything is binary
919     (erase-buffer)
920     (insert "\n")
921     (let ((file (gnus-agent-lib-file "history")))
922       (when (file-exists-p file)
923         (nnheader-insert-file-contents file))
924       (set (make-local-variable 'gnus-agent-file-name) file))))
925
926 (defun gnus-agent-save-history ()
927   (save-excursion
928     (set-buffer gnus-agent-current-history)
929     (gnus-make-directory (file-name-directory gnus-agent-file-name))
930     (let ((coding-system-for-write gnus-agent-file-coding-system))
931       (write-region (1+ (point-min)) (point-max)
932                     gnus-agent-file-name nil 'silent))))
933
934 (defun gnus-agent-close-history ()
935   (when (gnus-buffer-live-p gnus-agent-current-history)
936     (kill-buffer gnus-agent-current-history)
937     (setq gnus-agent-history-buffers
938           (delq (assoc (gnus-agent-method) gnus-agent-history-buffers)
939                 gnus-agent-history-buffers))))
940
941 (defun gnus-agent-enter-history (id group-arts date)
942   (save-excursion
943     (set-buffer gnus-agent-current-history)
944     (goto-char (point-max))
945     (let ((p (point)))
946       (insert id "\t" (number-to-string date) "\t")
947       (while group-arts
948         (insert (format "%S" (intern (caar group-arts)))
949                 " " (number-to-string (cdr (pop group-arts)))
950                 " "))
951       (insert "\n")
952       (while (search-backward "\\." p t)
953         (delete-char 1)))))
954
955 (defun gnus-agent-article-in-history-p (id)
956   (save-excursion
957     (set-buffer (gnus-agent-history-buffer))
958     (goto-char (point-min))
959     (search-forward (concat "\n" id "\t") nil t)))
960
961 (defun gnus-agent-history-path (id)
962   (save-excursion
963     (set-buffer (gnus-agent-history-buffer))
964     (goto-char (point-min))
965     (when (search-forward (concat "\n" id "\t") nil t)
966       (let ((method (gnus-agent-method)))
967         (let (paths group)
968           (while (not (numberp (setq group (read (current-buffer)))))
969             (push (concat method "/" group) paths))
970           (nreverse paths))))))
971
972 ;;;
973 ;;; Fetching
974 ;;;
975
976 (defun gnus-agent-fetch-articles (group articles)
977   "Fetch ARTICLES from GROUP and put them into the Agent."
978   (when articles
979     ;; Prune off articles that we have already fetched.
980     (while (and articles
981                 (cdr (assq (car articles) gnus-agent-article-alist)))
982       (pop articles))
983     (let ((arts articles))
984       (while (cdr arts)
985         (if (cdr (assq (cadr arts) gnus-agent-article-alist))
986             (setcdr arts (cddr arts))
987           (setq arts (cdr arts)))))
988     (when articles
989       (let ((dir (concat
990                   (gnus-agent-directory)
991                   (gnus-agent-group-path group) "/"))
992             (date (time-to-days (current-time)))
993             (case-fold-search t)
994             pos crosses id elem)
995         (gnus-make-directory dir)
996         (gnus-message 7 "Fetching articles for %s..." group)
997         ;; Fetch the articles from the backend.
998         (if (gnus-check-backend-function 'retrieve-articles group)
999             (setq pos (gnus-retrieve-articles articles group))
1000           (with-temp-buffer
1001             (let (article)
1002               (while (setq article (pop articles))
1003                 (gnus-message 10 "Fetching article %s for %s..."
1004                               article group)
1005                 (when (or
1006                        (gnus-backlog-request-article group article
1007                                                      nntp-server-buffer)
1008                        (gnus-request-article article group))
1009                   (goto-char (point-max))
1010                   (push (cons article (point)) pos)
1011                   (insert-buffer-substring nntp-server-buffer)))
1012               (copy-to-buffer nntp-server-buffer (point-min) (point-max))
1013               (setq pos (nreverse pos)))))
1014         ;; Then save these articles into the Agent.
1015         (save-excursion
1016           (set-buffer nntp-server-buffer)
1017           (while pos
1018             (narrow-to-region (cdar pos) (or (cdadr pos) (point-max)))
1019             (goto-char (point-min))
1020             (unless (eobp)  ;; Don't save empty articles.
1021               (when (search-forward "\n\n" nil t)
1022                 (when (search-backward "\nXrefs: " nil t)
1023                   ;; Handle cross posting.
1024                   (skip-chars-forward "^ ")
1025                   (skip-chars-forward " ")
1026                   (setq crosses nil)
1027                   (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) +")
1028                     (push (cons (buffer-substring (match-beginning 1)
1029                                                   (match-end 1))
1030                                 (buffer-substring (match-beginning 2)
1031                                                   (match-end 2)))
1032                           crosses)
1033                     (goto-char (match-end 0)))
1034                   (gnus-agent-crosspost crosses (caar pos))))
1035               (goto-char (point-min))
1036               (if (not (re-search-forward
1037                         "^Message-ID: *<\\([^>\n]+\\)>" nil t))
1038                   (setq id "No-Message-ID-in-article")
1039                 (setq id (buffer-substring (match-beginning 1) (match-end 1))))
1040               (let ((coding-system-for-write
1041                      gnus-agent-file-coding-system))
1042                 (write-region (point-min) (point-max)
1043                               (concat dir (number-to-string (caar pos)))
1044                               nil 'silent))
1045               (when (setq elem (assq (caar pos) gnus-agent-article-alist))
1046                 (setcdr elem t))
1047               (gnus-agent-enter-history
1048                id (or crosses (list (cons group (caar pos)))) date))
1049             (widen)
1050             (pop pos)))
1051         (gnus-agent-save-alist group)))))
1052
1053 (defun gnus-agent-crosspost (crosses article)
1054   (let (gnus-agent-article-alist group alist beg end)
1055     (save-excursion
1056       (set-buffer gnus-agent-overview-buffer)
1057       (when (nnheader-find-nov-line article)
1058         (forward-word 1)
1059         (setq beg (point))
1060         (setq end (progn (forward-line 1) (point)))))
1061     (while crosses
1062       (setq group (caar crosses))
1063       (unless (setq alist (assoc group gnus-agent-group-alist))
1064         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
1065               gnus-agent-group-alist))
1066       (setcdr alist (cons (cons (cdar crosses) t) (cdr alist)))
1067       (save-excursion
1068         (set-buffer (gnus-get-buffer-create (format " *Gnus agent overview %s*"
1069                                                     group)))
1070         (when (= (point-max) (point-min))
1071           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
1072           (ignore-errors
1073             (nnheader-insert-file-contents
1074              (gnus-agent-article-name ".overview" group))))
1075         (nnheader-find-nov-line (string-to-number (cdar crosses)))
1076         (insert (string-to-number (cdar crosses)))
1077         (insert-buffer-substring gnus-agent-overview-buffer beg end))
1078       (pop crosses))))
1079
1080 (defun gnus-agent-flush-cache ()
1081   (save-excursion
1082     (while gnus-agent-buffer-alist
1083       (set-buffer (cdar gnus-agent-buffer-alist))
1084       (let ((coding-system-for-write
1085              gnus-agent-file-coding-system))
1086         (write-region (point-min) (point-max)
1087                       (gnus-agent-article-name ".overview"
1088                                                (caar gnus-agent-buffer-alist))
1089                       nil 'silent))
1090       (pop gnus-agent-buffer-alist))
1091     (while gnus-agent-group-alist
1092       (with-temp-file (caar gnus-agent-group-alist)
1093         (princ (cdar gnus-agent-group-alist))
1094         (insert "\n"))
1095       (pop gnus-agent-group-alist))))
1096
1097 (defun gnus-agent-fetch-headers (group &optional force)
1098   (let ((articles
1099          (if (and gnus-agent-consider-all-articles
1100                   ;; Do not fetch all headers if the predicate
1101                   ;; implies that we only consider unread articles.
1102                   (not (gnus-predicate-implies-unread
1103                         (or (gnus-group-find-parameter
1104                              group 'agent-predicate t)
1105                             (cadr (gnus-group-category group))))))
1106              (gnus-uncompress-range (gnus-active group))
1107            (gnus-list-of-unread-articles group)))
1108         (gnus-decode-encoded-word-function 'identity)
1109         (file (gnus-agent-article-name ".overview" group))
1110         gnus-agent-cache)
1111     ;; Add articles with marks to the list of article headers we want to
1112     ;; fetch.  Don't fetch articles solely on the basis of a recent or seen
1113     ;; mark, but do fetch recent or seen articles if they have other, more
1114     ;; interesting marks.  (We have to fetch articles with boring marks
1115     ;; because otherwise the agent will remove their marks.)
1116     (dolist (arts (gnus-info-marks (gnus-get-info group)))
1117       (unless (memq (car arts) '(seen recent))
1118         (setq articles (gnus-range-add articles (cdr arts)))))
1119     (setq articles (sort (gnus-uncompress-sequence articles) '<))
1120     ;; Note which headers are fetched, and don't fetch those again.
1121     (gnus-agent-load-fetched-headers group)
1122     (let ((new-fetched (gnus-range-add gnus-agent-fetched-headers
1123                                        articles))
1124           (new-articles (gnus-list-range-difference
1125                          articles gnus-agent-fetched-headers)))
1126       (gnus-agent-save-fetched-headers group new-fetched)
1127       (setq articles new-articles))
1128     ;; Remove known articles.
1129     (when (gnus-agent-load-alist group)
1130       (let ((low (1+ (caar (last gnus-agent-article-alist))))
1131             (high (cdr (gnus-active group))))
1132         ;; I suspect a deeper problem here and I suspect that low
1133         ;; should never be greater than high.  But for the time being
1134         ;; we just work around the problem and abstain from frobbing
1135         ;; the article list in that case.  If anyone knows how to
1136         ;; properly deal with it, please holler.  -- kai
1137         (when (<= low high)
1138           (setq articles (gnus-list-range-intersection
1139                           articles (list (cons low high)))))))
1140     ;; Fetch them.
1141     (gnus-make-directory (nnheader-translate-file-chars
1142                           (file-name-directory file) t))
1143     (when articles
1144       (gnus-message 7 "Fetching headers for %s..." group)
1145       (save-excursion
1146         (set-buffer nntp-server-buffer)
1147         (unless (eq 'nov (gnus-retrieve-headers articles group))
1148           (nnvirtual-convert-headers))
1149         ;; Save these headers for later processing.
1150         (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
1151         (when (file-exists-p file)
1152           (gnus-agent-braid-nov group articles file))
1153         (let ((coding-system-for-write
1154                gnus-agent-file-coding-system))
1155           (write-region (point-min) (point-max) file nil 'silent))
1156         (gnus-agent-save-alist group articles nil)
1157         (gnus-agent-enter-history
1158          "last-header-fetched-for-session"
1159          (list (cons group (nth (- (length  articles) 1) articles)))
1160          (time-to-days (current-time)))
1161         articles))))
1162
1163 (defsubst gnus-agent-copy-nov-line (article)
1164   (let (art b e)
1165     (set-buffer gnus-agent-overview-buffer)
1166     (while (and (not (eobp))
1167                 (< (setq art (read (current-buffer))) article))
1168       (forward-line 1))
1169     (beginning-of-line)
1170     (if (or (eobp)
1171             (not (eq article art)))
1172         (set-buffer nntp-server-buffer)
1173       (setq b (point))
1174       (setq e (progn (forward-line 1) (point)))
1175       (set-buffer nntp-server-buffer)
1176       (insert-buffer-substring gnus-agent-overview-buffer b e))))
1177
1178 (defun gnus-agent-braid-nov (group articles file)
1179   (let (start last)
1180     (set-buffer gnus-agent-overview-buffer)
1181     (goto-char (point-min))
1182     (set-buffer nntp-server-buffer)
1183     (erase-buffer)
1184     (nnheader-insert-file-contents file)
1185     (goto-char (point-max))
1186     (unless (or (= (point-min) (point-max))
1187                 (progn
1188                   (forward-line -1)
1189                   (< (setq last (read (current-buffer))) (car articles))))
1190       ;; We do it the hard way.
1191       (nnheader-find-nov-line (car articles))
1192       (gnus-agent-copy-nov-line (pop articles))
1193       (while (and articles
1194                   (not (eobp)))
1195         (while (and (not (eobp))
1196                     (< (read (current-buffer)) (car articles)))
1197           (forward-line 1))
1198         (beginning-of-line)
1199         (unless (eobp)
1200           (gnus-agent-copy-nov-line (pop articles)))))
1201     ;; Copy the rest lines
1202     (set-buffer nntp-server-buffer)
1203     (goto-char (point-max))
1204     (when articles
1205       (when last
1206         (set-buffer gnus-agent-overview-buffer)
1207         (while (and (not (eobp))
1208                     (<= (read (current-buffer)) last))
1209           (forward-line 1))
1210         (beginning-of-line)
1211         (setq start (point))
1212         (set-buffer nntp-server-buffer))
1213       (insert-buffer-substring gnus-agent-overview-buffer start))))
1214
1215 (defun gnus-agent-load-alist (group)
1216   "Load the article-state alist for GROUP."
1217   (setq gnus-agent-article-alist
1218         (gnus-cache-file-contents
1219          (gnus-agent-article-name ".agentview" group)
1220          'gnus-agent-file-loading-cache
1221          'gnus-agent-read-file)))
1222
1223 ;; Why do we have to create the directory for the .fetched files (see
1224 ;; function gnus-agent-save-fetched-headers below) but not for the
1225 ;; .agentview files?
1226 (defun gnus-agent-save-alist (group &optional articles state)
1227   "Save the article-state alist for GROUP."
1228   (let* ((file-name-coding-system nnmail-pathname-coding-system)
1229          (prev (cons nil gnus-agent-article-alist))
1230          (all prev)
1231          print-level print-length item article)
1232     (while (setq article (pop articles))
1233       (while (and (cdr prev)
1234                  (< (caadr prev) article))
1235         (setq prev (cdr prev)))
1236       (cond
1237        ((not (cdr prev))
1238         (setcdr prev (list (cons article state))))
1239        ((> (caadr prev) article)
1240         (setcdr prev (cons (cons article state) (cdr prev))))
1241        ((= (caadr prev) article)
1242         (setcdr (cadr prev) state)))
1243       (setq prev (cdr prev)))
1244     (setq gnus-agent-article-alist (cdr all))
1245     (with-temp-file (gnus-agent-article-name ".agentview" group)
1246       (princ gnus-agent-article-alist (current-buffer))
1247       (insert "\n"))))
1248
1249 (defun gnus-agent-load-fetched-headers (group)
1250   "Load ranges of fetched headers for GROUP."
1251   (setq gnus-agent-fetched-headers
1252         (gnus-cache-file-contents
1253          (gnus-agent-article-name ".fetched" group)
1254          'gnus-agent-file-header-cache
1255          'gnus-agent-read-file)))
1256
1257 (defun gnus-agent-save-fetched-headers (group range)
1258   "Save ranges of fetched headers for GROUP.
1259 This range includes nonexisting articles."
1260   (let ((file-name-coding-system nnmail-pathname-coding-system)
1261         (fetched-file (gnus-agent-article-name ".fetched" group))
1262         print-level print-length)
1263     (setq gnus-agent-fetched-headers range)
1264     (unless (file-exists-p (file-name-directory fetched-file))
1265       (make-directory (file-name-directory fetched-file) t))
1266     (with-temp-file fetched-file
1267       (princ gnus-agent-fetched-headers (current-buffer))
1268       (insert "\n"))))
1269
1270 (defun gnus-agent-article-name (article group)
1271   (expand-file-name (if (stringp article) article (string-to-number article))
1272                     (file-name-as-directory
1273                      (expand-file-name (gnus-agent-group-path group)
1274                                        (gnus-agent-directory)))))
1275
1276 (defun gnus-agent-batch-confirmation (msg)
1277   "Show error message and return t."
1278   (gnus-message 1 msg)
1279   t)
1280
1281 ;;;###autoload
1282 (defun gnus-agent-batch-fetch ()
1283   "Start Gnus and fetch session."
1284   (interactive)
1285   (gnus)
1286   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1287     (gnus-agent-fetch-session))
1288   (gnus-group-exit))
1289
1290 (defun gnus-agent-fetch-session ()
1291   "Fetch all articles and headers that are eligible for fetching."
1292   (interactive)
1293   (unless gnus-agent-covered-methods
1294     (error "No servers are covered by the Gnus agent"))
1295   (unless gnus-plugged
1296     (error "Can't fetch articles while Gnus is unplugged"))
1297   (let ((methods gnus-agent-covered-methods)
1298         groups group gnus-command-method)
1299     (save-excursion
1300       (while methods
1301         (condition-case err
1302             (progn
1303               (setq gnus-command-method (car methods))
1304               (when (and (or (gnus-server-opened gnus-command-method)
1305                              (gnus-open-server gnus-command-method))
1306                          (gnus-online gnus-command-method))
1307                 (setq groups (gnus-groups-from-server (car methods)))
1308                 (gnus-agent-with-fetch
1309                   (while (setq group (pop groups))
1310                     (when (<= (gnus-group-level group) gnus-agent-handle-level)
1311                       (gnus-agent-fetch-group-1 group gnus-command-method))))))
1312           (error
1313            (unless (funcall gnus-agent-confirmation-function
1314                             (format "Error (%s).  Continue? " (cadr err)))
1315              (error "Cannot fetch articles into the Gnus agent")))
1316           (quit
1317            (unless (funcall gnus-agent-confirmation-function
1318                             (format "Quit fetching session (%s).  Continue? "
1319                                     (cadr err)))
1320              (signal 'quit "Cannot fetch articles into the Gnus agent"))))
1321         (pop methods))
1322       (run-hooks 'gnus-agent-fetch-hook)
1323       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
1324
1325 (defun gnus-agent-fetch-group-1 (group method)
1326   "Fetch GROUP."
1327   (let ((gnus-command-method method)
1328         (gnus-newsgroup-name group)
1329         gnus-newsgroup-dependencies gnus-newsgroup-headers
1330         gnus-newsgroup-scored gnus-headers gnus-score
1331         gnus-use-cache articles arts
1332         category predicate info marks score-param
1333         (gnus-summary-expunge-below gnus-summary-expunge-below)
1334         (gnus-summary-mark-below gnus-summary-mark-below)
1335         (gnus-orphan-score gnus-orphan-score)
1336         ;; Maybe some other gnus-summary local variables should also
1337         ;; be put here.
1338         )
1339     (unless (gnus-check-group group)
1340       (error "Can't open server for %s" group))
1341     ;; Fetch headers.
1342     (when (and (or (gnus-active group)
1343                    (gnus-activate-group group))
1344                (setq articles (gnus-agent-fetch-headers group))
1345                (let ((nntp-server-buffer gnus-agent-overview-buffer))
1346                  ;; Parse them and see which articles we want to fetch.
1347                  (setq gnus-newsgroup-dependencies
1348                        (make-vector (length articles) 0))
1349                  (setq gnus-newsgroup-headers
1350                        (gnus-get-newsgroup-headers-xover articles nil nil
1351                                                          group))
1352                  ;; Some articles may not exist, so update `articles'
1353                  ;; from what was actually found.  -- kai
1354                  (setq articles
1355                        (mapcar (lambda (x) (aref x 0))
1356                                gnus-newsgroup-headers))
1357                  ;; `gnus-agent-overview-buffer' may be killed for
1358                  ;; timeout reason.  If so, recreate it.
1359                  (gnus-agent-create-buffer)))
1360       (setq category (gnus-group-category group))
1361       (setq predicate
1362             (gnus-get-predicate
1363              (or (gnus-group-find-parameter group 'agent-predicate t)
1364                  (cadr category))))
1365       (if (memq predicate '(gnus-agent-true gnus-agent-false))
1366           ;; Simple implementation
1367           (setq arts (and (eq predicate 'gnus-agent-true) articles))
1368         (setq arts nil)
1369         (setq score-param
1370               (or (gnus-group-get-parameter group 'agent-score t)
1371                   (caddr category)))
1372         ;; Translate score-param into real one
1373         (cond
1374          ((not score-param))
1375          ((eq score-param 'file)
1376           (setq score-param (gnus-all-score-files group)))
1377          ((stringp (car score-param)))
1378          (t
1379           (setq score-param (list (list score-param)))))
1380         (when score-param
1381           (gnus-score-headers score-param))
1382         (while (setq gnus-headers (pop gnus-newsgroup-headers))
1383           (setq gnus-score
1384                 (or (cdr (assq (mail-header-number gnus-headers)
1385                                gnus-newsgroup-scored))
1386                     gnus-summary-default-score))
1387           (when (funcall predicate)
1388             (push (mail-header-number gnus-headers)
1389                   arts))))
1390       ;; Fetch the articles.
1391       (when arts
1392         (gnus-agent-fetch-articles group arts)))
1393     ;; Perhaps we have some additional articles to fetch.
1394     (dolist (mark gnus-agent-download-marks)
1395       (setq arts (assq mark (gnus-info-marks
1396                              (setq info (gnus-get-info group)))))
1397       (when (cdr arts)
1398         (gnus-message 8 "Agent is downloading marked articles...")
1399         (gnus-agent-fetch-articles
1400          group (gnus-uncompress-range (cdr arts)))
1401         (when (eq mark 'download)
1402           (setq marks (delq arts (gnus-info-marks info)))
1403           (gnus-info-set-marks info marks)
1404           (gnus-dribble-enter
1405            (concat "(gnus-group-set-info '"
1406                    (gnus-prin1-to-string info)
1407                    ")")))))))
1408
1409 ;;;
1410 ;;; Agent Category Mode
1411 ;;;
1412
1413 (defvar gnus-category-mode-hook nil
1414   "Hook run in `gnus-category-mode' buffers.")
1415
1416 (defvar gnus-category-line-format "     %(%20c%): %g\n"
1417   "Format of category lines.
1418
1419 Valid specifiers include:
1420 %c  Topic name (string)
1421 %g  The number of groups in the topic (integer)
1422
1423 General format specifiers can also be used.  See Info node
1424 `(gnus)Formatting Variables'.")
1425
1426 (defvar gnus-category-mode-line-format "Gnus: %%b"
1427   "The format specification for the category mode line.")
1428
1429 (defvar gnus-agent-short-article 100
1430   "Articles that have fewer lines than this are short.")
1431
1432 (defvar gnus-agent-long-article 200
1433   "Articles that have more lines than this are long.")
1434
1435 (defvar gnus-agent-low-score 0
1436   "Articles that have a score lower than this have a low score.")
1437
1438 (defvar gnus-agent-high-score 0
1439   "Articles that have a score higher than this have a high score.")
1440
1441
1442 ;;; Internal variables.
1443
1444 (defvar gnus-category-buffer "*Agent Category*")
1445
1446 (defvar gnus-category-line-format-alist
1447   `((?c gnus-tmp-name ?s)
1448     (?g gnus-tmp-groups ?d)))
1449
1450 (defvar gnus-category-mode-line-format-alist
1451   `((?u user-defined ?s)))
1452
1453 (defvar gnus-category-line-format-spec nil)
1454 (defvar gnus-category-mode-line-format-spec nil)
1455
1456 (defvar gnus-category-mode-map nil)
1457 (put 'gnus-category-mode 'mode-class 'special)
1458
1459 (unless gnus-category-mode-map
1460   (setq gnus-category-mode-map (make-sparse-keymap))
1461   (suppress-keymap gnus-category-mode-map)
1462
1463   (gnus-define-keys gnus-category-mode-map
1464     "q" gnus-category-exit
1465     "k" gnus-category-kill
1466     "c" gnus-category-copy
1467     "a" gnus-category-add
1468     "p" gnus-category-edit-predicate
1469     "g" gnus-category-edit-groups
1470     "s" gnus-category-edit-score
1471     "l" gnus-category-list
1472
1473     "\C-c\C-i" gnus-info-find-node
1474     "\C-c\C-b" gnus-bug))
1475
1476 (defvar gnus-category-menu-hook nil
1477   "*Hook run after the creation of the menu.")
1478
1479 (defun gnus-category-make-menu-bar ()
1480   (gnus-turn-off-edit-menu 'category)
1481   (unless (boundp 'gnus-category-menu)
1482     (easy-menu-define
1483      gnus-category-menu gnus-category-mode-map ""
1484      '("Categories"
1485        ["Add" gnus-category-add t]
1486        ["Kill" gnus-category-kill t]
1487        ["Copy" gnus-category-copy t]
1488        ["Edit predicate" gnus-category-edit-predicate t]
1489        ["Edit score" gnus-category-edit-score t]
1490        ["Edit groups" gnus-category-edit-groups t]
1491        ["Exit" gnus-category-exit t]))
1492
1493     (gnus-run-hooks 'gnus-category-menu-hook)))
1494
1495 (defun gnus-category-mode ()
1496   "Major mode for listing and editing agent categories.
1497
1498 All normal editing commands are switched off.
1499 \\<gnus-category-mode-map>
1500 For more in-depth information on this mode, read the manual
1501 (`\\[gnus-info-find-node]').
1502
1503 The following commands are available:
1504
1505 \\{gnus-category-mode-map}"
1506   (interactive)
1507   (when (gnus-visual-p 'category-menu 'menu)
1508     (gnus-category-make-menu-bar))
1509   (kill-all-local-variables)
1510   (gnus-simplify-mode-line)
1511   (setq major-mode 'gnus-category-mode)
1512   (setq mode-name "Category")
1513   (gnus-set-default-directory)
1514   (setq mode-line-process nil)
1515   (use-local-map gnus-category-mode-map)
1516   (buffer-disable-undo)
1517   (setq truncate-lines t)
1518   (setq buffer-read-only t)
1519   (gnus-run-hooks 'gnus-category-mode-hook))
1520
1521 (defalias 'gnus-category-position-point 'gnus-goto-colon)
1522
1523 (defun gnus-category-insert-line (category)
1524   (let* ((gnus-tmp-name (format "%s" (car category)))
1525          (gnus-tmp-groups (length (cadddr category))))
1526     (beginning-of-line)
1527     (gnus-add-text-properties
1528      (point)
1529      (prog1 (1+ (point))
1530        ;; Insert the text.
1531        (eval gnus-category-line-format-spec))
1532      (list 'gnus-category gnus-tmp-name))))
1533
1534 (defun gnus-enter-category-buffer ()
1535   "Go to the Category buffer."
1536   (interactive)
1537   (gnus-category-setup-buffer)
1538   (gnus-configure-windows 'category)
1539   (gnus-category-prepare))
1540
1541 (defun gnus-category-setup-buffer ()
1542   (unless (get-buffer gnus-category-buffer)
1543     (save-excursion
1544       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
1545       (gnus-category-mode))))
1546
1547 (defun gnus-category-prepare ()
1548   (gnus-set-format 'category-mode)
1549   (gnus-set-format 'category t)
1550   (let ((alist gnus-category-alist)
1551         (buffer-read-only nil))
1552     (erase-buffer)
1553     (while alist
1554       (gnus-category-insert-line (pop alist)))
1555     (goto-char (point-min))
1556     (gnus-category-position-point)))
1557
1558 (defun gnus-category-name ()
1559   (or (intern (get-text-property (gnus-point-at-bol) 'gnus-category))
1560       (error "No category on the current line")))
1561
1562 (defun gnus-category-read ()
1563   "Read the category alist."
1564   (setq gnus-category-alist
1565         (or (gnus-agent-read-file
1566              (nnheader-concat gnus-agent-directory "lib/categories"))
1567             (list (list 'default 'short nil nil)))))
1568
1569 (defun gnus-category-write ()
1570   "Write the category alist."
1571   (setq gnus-category-predicate-cache nil
1572         gnus-category-group-cache nil)
1573   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
1574   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
1575     (prin1 gnus-category-alist (current-buffer))))
1576
1577 (defun gnus-category-edit-predicate (category)
1578   "Edit the predicate for CATEGORY."
1579   (interactive (list (gnus-category-name)))
1580   (let ((info (assq category gnus-category-alist)))
1581     (gnus-edit-form
1582      (cadr info) (format "Editing the predicate for category %s" category)
1583      `(lambda (predicate)
1584         (setcar (cdr (assq ',category gnus-category-alist)) predicate)
1585         (gnus-category-write)
1586         (gnus-category-list)))))
1587
1588 (defun gnus-category-edit-score (category)
1589   "Edit the score expression for CATEGORY."
1590   (interactive (list (gnus-category-name)))
1591   (let ((info (assq category gnus-category-alist)))
1592     (gnus-edit-form
1593      (caddr info)
1594      (format "Editing the score expression for category %s" category)
1595      `(lambda (groups)
1596         (setcar (cddr (assq ',category gnus-category-alist)) groups)
1597         (gnus-category-write)
1598         (gnus-category-list)))))
1599
1600 (defun gnus-category-edit-groups (category)
1601   "Edit the group list for CATEGORY."
1602   (interactive (list (gnus-category-name)))
1603   (let ((info (assq category gnus-category-alist)))
1604     (gnus-edit-form
1605      (cadddr info) (format "Editing the group list for category %s" category)
1606      `(lambda (groups)
1607         (setcar (nthcdr 3 (assq ',category gnus-category-alist)) groups)
1608         (gnus-category-write)
1609         (gnus-category-list)))))
1610
1611 (defun gnus-category-kill (category)
1612   "Kill the current category."
1613   (interactive (list (gnus-category-name)))
1614   (let ((info (assq category gnus-category-alist))
1615         (buffer-read-only nil))
1616     (gnus-delete-line)
1617     (setq gnus-category-alist (delq info gnus-category-alist))
1618     (gnus-category-write)))
1619
1620 (defun gnus-category-copy (category to)
1621   "Copy the current category."
1622   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
1623   (let ((info (assq category gnus-category-alist)))
1624     (push (list to (gnus-copy-sequence (cadr info))
1625                 (gnus-copy-sequence (caddr info)) nil)
1626           gnus-category-alist)
1627     (gnus-category-write)
1628     (gnus-category-list)))
1629
1630 (defun gnus-category-add (category)
1631   "Create a new category."
1632   (interactive "SCategory name: ")
1633   (when (assq category gnus-category-alist)
1634     (error "Category %s already exists" category))
1635   (push (list category 'false nil nil)
1636         gnus-category-alist)
1637   (gnus-category-write)
1638   (gnus-category-list))
1639
1640 (defun gnus-category-list ()
1641   "List all categories."
1642   (interactive)
1643   (gnus-category-prepare))
1644
1645 (defun gnus-category-exit ()
1646   "Return to the group buffer."
1647   (interactive)
1648   (kill-buffer (current-buffer))
1649   (gnus-configure-windows 'group t))
1650
1651 ;; To avoid having 8-bit characters in the source file.
1652 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
1653
1654 (defvar gnus-category-predicate-alist
1655   '((spam . gnus-agent-spam-p)
1656     (short . gnus-agent-short-p)
1657     (long . gnus-agent-long-p)
1658     (low . gnus-agent-low-scored-p)
1659     (high . gnus-agent-high-scored-p)
1660     (read . gnus-agent-read-p)
1661     (true . gnus-agent-true)
1662     (false . gnus-agent-false))
1663   "Mapping from short score predicate symbols to predicate functions.")
1664
1665 (defun gnus-agent-spam-p ()
1666   "Say whether an article is spam or not."
1667   (unless gnus-agent-spam-hashtb
1668     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
1669   (if (not (equal (mail-header-references gnus-headers) ""))
1670       nil
1671     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
1672       (prog1
1673           (gnus-gethash string gnus-agent-spam-hashtb)
1674         (gnus-sethash string t gnus-agent-spam-hashtb)))))
1675
1676 (defun gnus-agent-short-p ()
1677   "Say whether an article is short or not."
1678   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
1679
1680 (defun gnus-agent-long-p ()
1681   "Say whether an article is long or not."
1682   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
1683
1684 (defun gnus-agent-low-scored-p ()
1685   "Say whether an article has a low score or not."
1686   (< gnus-score gnus-agent-low-score))
1687
1688 (defun gnus-agent-high-scored-p ()
1689   "Say whether an article has a high score or not."
1690   (> gnus-score gnus-agent-high-score))
1691
1692 (defun gnus-agent-read-p ()
1693   "Say whether an article is read or not."
1694   (gnus-member-of-range (mail-header-number gnus-headers)
1695                         (gnus-info-read (gnus-get-info gnus-newsgroup-name))))
1696
1697 (defun gnus-category-make-function (cat)
1698   "Make a function from category CAT."
1699   (let ((func (gnus-category-make-function-1 cat)))
1700     (if (and (= (length func) 1)
1701              (symbolp (car func)))
1702         (car func)
1703       (gnus-byte-compile `(lambda () ,func)))))
1704
1705 (defun gnus-agent-true ()
1706   "Return t."
1707   t)
1708
1709 (defun gnus-agent-false ()
1710   "Return nil."
1711   nil)
1712
1713 (defun gnus-category-make-function-1 (cat)
1714   "Make a function from category CAT."
1715   (cond
1716    ;; Functions are just returned as is.
1717    ((or (symbolp cat)
1718         (gnus-functionp cat))
1719     `(,(or (cdr (assq cat gnus-category-predicate-alist))
1720            cat)))
1721    ;; More complex category.
1722    ((consp cat)
1723     `(,(cond
1724         ((memq (car cat) '(& and))
1725          'and)
1726         ((memq (car cat) '(| or))
1727          'or)
1728         ((memq (car cat) gnus-category-not)
1729          'not))
1730       ,@(mapcar 'gnus-category-make-function-1 (cdr cat))))
1731    (t
1732     (error "Unknown category type: %s" cat))))
1733
1734 (defun gnus-get-predicate (predicate)
1735   "Return the predicate for CATEGORY."
1736   (or (cdr (assoc predicate gnus-category-predicate-cache))
1737       (let ((func (gnus-category-make-function predicate)))
1738         (setq gnus-category-predicate-cache
1739               (nconc gnus-category-predicate-cache
1740                      (list (cons predicate func))))
1741         func)))
1742
1743 (defun gnus-predicate-implies-unread (predicate)
1744   "Say whether PREDICATE implies unread articles only.
1745 It is okay to miss some cases, but there must be no false positives.
1746 That is, if this function returns true, then indeed the predicate must
1747 return only unread articles."
1748   ;; Todo: make this work in more cases.
1749   (equal predicate '(not read)))
1750
1751 (defun gnus-group-category (group)
1752   "Return the category GROUP belongs to."
1753   (unless gnus-category-group-cache
1754     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
1755     (let ((cs gnus-category-alist)
1756           groups cat)
1757       (while (setq cat (pop cs))
1758         (setq groups (cadddr cat))
1759         (while groups
1760           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
1761   (or (gnus-gethash group gnus-category-group-cache)
1762       (assq 'default gnus-category-alist)))
1763
1764 (defun gnus-agent-expire (&optional articles group force)
1765   "Expire all old articles.
1766 If you want to force expiring of certain articles, this function can
1767 take ARTICLES, GROUP and FORCE parameters as well.  Setting ARTICLES
1768 and GROUP without FORCE is not supported."
1769   (interactive)
1770   (let ((methods (if group
1771                      (list (gnus-find-method-for-group group))
1772                    gnus-agent-covered-methods))
1773         (day (if (numberp gnus-agent-expire-days)
1774                  (- (time-to-days (current-time)) gnus-agent-expire-days)
1775                nil))
1776         (current-day (time-to-days (current-time)))
1777         gnus-command-method sym arts pos
1778         history overview file histories elem art nov-file low info
1779         unreads marked article orig lowest highest found days)
1780     (save-excursion
1781       (setq overview (gnus-get-buffer-create " *expire overview*"))
1782       (while (setq gnus-command-method (pop methods))
1783         (when (file-exists-p (gnus-agent-lib-file "active"))
1784           (with-temp-buffer
1785             (nnheader-insert-file-contents (gnus-agent-lib-file "active"))
1786             (gnus-active-to-gnus-format
1787              gnus-command-method
1788              (setq orig (gnus-make-hashtable
1789                          (count-lines (point-min) (point-max))))))
1790           (let ((expiry-hashtb (gnus-make-hashtable 1023)))
1791             (gnus-agent-open-history)
1792             (set-buffer
1793              (setq gnus-agent-current-history
1794                    (setq history (gnus-agent-history-buffer))))
1795             (goto-char (point-min))
1796             (if (and articles group force) ;; point usless without art+group
1797                 (while (setq article (pop articles))
1798                   ;; try to find history entries for articles
1799                   (goto-char (point-min))
1800                   (if (re-search-forward 
1801                        (concat "^[^\t]*\t[^\t]*\t\(.* ?\)"
1802                                (format "%S" (gnus-group-prefixed-name
1803                                              group gnus-command-method))
1804                                " "
1805                                (number-to-string article)
1806                                " $")
1807                        nil t)
1808                       (setq pos (point))
1809                     (setq pos nil))
1810                   (setq sym (let ((obarray expiry-hashtb) s)
1811                               (intern group)))
1812                   (if (boundp sym)
1813                       (set sym (cons (cons article pos)
1814                                      (symbol-value sym)))
1815                     (set sym (list (cons article pos)))))
1816               ;; go through history file to find eligble articles
1817               (when (> (buffer-size) 1)
1818                 (goto-char (point-min))
1819                 (while (not (eobp))
1820                   (skip-chars-forward "^\t")
1821                   (if (let ((fetch-date (read (current-buffer))))
1822                         (if (numberp fetch-date)
1823                             ;; We now have the arrival day, so we see
1824                             ;; whether it's old enough to be expired.
1825                             (if (numberp day)
1826                                 (> fetch-date day)
1827                               (skip-chars-forward "\t")
1828                               (setq found nil
1829                                     days gnus-agent-expire-days)
1830                               (while (and (not found)
1831                                           days)
1832                                 (when (looking-at (caar days))
1833                                   (setq found (cadar days)))
1834                                 (pop days))
1835                               (> fetch-date (- current-day found)))
1836                           ;; History file is corrupted.
1837                           (gnus-message
1838                            5
1839                            (format "File %s is corrupted!"
1840                                    (gnus-agent-lib-file "history")))
1841                           (sit-for 1)
1842                           ;; Ignore it
1843                           t))
1844                       ;; New article; we don't expire it.
1845                       (forward-line 1)
1846                     ;; Old article.  Schedule it for possible nuking.
1847                     (while (not (eolp))
1848                       (setq sym (let ((obarray expiry-hashtb) s)
1849                                   (setq s (read (current-buffer)))
1850                                   (if (stringp s) (intern s) s)))
1851                       (if (boundp sym)
1852                           (set sym (cons (cons (read (current-buffer)) (point))
1853                                          (symbol-value sym)))
1854                         (set sym (list (cons (read (current-buffer))
1855                                              (point)))))
1856                       (skip-chars-forward " "))
1857                     (forward-line 1)))))
1858             ;; We now have all articles that can possibly be expired.
1859             (mapatoms
1860              (lambda (sym)
1861                (setq group (symbol-name sym)
1862                      arts (sort (symbol-value sym) 'car-less-than-car)
1863                      low (car (gnus-active group))
1864                      info (gnus-get-info group)
1865                      unreads (ignore-errors
1866                                (gnus-list-of-unread-articles group))
1867                      marked (nconc
1868                              (gnus-uncompress-range
1869                               (cdr (assq 'tick (gnus-info-marks info))))
1870                              (gnus-uncompress-range
1871                               (cdr (assq 'dormant
1872                                          (gnus-info-marks info)))))
1873                      nov-file (gnus-agent-article-name ".overview" group)
1874                      lowest nil
1875                      highest nil)
1876                (gnus-agent-load-alist group)
1877                (gnus-message 5 "Expiring articles in %s" group)
1878                (set-buffer overview)
1879                (erase-buffer)
1880                (when (file-exists-p nov-file)
1881                  (nnheader-insert-file-contents nov-file))
1882                (goto-char (point-min))
1883                (setq article 0)
1884                (while (setq elem (pop arts))
1885                  (setq article (car elem))
1886                  (when (or (null low)
1887                            (< article low)
1888                            gnus-agent-expire-all
1889                            (and (not (memq article unreads))
1890                                 (not (memq article marked)))
1891                            force)
1892                    ;; Find and nuke the NOV line.
1893                    (while (and (not (eobp))
1894                                (or (not (numberp
1895                                          (setq art (read (current-buffer)))))
1896                                    (< art article)))
1897                      (if (and (numberp art)
1898                               (file-exists-p
1899                                (gnus-agent-article-name
1900                                 (number-to-string art) group)))
1901                          (progn
1902                            (unless lowest
1903                              (setq lowest art))
1904                            (setq highest art)
1905                            (forward-line 1))
1906                        ;; Remove old NOV lines that have no articles.
1907                        (gnus-delete-line)))
1908                    (if (or (eobp)
1909                            (/= art article))
1910                        (beginning-of-line)
1911                      (gnus-delete-line))
1912                    ;; Nuke the article.
1913                    (when (file-exists-p
1914                           (setq file (gnus-agent-article-name
1915                                       (number-to-string article)
1916                                       group)))
1917                      (delete-file file))
1918                    ;; Schedule the history line for nuking.
1919                    (if (cdr elem)
1920                        (push (cdr elem) histories))))
1921                (gnus-make-directory (file-name-directory nov-file))
1922                (let ((coding-system-for-write
1923                       gnus-agent-file-coding-system))
1924                  (write-region (point-min) (point-max) nov-file nil 'silent))
1925                ;; Delete the unwanted entries in the alist.
1926                (setq gnus-agent-article-alist
1927                      (sort gnus-agent-article-alist 'car-less-than-car))
1928                (let* ((alist gnus-agent-article-alist)
1929                       (prev (cons nil alist))
1930                       (first prev)
1931                       expired)
1932                  (while (and alist
1933                              (<= (caar alist) article))
1934                    (if (or (not (cdar alist))
1935                            (not (file-exists-p
1936                                  (gnus-agent-article-name
1937                                   (number-to-string
1938                                    (caar alist))
1939                                   group))))
1940                        (progn
1941                          (push (caar alist) expired)
1942                          (setcdr prev (setq alist (cdr alist))))
1943                      (setq prev alist
1944                            alist (cdr alist))))
1945                  (setq gnus-agent-article-alist (cdr first))
1946                  (gnus-agent-save-alist group)
1947                  ;; Mark all articles up to the first article
1948                  ;; in `gnus-agent-article-alist' as read.
1949                  (when (and info (caar gnus-agent-article-alist))
1950                    (setcar (nthcdr 2 info)
1951                            (gnus-range-add
1952                             (nth 2 info)
1953                             (cons 1 (- (caar gnus-agent-article-alist) 1)))))
1954                  ;; Maybe everything has been expired from
1955                  ;; `gnus-agent-article-alist' and so the above marking as
1956                  ;; read could not be conducted, or there are
1957                  ;; expired article within the range of the alist.
1958                  (when (and info
1959                             expired
1960                             (or (not (caar gnus-agent-article-alist))
1961                                 (> (car expired)
1962                                    (caar gnus-agent-article-alist))))
1963                    (setcar (nthcdr 2 info)
1964                            (gnus-add-to-range
1965                             (nth 2 info)
1966                             (nreverse expired))))
1967                  (gnus-dribble-enter
1968                   (concat "(gnus-group-set-info '"
1969                           (gnus-prin1-to-string info)
1970                           ")")))
1971                (when lowest
1972                  (if (gnus-gethash group orig)
1973                      (setcar (gnus-gethash group orig) lowest)
1974                    (gnus-sethash group (cons lowest highest) orig))))
1975              expiry-hashtb)
1976             (set-buffer history)
1977             (setq histories (nreverse (sort histories '<)))
1978             (while histories
1979               (goto-char (pop histories))
1980               (gnus-delete-line))
1981             (gnus-agent-save-history)
1982             (gnus-agent-close-history)
1983             (gnus-write-active-file
1984              (gnus-agent-lib-file "active") orig))
1985           (gnus-message 4 "Expiry...done"))))))
1986
1987 ;;;###autoload
1988 (defun gnus-agent-batch ()
1989   "Start Gnus, send queue and fetch session."
1990   (interactive)
1991   (let ((init-file-user "")
1992         (gnus-always-read-dribble-file t))
1993     (gnus))
1994   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1995     (gnus-group-send-queue)
1996     (gnus-agent-fetch-session)))
1997
1998 (defun gnus-agent-retrieve-headers (articles group &optional fetch-old)
1999   (save-excursion
2000     (gnus-agent-create-buffer)
2001     (let ((gnus-decode-encoded-word-function 'identity)
2002           (file (gnus-agent-article-name ".overview" group))
2003           cached-articles uncached-articles)
2004       (gnus-make-directory (nnheader-translate-file-chars
2005                             (file-name-directory file) t))
2006       (when (file-exists-p file)
2007         (with-current-buffer gnus-agent-overview-buffer
2008           (erase-buffer)
2009           (let ((nnheader-file-coding-system
2010                  gnus-agent-file-coding-system))
2011             (nnheader-insert-nov-file file (car articles)))
2012           (nnheader-find-nov-line (car articles))
2013           (while (not (eobp))
2014             (when (looking-at "[0-9]")
2015               (push (read (current-buffer)) cached-articles))
2016             (forward-line 1))
2017           (setq cached-articles (nreverse cached-articles))))
2018       (if (setq uncached-articles
2019                 (gnus-sorted-difference articles cached-articles))
2020           (progn
2021             (set-buffer nntp-server-buffer)
2022             (erase-buffer)
2023             (let (gnus-agent-cache)
2024               (unless (eq 'nov
2025                           (gnus-retrieve-headers
2026                            uncached-articles group fetch-old))
2027                 (nnvirtual-convert-headers)))
2028             (set-buffer gnus-agent-overview-buffer)
2029             (erase-buffer)
2030             (set-buffer nntp-server-buffer)
2031             (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
2032             (when (and uncached-articles (file-exists-p file))
2033               (gnus-agent-braid-nov group uncached-articles file))
2034             (set-buffer nntp-server-buffer)
2035             (let ((coding-system-for-write
2036                    gnus-agent-file-coding-system))
2037               (write-region (point-min) (point-max) file nil 'silent))
2038             (gnus-agent-load-alist group)
2039             (gnus-agent-save-alist group uncached-articles nil)
2040             (gnus-agent-open-history)
2041             (setq gnus-agent-current-history (gnus-agent-history-buffer))
2042             (gnus-agent-enter-history
2043              "last-header-fetched-for-session"
2044              (list (cons group (nth (- (length  articles) 1) articles)))
2045              (time-to-days (current-time)))
2046             (gnus-agent-save-history))
2047         (set-buffer nntp-server-buffer)
2048         (erase-buffer)
2049         (insert-buffer-substring gnus-agent-overview-buffer)))
2050     (if (and fetch-old
2051              (not (numberp fetch-old)))
2052         t                               ; Don't remove anything.
2053       (nnheader-nov-delete-outside-range
2054        (if fetch-old (max 1 (- (car articles) fetch-old))
2055          (car articles))
2056        (car (last articles)))
2057       t)
2058     'nov))
2059
2060 (defun gnus-agent-request-article (article group)
2061   "Retrieve ARTICLE in GROUP from the agent cache."
2062   (let* ((gnus-command-method (gnus-find-method-for-group group))
2063          (file (concat
2064                   (gnus-agent-directory)
2065                   (gnus-agent-group-path group) "/"
2066                   (number-to-string article)))
2067          (buffer-read-only nil))
2068     (when (and (file-exists-p file)
2069                (> (nth 7 (file-attributes file)) 0))
2070       (erase-buffer)
2071       (gnus-kill-all-overlays)
2072       (let ((coding-system-for-read gnus-cache-coding-system))
2073         (insert-file-contents file))
2074       t)))
2075
2076 (defun gnus-agent-regenerate-group (group &optional clean)
2077   "Regenerate GROUP."
2078   (let ((dir (concat (gnus-agent-directory)
2079                      (gnus-agent-group-path group) "/"))
2080         (file (gnus-agent-article-name ".overview" group))
2081         n point arts alist header new-alist changed)
2082     (when (file-exists-p dir)
2083       (setq arts
2084             (sort (mapcar (lambda (name) (string-to-int name))
2085                           (directory-files dir nil "^[0-9]+$" t))
2086                   '<)))
2087     (gnus-make-directory (nnheader-translate-file-chars
2088                           (file-name-directory file) t))
2089     (mm-with-unibyte-buffer
2090       (if (file-exists-p file)
2091           (let ((nnheader-file-coding-system
2092                  gnus-agent-file-coding-system))
2093             (nnheader-insert-file-contents file)))
2094       (goto-char (point-min))
2095       (while (not (eobp))
2096         (while (not (or (eobp) (looking-at "[0-9]")))
2097           (setq point (point))
2098           (forward-line 1)
2099           (delete-region point (point)))
2100         (unless (eobp)
2101           (setq n (read (current-buffer)))
2102           (when (and arts (> n (car arts)))
2103             (beginning-of-line)
2104             (while (and arts (> n (car arts)))
2105               (message "Regenerating NOV %s %d..." group (car arts))
2106               (mm-with-unibyte-buffer
2107                 (nnheader-insert-file-contents
2108                  (concat dir (number-to-string (car arts))))
2109                 (nnheader-remove-body)
2110                 (setq header (nnheader-parse-naked-head)))
2111               (mail-header-set-number header (car arts))
2112               (nnheader-insert-nov header)
2113               (setq changed t)
2114               (push (cons (car arts) t) alist)
2115               (pop arts)))
2116           (if (and arts (= n (car arts)))
2117               (progn
2118                 (push (cons n t) alist)
2119                 (pop arts))
2120             (push (cons n nil) alist))
2121           (forward-line 1)))
2122       (if changed
2123           (let ((coding-system-for-write gnus-agent-file-coding-system))
2124             (write-region (point-min) (point-max) file nil 'silent))))
2125     (setq gnus-agent-article-alist nil)
2126     (unless clean
2127       (gnus-agent-load-alist group))
2128     (setq alist (sort alist 'car-less-than-car))
2129     (setq gnus-agent-article-alist (sort gnus-agent-article-alist
2130                                          'car-less-than-car))
2131     (while (and alist gnus-agent-article-alist)
2132       (cond
2133        ((< (caar alist) (caar gnus-agent-article-alist))
2134         (push (pop alist) new-alist))
2135        ((> (caar alist) (caar gnus-agent-article-alist))
2136         (push (list (car (pop gnus-agent-article-alist))) new-alist))
2137        (t
2138         (pop gnus-agent-article-alist)
2139         (while (and gnus-agent-article-alist
2140                     (= (caar alist) (caar gnus-agent-article-alist)))
2141           (pop gnus-agent-article-alist))
2142         (push (pop alist) new-alist))))
2143     (while alist
2144       (push (pop alist) new-alist))
2145     (while gnus-agent-article-alist
2146       (push (list (car (pop gnus-agent-article-alist))) new-alist))
2147     (setq gnus-agent-article-alist (nreverse new-alist))
2148     (gnus-agent-save-alist group)))
2149
2150 (defun gnus-agent-regenerate-history (group article)
2151   (let ((file (concat (gnus-agent-directory)
2152                       (gnus-agent-group-path group) "/"
2153                       (number-to-string article))) id)
2154     (mm-with-unibyte-buffer
2155       (nnheader-insert-file-contents file)
2156       (message-narrow-to-head)
2157       (goto-char (point-min))
2158       (if (not (re-search-forward "^Message-ID: *<\\([^>\n]+\\)>" nil t))
2159           (setq id "No-Message-ID-in-article")
2160         (setq id (buffer-substring (match-beginning 1) (match-end 1))))
2161       (gnus-agent-enter-history
2162        id (list (cons group article))
2163        (time-to-days (nth 5 (file-attributes file)))))))
2164
2165 ;;;###autoload
2166 (defun gnus-agent-regenerate (&optional clean)
2167   "Regenerate all agent covered files.
2168 If CLEAN, don't read existing active and agentview files."
2169   (interactive "P")
2170   (message "Regenerating Gnus agent files...")
2171   (dolist (gnus-command-method gnus-agent-covered-methods)
2172     (let ((active-file (gnus-agent-lib-file "active"))
2173           history-hashtb active-hashtb active-changed
2174           history-changed point)
2175       (gnus-make-directory (file-name-directory active-file))
2176       (if clean
2177           (setq active-hashtb (gnus-make-hashtable 1000))
2178         (mm-with-unibyte-buffer
2179           (if (file-exists-p active-file)
2180               (let ((nnheader-file-coding-system
2181                      gnus-agent-file-coding-system))
2182                 (nnheader-insert-file-contents active-file))
2183             (setq active-changed t))
2184           (gnus-active-to-gnus-format
2185            nil (setq active-hashtb
2186                      (gnus-make-hashtable
2187                       (count-lines (point-min) (point-max)))))))
2188       (gnus-agent-open-history)
2189       (setq history-hashtb (gnus-make-hashtable 1000))
2190       (with-current-buffer
2191           (setq gnus-agent-current-history (gnus-agent-history-buffer))
2192         (goto-char (point-min))
2193         (forward-line 1)
2194         (while (not (eobp))
2195           (if (looking-at
2196                "\\([^\t\n]+\\)\t[0-9]+\t\\([^ \n]+\\) \\([0-9]+\\)")
2197               (progn
2198                 (unless (string= (match-string 1)
2199                                  "last-header-fetched-for-session")
2200                   (gnus-sethash (match-string 2)
2201                                 (cons (string-to-number (match-string 3))
2202                                       (gnus-gethash-safe (match-string 2)
2203                                                          history-hashtb))
2204                                 history-hashtb))
2205                 (forward-line 1))
2206             (setq point (point))
2207             (forward-line 1)
2208             (delete-region point (point))
2209             (setq history-changed t))))
2210       (dolist (group (gnus-groups-from-server gnus-command-method))
2211         (gnus-agent-regenerate-group group clean)
2212         (let ((min (or (caar gnus-agent-article-alist) 1))
2213               (max (or (caar (last gnus-agent-article-alist)) 0))
2214               (active (gnus-gethash-safe (gnus-group-real-name group)
2215                                          active-hashtb)))
2216           (if (not active)
2217               (progn
2218                 (setq active (cons min max)
2219                       active-changed t)
2220                 (gnus-sethash group active active-hashtb))
2221             (when (> (car active) min)
2222               (setcar active min)
2223               (setq active-changed t))
2224             (when (< (cdr active) max)
2225               (setcdr active max)
2226               (setq active-changed t))))
2227         (let ((arts (sort (gnus-gethash-safe group history-hashtb) '<))
2228               n)
2229           (gnus-sethash group arts history-hashtb)
2230           (while (and arts gnus-agent-article-alist)
2231             (cond
2232              ((> (car arts) (caar gnus-agent-article-alist))
2233               (when (cdar gnus-agent-article-alist)
2234                 (gnus-agent-regenerate-history
2235                  group (caar gnus-agent-article-alist))
2236                 (setq history-changed t))
2237               (setq n (car (pop gnus-agent-article-alist)))
2238               (while (and gnus-agent-article-alist
2239                           (= n (caar gnus-agent-article-alist)))
2240                 (pop gnus-agent-article-alist)))
2241              ((< (car arts) (caar gnus-agent-article-alist))
2242               (setq n (pop arts))
2243               (while (and arts (= n (car arts)))
2244                 (pop arts)))
2245              (t
2246               (setq n (car (pop gnus-agent-article-alist)))
2247               (while (and gnus-agent-article-alist
2248                           (= n (caar gnus-agent-article-alist)))
2249                 (pop gnus-agent-article-alist))
2250               (setq n (pop arts))
2251               (while (and arts (= n (car arts)))
2252                 (pop arts)))))
2253           (while gnus-agent-article-alist
2254             (when (cdar gnus-agent-article-alist)
2255               (gnus-agent-regenerate-history
2256                group (caar gnus-agent-article-alist))
2257               (setq history-changed t))
2258             (pop gnus-agent-article-alist))))
2259       (when history-changed
2260         (message "Regenerate the history file of %s:%s"
2261                  (car gnus-command-method)
2262                  (cadr gnus-command-method))
2263         (gnus-agent-save-history))
2264       (gnus-agent-close-history)
2265       (when active-changed
2266         (message "Regenerate %s" active-file)
2267         (let ((nnmail-active-file-coding-system gnus-agent-file-coding-system))
2268           (gnus-write-active-file active-file active-hashtb)))))
2269   (message "Regenerating Gnus agent files...done"))
2270
2271 (defun gnus-agent-go-online (&optional force)
2272   "Switch servers into online status."
2273   (interactive (list t))
2274   (dolist (server gnus-opened-servers)
2275     (when (eq (nth 1 server) 'offline)
2276       (if (if (eq force 'ask)
2277               (gnus-y-or-n-p
2278                (format "Switch %s:%s into online status? "
2279                        (caar server) (cadar server)))
2280             force)
2281           (setcar (nthcdr 1 server) 'close)))))
2282
2283 (defun gnus-agent-toggle-group-plugged (group)
2284   "Toggle the status of the server of the current group."
2285   (interactive (list (gnus-group-group-name)))
2286   (let* ((method (gnus-find-method-for-group group))
2287          (status (cadr (assoc method gnus-opened-servers))))
2288     (if (eq status 'offline)
2289         (gnus-server-set-status method 'closed)
2290       (gnus-close-server method)
2291       (gnus-server-set-status method 'offline))
2292     (message "Turn %s:%s from %s to %s." (car method) (cadr method)
2293              (if (eq status 'offline) 'offline 'online)
2294              (if (eq status 'offline) 'online 'offline))))
2295
2296 (provide 'gnus-agent)
2297
2298 ;;; gnus-agent.el ends here