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