* nnheader.el (nnheader-replace-chars-in-string): Use `static-if'.
[elisp/gnus.git-] / lisp / gnus-agent.el
1 ;;; gnus-agent.el --- unplugged support for Semi-gnus
2 ;; Copyright (C) 1997, 1998, 1999, 2000 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;;      Tatsuya Ichikawa <t-ichi@po.shiojiri.ne.jp>
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 (eval-when-compile (require 'cl))
28 (eval-when-compile (require 'gnus-clfns))
29
30 (require 'gnus)
31 (require 'gnus-cache)
32 (require 'nnvirtual)
33 (require 'gnus-sum)
34 (eval-when-compile
35   (require 'timer)
36   (require 'gnus-score)
37   (require 'gnus-group))
38
39 (defcustom gnus-agent-directory (nnheader-concat gnus-directory "agent/")
40   "Where the Gnus agent will store its files."
41   :group 'gnus-agent
42   :type 'directory)
43
44 (defcustom gnus-agent-plugged-hook nil
45   "Hook run when plugging into the network."
46   :group 'gnus-agent
47   :type 'hook)
48
49 (defcustom gnus-agent-unplugged-hook nil
50   "Hook run when unplugging from the network."
51   :group 'gnus-agent
52   :type 'hook)
53
54 (defcustom gnus-agent-handle-level gnus-level-subscribed
55   "Groups on levels higher than this variable will be ignored by the Agent."
56   :group 'gnus-agent
57   :type 'integer)
58
59 (defcustom gnus-agent-expire-days 7
60   "Read articles older than this will be expired."
61   :group 'gnus-agent
62   :type 'integer)
63
64 (defcustom gnus-agent-expire-all nil
65   "If non-nil, also expire unread, ticked and dormant articles.
66 If nil, only read articles will be expired."
67   :group 'gnus-agent
68   :type 'boolean)
69
70 (defcustom gnus-agent-group-mode-hook nil
71   "Hook run in Agent group minor modes."
72   :group 'gnus-agent
73   :type 'hook)
74
75 (defcustom gnus-agent-summary-mode-hook nil
76   "Hook run in Agent summary minor modes."
77   :group 'gnus-agent
78   :type 'hook)
79
80 (defcustom gnus-agent-server-mode-hook nil
81   "Hook run in Agent summary minor modes."
82   :group 'gnus-agent
83   :type 'hook)
84
85 (defcustom gnus-agent-confirmation-function 'y-or-n-p
86   "Function to confirm when error happens."
87   :group 'gnus-agent
88   :type 'function)
89
90 (defcustom gnus-agent-large-newsgroup nil
91   "*The number of articles which indicates a large newsgroup.
92 If the number of unread articles exceeds it, The number of articles to be
93 fetched will be limited to it. If not a positive integer, never consider it."
94   :group 'gnus-agent
95   :type '(choice (const nil)
96                  (integer :tag "Number")))
97
98 ;;; Internal variables
99
100 (defvar gnus-agent-history-buffers nil)
101 (defvar gnus-agent-buffer-alist nil)
102 (defvar gnus-agent-article-alist nil)
103 (defvar gnus-agent-group-alist nil)
104 (defvar gnus-agent-covered-methods nil)
105 (defvar gnus-category-alist nil)
106 (defvar gnus-agent-current-history nil)
107 (defvar gnus-agent-overview-buffer nil)
108 (defvar gnus-category-predicate-cache nil)
109 (defvar gnus-category-group-cache nil)
110 (defvar gnus-agent-spam-hashtb nil)
111 (defvar gnus-agent-file-name nil)
112 (defvar gnus-agent-send-mail-function nil)
113 (defvar gnus-agent-file-coding-system 'raw-text)
114
115 (defconst gnus-agent-scoreable-headers
116   '("subject" "from" "date" "message-id" "references" "chars" "lines" "xref")
117   "Headers that are considered when scoring articles for download via the Agent.")
118
119 ;; Dynamic variables
120 (defvar gnus-headers)
121 (defvar gnus-score)
122
123 ;;;
124 ;;; Setup
125 ;;;
126
127 (defun gnus-open-agent ()
128   (setq gnus-agent t)
129   (gnus-agent-read-servers)
130   (gnus-category-read)
131   (gnus-agent-create-buffer)
132   (add-hook 'gnus-group-mode-hook 'gnus-agent-mode)
133   (add-hook 'gnus-summary-mode-hook 'gnus-agent-mode)
134   (add-hook 'gnus-server-mode-hook 'gnus-agent-mode))
135
136 (defun gnus-agent-create-buffer ()
137   (if (gnus-buffer-live-p gnus-agent-overview-buffer)
138       t
139     (setq gnus-agent-overview-buffer
140           (gnus-get-buffer-create " *Gnus agent overview*"))
141     (with-current-buffer gnus-agent-overview-buffer
142       (set-buffer-multibyte t))
143     nil))
144
145 (gnus-add-shutdown 'gnus-close-agent 'gnus)
146
147 (defun gnus-close-agent ()
148   (setq gnus-agent-covered-methods nil
149         gnus-category-predicate-cache nil
150         gnus-category-group-cache nil
151         gnus-agent-spam-hashtb nil)
152   (gnus-kill-buffer gnus-agent-overview-buffer))
153
154 ;;;
155 ;;; Utility functions
156 ;;;
157
158 (defun gnus-agent-read-file (file)
159   "Load FILE and do a `read' there."
160   (with-temp-buffer
161     (ignore-errors
162       (nnheader-insert-file-contents file)
163       (goto-char (point-min))
164       (read (current-buffer)))))
165
166 (defsubst gnus-agent-method ()
167   (concat (symbol-name (car gnus-command-method)) "/"
168           (if (equal (cadr gnus-command-method) "")
169               "unnamed"
170             (cadr gnus-command-method))))
171
172 (defsubst gnus-agent-directory ()
173   "Path of the Gnus agent directory."
174   (nnheader-concat gnus-agent-directory
175                    (nnheader-translate-file-chars (gnus-agent-method)) "/"))
176
177 (defun gnus-agent-lib-file (file)
178   "The full path of the Gnus agent library FILE."
179   (concat (gnus-agent-directory) "agent.lib/" file))
180
181 ;;; Fetching setup functions.
182
183 (defun gnus-agent-start-fetch ()
184   "Initialize data structures for efficient fetching."
185   (gnus-agent-open-history)
186   (setq gnus-agent-current-history (gnus-agent-history-buffer))
187   (gnus-agent-create-buffer))
188
189 (defun gnus-agent-stop-fetch ()
190   "Save all data structures and clean up."
191   (gnus-agent-save-history)
192   (gnus-agent-close-history)
193   (setq gnus-agent-spam-hashtb nil)
194   (save-excursion
195     (set-buffer nntp-server-buffer)
196     (widen)))
197
198 (defmacro gnus-agent-with-fetch (&rest forms)
199   "Do FORMS safely."
200   `(unwind-protect
201        (progn
202          (gnus-agent-start-fetch)
203          ,@forms)
204      (gnus-agent-stop-fetch)))
205
206 (put 'gnus-agent-with-fetch 'lisp-indent-function 0)
207 (put 'gnus-agent-with-fetch 'edebug-form-spec '(body))
208
209 ;;;
210 ;;; Mode infestation
211 ;;;
212
213 (defvar gnus-agent-mode-hook nil
214   "Hook run when installing agent mode.")
215
216 (defvar gnus-agent-mode nil)
217 (defvar gnus-agent-mode-status '(gnus-agent-mode " Plugged"))
218
219 (defun gnus-agent-mode ()
220   "Minor mode for providing a agent support in Gnus buffers."
221   (let* ((buffer (progn (string-match "^gnus-\\(.*\\)-mode$"
222                                       (symbol-name major-mode))
223                         (match-string 1 (symbol-name major-mode))))
224          (mode (intern (format "gnus-agent-%s-mode" buffer))))
225     (set (make-local-variable 'gnus-agent-mode) t)
226     (set mode nil)
227     (set (make-local-variable mode) t)
228     ;; Set up the menu.
229     (when (gnus-visual-p 'agent-menu 'menu)
230       (funcall (intern (format "gnus-agent-%s-make-menu-bar" buffer))))
231     (unless (assq 'gnus-agent-mode minor-mode-alist)
232       (push gnus-agent-mode-status minor-mode-alist))
233     (unless (assq mode minor-mode-map-alist)
234       (push (cons mode (symbol-value (intern (format "gnus-agent-%s-mode-map"
235                                                      buffer))))
236             minor-mode-map-alist))
237     (when (eq major-mode 'gnus-group-mode)
238       (gnus-agent-toggle-plugged gnus-plugged))
239     (gnus-run-hooks 'gnus-agent-mode-hook
240                     (intern (format "gnus-agent-%s-mode-hook" buffer)))))
241
242 (defvar gnus-agent-group-mode-map (make-sparse-keymap))
243 (gnus-define-keys gnus-agent-group-mode-map
244   "Ju" gnus-agent-fetch-groups
245   "Jc" gnus-enter-category-buffer
246   "Jj" gnus-agent-toggle-plugged
247   "Js" gnus-agent-fetch-session
248   "JY" gnus-agent-synchronize
249   "JS" gnus-group-send-drafts
250   "Ja" gnus-agent-add-group
251   "Jr" gnus-agent-remove-group)
252
253 (defun gnus-agent-group-make-menu-bar ()
254   (unless (boundp 'gnus-agent-group-menu)
255     (easy-menu-define
256      gnus-agent-group-menu gnus-agent-group-mode-map ""
257      '("Agent"
258        ["Toggle plugged" gnus-agent-toggle-plugged t]
259        ["List categories" gnus-enter-category-buffer t]
260        ["Send drafts" gnus-group-send-drafts gnus-plugged]
261        ("Fetch"
262         ["All" gnus-agent-fetch-session gnus-plugged]
263         ["Group" gnus-agent-fetch-group gnus-plugged])))))
264
265 (defvar gnus-agent-summary-mode-map (make-sparse-keymap))
266 (gnus-define-keys gnus-agent-summary-mode-map
267   "Jj" gnus-agent-toggle-plugged
268   "J#" gnus-agent-mark-article
269   "J\M-#" gnus-agent-unmark-article
270   "@" gnus-agent-toggle-mark
271   "Jc" gnus-agent-catchup)
272
273 (defun gnus-agent-summary-make-menu-bar ()
274   (unless (boundp 'gnus-agent-summary-menu)
275     (easy-menu-define
276      gnus-agent-summary-menu gnus-agent-summary-mode-map ""
277      '("Agent"
278        ["Toggle plugged" gnus-agent-toggle-plugged t]
279        ["Mark as downloadable" gnus-agent-mark-article t]
280        ["Unmark as downloadable" gnus-agent-unmark-article t]
281        ["Toggle mark" gnus-agent-toggle-mark t]
282        ["Catchup undownloaded" gnus-agent-catchup t]))))
283
284 (defvar gnus-agent-server-mode-map (make-sparse-keymap))
285 (gnus-define-keys gnus-agent-server-mode-map
286   "Jj" gnus-agent-toggle-plugged
287   "Ja" gnus-agent-add-server
288   "Jr" gnus-agent-remove-server)
289
290 (defun gnus-agent-server-make-menu-bar ()
291   (unless (boundp 'gnus-agent-server-menu)
292     (easy-menu-define
293      gnus-agent-server-menu gnus-agent-server-mode-map ""
294      '("Agent"
295        ["Toggle plugged" gnus-agent-toggle-plugged t]
296        ["Add" gnus-agent-add-server t]
297        ["Remove" gnus-agent-remove-server t]))))
298
299 (defun gnus-agent-toggle-plugged (plugged)
300   "Toggle whether Gnus is unplugged or not."
301   (interactive (list (not gnus-plugged)))
302   (if plugged
303       (progn
304         (setq gnus-plugged plugged)
305         (gnus-run-hooks 'gnus-agent-plugged-hook)
306         (setcar (cdr gnus-agent-mode-status) " Plugged"))
307     (gnus-agent-close-connections)
308     (setq gnus-plugged plugged)
309     (gnus-run-hooks 'gnus-agent-unplugged-hook)
310     (setcar (cdr gnus-agent-mode-status) " Unplugged"))
311   (force-mode-line-update))
312
313 (defun gnus-agent-close-connections ()
314   "Close all methods covered by the Gnus agent."
315   (let ((methods gnus-agent-covered-methods))
316     (while methods
317       (gnus-close-server (pop methods)))))
318
319 ;;;###autoload
320 (defun gnus-unplugged ()
321   "Start Gnus unplugged."
322   (interactive)
323   (setq gnus-plugged nil)
324   (gnus))
325
326 ;;;###autoload
327 (defun gnus-plugged ()
328   "Start Gnus plugged."
329   (interactive)
330   (setq gnus-plugged t)
331   (gnus))
332
333 ;;;###autoload
334 (defun gnus-agentize ()
335   "Allow Gnus to be an offline newsreader.
336 The normal usage of this command is to put the following as the
337 last form in your `.gnus.el' file:
338
339 \(gnus-agentize)
340
341 This will modify the `gnus-before-startup-hook', `gnus-post-method',
342 and `message-send-mail-function' variables, and install the Gnus
343 agent minor mode in all Gnus buffers."
344   (interactive)
345   (gnus-open-agent)
346   (add-hook 'gnus-setup-news-hook 'gnus-agent-queue-setup)
347   (unless gnus-agent-send-mail-function
348     (setq gnus-agent-send-mail-function message-send-mail-function
349           message-send-mail-function 'gnus-agent-send-mail))
350   (unless gnus-agent-covered-methods
351     (setq gnus-agent-covered-methods (list gnus-select-method))))
352
353 (defun gnus-agent-queue-setup ()
354   "Make sure the queue group exists."
355   (unless (gnus-gethash "nndraft:queue" gnus-newsrc-hashtb)
356     (gnus-request-create-group "queue" '(nndraft ""))
357     (let ((gnus-level-default-subscribed 1))
358       (gnus-subscribe-group "nndraft:queue" nil '(nndraft "")))
359     (gnus-group-set-parameter
360      "nndraft:queue" 'gnus-dummy '((gnus-draft-mode)))))
361
362 (defun gnus-agent-send-mail ()
363   (if gnus-plugged
364       (funcall gnus-agent-send-mail-function)
365     (goto-char (point-min))
366     (re-search-forward
367      (concat "^" (regexp-quote mail-header-separator) "\n"))
368     (replace-match "\n")
369     (gnus-agent-insert-meta-information 'mail)
370     (gnus-request-accept-article "nndraft:queue" nil t t)))
371
372 (defun gnus-agent-insert-meta-information (type &optional method)
373   "Insert meta-information into the message that says how it's to be posted.
374 TYPE can be either `mail' or `news'.  If the latter METHOD can
375 be a select method."
376   (save-excursion
377     (message-remove-header gnus-agent-meta-information-header)
378     (goto-char (point-min))
379     (insert gnus-agent-meta-information-header ": "
380             (symbol-name type) " " (format "%S" method)
381             "\n")
382     (forward-char -1)
383     (while (search-backward "\n" nil t)
384       (replace-match "\\n" t t))))
385
386 ;;;
387 ;;; Group mode commands
388 ;;;
389
390 (defun gnus-agent-fetch-groups (n)
391   "Put all new articles in the current groups into the Agent."
392   (interactive "P")
393   (unless gnus-plugged
394     (error "Groups can't be fetched when Gnus is unplugged"))
395   (gnus-group-iterate n 'gnus-agent-fetch-group))
396
397 (defun gnus-agent-fetch-group (group)
398   "Put all new articles in GROUP into the Agent."
399   (interactive (list (gnus-group-group-name)))
400   (unless gnus-plugged
401     (error "Groups can't be fetched when Gnus is unplugged"))
402   (unless group
403     (error "No group on the current line"))
404   (let ((gnus-command-method (gnus-find-method-for-group group)))
405     (gnus-agent-with-fetch
406       (gnus-agent-fetch-group-1 group gnus-command-method)
407       (gnus-message 5 "Fetching %s...done" group))))
408
409 (defun gnus-agent-add-group (category arg)
410   "Add the current group to an agent category."
411   (interactive
412    (list
413     (intern
414      (completing-read
415       "Add to category: "
416       (mapcar (lambda (cat) (list (symbol-name (car cat))))
417               gnus-category-alist)
418       nil t))
419     current-prefix-arg))
420   (let ((cat (assq category gnus-category-alist))
421         c groups)
422     (gnus-group-iterate arg
423       (lambda (group)
424         (when (cadddr (setq c (gnus-group-category group)))
425           (setf (cadddr c) (delete group (cadddr c))))
426         (push group groups)))
427     (setf (cadddr cat) (nconc (cadddr cat) groups))
428     (gnus-category-write)))
429
430 (defun gnus-agent-remove-group (arg)
431   "Remove the current group from its agent category, if any."
432   (interactive "P")
433   (let (c)
434     (gnus-group-iterate arg
435       (lambda (group)
436         (when (cadddr (setq c (gnus-group-category group)))
437           (setf (cadddr c) (delete group (cadddr c))))))
438     (gnus-category-write)))
439
440 (defun gnus-agent-synchronize ()
441   "Synchronize local, unplugged, data with backend.
442 Currently sends flag setting requests, if any."
443   (interactive)
444   (save-excursion
445     (dolist (gnus-command-method gnus-agent-covered-methods)
446       (when (file-exists-p (gnus-agent-lib-file "flags"))
447         (set-buffer (get-buffer-create " *Gnus Agent flag synchronize*"))
448         (erase-buffer)
449         (nnheader-insert-file-contents (gnus-agent-lib-file "flags"))
450         (if (null (gnus-check-server gnus-command-method))
451             (message "Couldn't open server %s" (nth 1 gnus-command-method))
452           (while (not (eobp))
453             (if (null (eval (read (current-buffer))))
454                 (progn (forward-line)
455                        (kill-line -1))
456               (write-file (gnus-agent-lib-file "flags"))
457               (error "Couldn't set flags from file %s"
458                      (gnus-agent-lib-file "flags"))))
459           (write-file (gnus-agent-lib-file "flags")))
460         (kill-buffer nil)))))
461
462 ;;;
463 ;;; Server mode commands
464 ;;;
465
466 (defun gnus-agent-add-server (server)
467   "Enroll SERVER in the agent program."
468   (interactive (list (gnus-server-server-name)))
469   (unless server
470     (error "No server on the current line"))
471   (let ((method (gnus-server-get-method nil (gnus-server-server-name))))
472     (when (member method gnus-agent-covered-methods)
473       (error "Server already in the agent program"))
474     (push method gnus-agent-covered-methods)
475     (gnus-agent-write-servers)
476     (message "Entered %s into the Agent" server)))
477
478 (defun gnus-agent-remove-server (server)
479   "Remove SERVER from the agent program."
480   (interactive (list (gnus-server-server-name)))
481   (unless server
482     (error "No server on the current line"))
483   (let ((method (gnus-server-get-method nil (gnus-server-server-name))))
484     (unless (member method gnus-agent-covered-methods)
485       (error "Server not in the agent program"))
486     (setq gnus-agent-covered-methods
487           (delete method gnus-agent-covered-methods))
488     (gnus-agent-write-servers)
489     (message "Removed %s from the agent" server)))
490
491 (defun gnus-agent-read-servers ()
492   "Read the alist of covered servers."
493   (setq gnus-agent-covered-methods
494         (gnus-agent-read-file
495          (nnheader-concat gnus-agent-directory "lib/servers"))))
496
497 (defun gnus-agent-write-servers ()
498   "Write the alist of covered servers."
499   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
500   (let ((coding-system-for-write nnheader-file-coding-system)
501         (output-coding-system nnheader-file-coding-system)
502         (file-name-coding-system nnmail-pathname-coding-system)
503         (pathname-coding-system nnmail-pathname-coding-system))
504     (with-temp-file (nnheader-concat gnus-agent-directory "lib/servers")
505       (prin1 gnus-agent-covered-methods (current-buffer)))))
506
507 ;;;
508 ;;; Summary commands
509 ;;;
510
511 (defun gnus-agent-mark-article (n &optional unmark)
512   "Mark the next N articles as downloadable.
513 If N is negative, mark backward instead.  If UNMARK is non-nil, remove
514 the mark instead.  The difference between N and the actual number of
515 articles marked is returned."
516   (interactive "p")
517   (let ((backward (< n 0))
518         (n (abs n)))
519     (while (and
520             (> n 0)
521             (progn
522               (gnus-summary-set-agent-mark
523                (gnus-summary-article-number) unmark)
524               (zerop (gnus-summary-next-subject (if backward -1 1) nil t))))
525       (setq n (1- n)))
526     (when (/= 0 n)
527       (gnus-message 7 "No more articles"))
528     (gnus-summary-recenter)
529     (gnus-summary-position-point)
530     n))
531
532 (defun gnus-agent-unmark-article (n)
533   "Remove the downloadable mark from the next N articles.
534 If N is negative, unmark backward instead.  The difference between N and
535 the actual number of articles unmarked is returned."
536   (interactive "p")
537   (gnus-agent-mark-article n t))
538
539 (defun gnus-agent-toggle-mark (n)
540   "Toggle the downloadable mark from the next N articles.
541 If N is negative, toggle backward instead.  The difference between N and
542 the actual number of articles toggled is returned."
543   (interactive "p")
544   (gnus-agent-mark-article n 'toggle))
545
546 (defun gnus-summary-set-agent-mark (article &optional unmark)
547   "Mark ARTICLE as downloadable."
548   (let ((unmark (if (and (not (null unmark)) (not (eq t unmark)))
549                     (memq article gnus-newsgroup-downloadable)
550                   unmark)))
551     (if unmark
552         (progn
553           (setq gnus-newsgroup-downloadable
554                 (delq article gnus-newsgroup-downloadable))
555           (push article gnus-newsgroup-undownloaded))
556       (setq gnus-newsgroup-undownloaded
557             (delq article gnus-newsgroup-undownloaded))
558       (push article gnus-newsgroup-downloadable))
559     (gnus-summary-update-mark
560      (if unmark gnus-undownloaded-mark gnus-downloadable-mark)
561      'unread)))
562
563 (defun gnus-agent-get-undownloaded-list ()
564   "Mark all unfetched articles as read."
565   (let ((gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name)))
566     (when (and (not gnus-plugged)
567                (gnus-agent-method-p gnus-command-method))
568       (gnus-agent-load-alist gnus-newsgroup-name)
569       ;; First mark all undownloaded articles as undownloaded.
570       (let ((articles (append gnus-newsgroup-unreads
571                               gnus-newsgroup-marked
572                               gnus-newsgroup-dormant))
573             article)
574         (while (setq article (pop articles))
575           (unless (or (cdr (assq article gnus-agent-article-alist))
576                       (memq article gnus-newsgroup-downloadable)
577                       (memq article gnus-newsgroup-cached))
578             (push article gnus-newsgroup-undownloaded))))
579       ;; Then mark downloaded downloadable as not-downloadable,
580       ;; if you get my drift.
581       (let ((articles gnus-newsgroup-downloadable)
582             article)
583         (while (setq article (pop articles))
584           (when (cdr (assq article gnus-agent-article-alist))
585             (setq gnus-newsgroup-downloadable
586                   (delq article gnus-newsgroup-downloadable))))))))
587
588 (defun gnus-agent-catchup ()
589   "Mark all undownloaded articles as read."
590   (interactive)
591   (save-excursion
592     (while gnus-newsgroup-undownloaded
593       (gnus-summary-mark-article
594        (pop gnus-newsgroup-undownloaded) gnus-catchup-mark)))
595   (gnus-summary-position-point))
596
597 ;;;
598 ;;; Internal functions
599 ;;;
600
601 (defun gnus-agent-save-active (method)
602   (gnus-agent-save-active-1 method 'gnus-active-to-gnus-format))
603
604 (defun gnus-agent-save-active-1 (method function)
605   (when (gnus-agent-method-p method)
606     (let* ((gnus-command-method method)
607            (new (gnus-make-hashtable (count-lines (point-min) (point-max))))
608            (file (gnus-agent-lib-file "active")))
609       (funcall function nil new)
610       (gnus-agent-write-active file new)
611       (erase-buffer)
612       (insert-file-contents-as-coding-system gnus-agent-file-coding-system
613                                              file))))
614
615 (defun gnus-agent-write-active (file new)
616   (let ((orig (gnus-make-hashtable (count-lines (point-min) (point-max))))
617         (file (gnus-agent-lib-file "active"))
618         elem osym)
619     (when (file-exists-p file)
620       (with-temp-buffer
621         (insert-file-contents-as-coding-system gnus-agent-file-coding-system
622                                                file)
623         (gnus-active-to-gnus-format nil orig))
624       (mapatoms
625        (lambda (sym)
626          (when (and sym (boundp sym))
627            (if (and (boundp (setq osym (intern (symbol-name sym) orig)))
628                     (setq elem (symbol-value osym)))
629                (setcdr elem (cdr (symbol-value sym)))
630              (set (intern (symbol-name sym) orig) (symbol-value sym)))))
631        new))
632     (gnus-make-directory (file-name-directory file))
633     ;; The hashtable contains real names of groups,  no more prefix
634     ;; removing, so set `full' to `t'.
635     (gnus-write-active-file-as-coding-system gnus-agent-file-coding-system
636                                              file orig t)))
637
638 (defun gnus-agent-save-groups (method)
639   (gnus-agent-save-active-1 method 'gnus-groups-to-gnus-format))
640
641 (defun gnus-agent-save-group-info (method group active)
642   (when (gnus-agent-method-p method)
643     (let* ((gnus-command-method method)
644            (coding-system-for-write nnheader-file-coding-system)
645            (output-coding-system nnheader-file-coding-system)
646            (file-name-coding-system nnmail-pathname-coding-system)
647            (pathname-coding-system nnmail-pathname-coding-system)
648            (file (gnus-agent-lib-file "active"))
649            oactive)
650       (gnus-make-directory (file-name-directory file))
651       (with-temp-file file
652         (when (file-exists-p file)
653           (nnheader-insert-file-contents file))
654         (goto-char (point-min))
655         (when (re-search-forward
656                (concat "^" (regexp-quote group) " ") nil t)
657           (save-excursion
658             (save-restriction
659               (narrow-to-region (match-beginning 0)
660                                 (progn
661                                   (forward-line 1)
662                                   (point)))
663               (setq oactive (car (nnmail-parse-active)))))
664           (gnus-delete-line))
665         (insert (format "%S %d %d y\n" (intern group)
666                         (cdr active)
667                         (or (car oactive) (car active))))
668         (goto-char (point-max))
669         (while (search-backward "\\." nil t)
670           (delete-char 1))))))
671
672 (defun gnus-agent-group-path (group)
673   "Translate GROUP into a path."
674   (if nnmail-use-long-file-names
675       (gnus-group-real-name group)
676     (nnheader-translate-file-chars
677      (nnheader-replace-chars-in-string
678       (nnheader-replace-duplicate-chars-in-string
679        (nnheader-replace-chars-in-string 
680         (gnus-group-real-name group)
681         ?/ ?_)
682        ?. ?_)
683       ?. ?/))))
684
685 \f
686
687 (defun gnus-agent-method-p (method)
688   "Say whether METHOD is covered by the agent."
689   (member method gnus-agent-covered-methods))
690
691 (defun gnus-agent-get-function (method)
692   (if (and (not gnus-plugged)
693            (gnus-agent-method-p method))
694       (progn
695         (require 'nnagent)
696         'nnagent)
697     (car method)))
698
699 ;;; History functions
700
701 (defun gnus-agent-history-buffer ()
702   (cdr (assoc (gnus-agent-method) gnus-agent-history-buffers)))
703
704 (defun gnus-agent-open-history ()
705   (save-excursion
706     (push (cons (gnus-agent-method)
707                 (set-buffer (gnus-get-buffer-create
708                              (format " *Gnus agent %s history*"
709                                      (gnus-agent-method)))))
710           gnus-agent-history-buffers)
711     (erase-buffer)
712     (insert "\n")
713     (let ((file (gnus-agent-lib-file "history")))
714       (when (file-exists-p file)
715         (nnheader-insert-file-contents file))
716       (set (make-local-variable 'gnus-agent-file-name) file))))
717
718 (defun gnus-agent-save-history ()
719   (save-excursion
720     (set-buffer gnus-agent-current-history)
721     (gnus-make-directory (file-name-directory gnus-agent-file-name))
722     (write-region-as-coding-system
723      gnus-agent-file-coding-system
724      (1+ (point-min)) (point-max) gnus-agent-file-name nil 'silent)))
725
726 (defun gnus-agent-close-history ()
727   (when (gnus-buffer-live-p gnus-agent-current-history)
728     (kill-buffer gnus-agent-current-history)
729     (setq gnus-agent-history-buffers
730           (delq (assoc (gnus-agent-method) gnus-agent-history-buffers)
731                 gnus-agent-history-buffers))))
732
733 (defun gnus-agent-enter-history (id group-arts date)
734   (save-excursion
735     (set-buffer gnus-agent-current-history)
736     (goto-char (point-max))
737     (let ((p (point)))
738       (insert id "\t" (number-to-string date) "\t")
739       (while group-arts
740         (insert (format "%S" (intern (caar group-arts)))
741                 " " (number-to-string (cdr (pop group-arts)))
742                 " "))
743       (insert "\n")
744       (while (search-backward "\\." p t)
745         (delete-char 1)))))
746
747 (defun gnus-agent-article-in-history-p (id)
748   (save-excursion
749     (set-buffer (gnus-agent-history-buffer))
750     (goto-char (point-min))
751     (search-forward (concat "\n" id "\t") nil t)))
752
753 (defun gnus-agent-history-path (id)
754   (save-excursion
755     (set-buffer (gnus-agent-history-buffer))
756     (goto-char (point-min))
757     (when (search-forward (concat "\n" id "\t") nil t)
758       (let ((method (gnus-agent-method)))
759         (let (paths group)
760           (while (not (numberp (setq group (read (current-buffer)))))
761             (push (concat method "/" group) paths))
762           (nreverse paths))))))
763
764 ;;;
765 ;;; Fetching
766 ;;;
767
768 (defun gnus-agent-fetch-articles (group articles)
769   "Fetch ARTICLES from GROUP and put them into the Agent."
770   (when articles
771     ;; Prune off articles that we have already fetched.
772     (while (and articles
773                 (cdr (assq (car articles) gnus-agent-article-alist)))
774       (pop articles))
775     (let ((arts articles))
776       (while (cdr arts)
777         (if (cdr (assq (cadr arts) gnus-agent-article-alist))
778             (setcdr arts (cddr arts))
779           (setq arts (cdr arts)))))
780     (when articles
781       (let ((dir (concat
782                   (gnus-agent-directory)
783                   (gnus-agent-group-path group) "/"))
784             (date (time-to-days (current-time)))
785             (case-fold-search t)
786             pos crosses id elem)
787         (gnus-make-directory dir)
788         (gnus-message 7 "Fetching articles for %s..." group)
789         ;; Fetch the articles from the backend.
790         (if (gnus-check-backend-function 'retrieve-articles group)
791             (setq pos (gnus-retrieve-articles articles group))
792           (with-temp-buffer
793             (let (article)
794               (while (setq article (pop articles))
795                 (when (or 
796                        (gnus-backlog-request-article group article 
797                                                      nntp-server-buffer)
798                        (gnus-request-article article group))
799                   (goto-char (point-max))
800                   (push (cons article (point)) pos)
801                   (insert-buffer-substring nntp-server-buffer)))
802               (copy-to-buffer nntp-server-buffer (point-min) (point-max))
803               (setq pos (nreverse pos)))))
804         ;; Then save these articles into the Agent.
805         (save-excursion
806           (set-buffer nntp-server-buffer)
807           (while pos
808             (narrow-to-region (cdar pos) (or (cdadr pos) (point-max)))
809             (goto-char (point-min))
810             (when (search-forward "\n\n" nil t)
811               (when (search-backward "\nXrefs: " nil t)
812                 ;; Handle crossposting.
813                 (skip-chars-forward "^ ")
814                 (skip-chars-forward " ")
815                 (setq crosses nil)
816                 (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) +")
817                   (push (cons (buffer-substring (match-beginning 1)
818                                                 (match-end 1))
819                               (buffer-substring (match-beginning 2)
820                                                 (match-end 2)))
821                         crosses)
822                   (goto-char (match-end 0)))
823                 (gnus-agent-crosspost crosses (caar pos))))
824             (goto-char (point-min))
825             (if (not (re-search-forward "^Message-ID: *<\\([^>\n]+\\)>" nil t))
826                 (setq id "No-Message-ID-in-article")
827               (setq id (buffer-substring (match-beginning 1) (match-end 1))))
828             (write-region-as-coding-system
829              gnus-agent-file-coding-system
830              (point-min) (point-max)
831              (concat dir (number-to-string (caar pos))) nil 'silent)
832             (when (setq elem (assq (caar pos) gnus-agent-article-alist))
833               (setcdr elem t))
834             (gnus-agent-enter-history
835              id (or crosses (list (cons group (caar pos)))) date)
836             (widen)
837             (pop pos)))
838         (gnus-agent-save-alist group)))))
839
840 (defun gnus-agent-crosspost (crosses article)
841   (let (gnus-agent-article-alist group alist beg end)
842     (save-excursion
843       (set-buffer gnus-agent-overview-buffer)
844       (when (nnheader-find-nov-line article)
845         (forward-word 1)
846         (setq beg (point))
847         (setq end (progn (forward-line 1) (point)))))
848     (while crosses
849       (setq group (caar crosses))
850       (unless (setq alist (assoc group gnus-agent-group-alist))
851         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
852               gnus-agent-group-alist))
853       (setcdr alist (cons (cons (cdar crosses) t) (cdr alist)))
854       (save-excursion
855         (set-buffer (gnus-get-buffer-create (format " *Gnus agent overview %s*"
856                                                     group)))
857         (when (= (point-max) (point-min))
858           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
859           (ignore-errors
860             (nnheader-insert-file-contents
861              (gnus-agent-article-name ".overview" group))))
862         (nnheader-find-nov-line (string-to-number (cdar crosses)))
863         (insert (string-to-number (cdar crosses)))
864         (insert-buffer-substring gnus-agent-overview-buffer beg end))
865       (pop crosses))))
866
867 (defun gnus-agent-flush-cache ()
868   (save-excursion
869     (while gnus-agent-buffer-alist
870       (set-buffer (cdar gnus-agent-buffer-alist))
871       (write-region-as-coding-system
872        gnus-agent-file-coding-system
873        (point-min) (point-max)
874        (gnus-agent-article-name ".overview"
875                                 (caar gnus-agent-buffer-alist))
876        nil 'silent)
877       (pop gnus-agent-buffer-alist))
878     (while gnus-agent-group-alist
879       (with-temp-file (caar gnus-agent-group-alist)
880         (princ (cdar gnus-agent-group-alist))
881         (insert "\n"))
882       (pop gnus-agent-group-alist))))
883
884 (defun gnus-agent-fetch-headers (group &optional force)
885   (let* ((articles (gnus-list-of-unread-articles group))
886          (len (length articles))
887          (gnus-decode-encoded-word-function 'identity)
888          (file (gnus-agent-article-name ".overview" group))
889          i)
890     ;; Check the number of articles is not too large.
891     (when (and (integerp gnus-agent-large-newsgroup)
892                (< 0 gnus-agent-large-newsgroup))
893       (and (< 0 (setq i (- len gnus-agent-large-newsgroup)))
894            (setq articles (nthcdr i articles))))
895     ;; add article with marks to list of article headers we want to fetch.
896     (dolist (arts (gnus-info-marks (gnus-get-info group)))
897       (setq articles (union (gnus-uncompress-sequence (cdr arts))
898                             articles)))
899     (setq articles (sort articles '<))
900     ;; Remove known articles.
901     (when (gnus-agent-load-alist group)
902       (setq articles (gnus-sorted-intersection
903                       articles
904                       (gnus-uncompress-range
905                        (cons (1+ (caar (last gnus-agent-article-alist)))
906                              (cdr (gnus-active group)))))))
907     ;; Fetch them.
908     (gnus-make-directory (nnheader-translate-file-chars
909                           (file-name-directory file) t))
910     (when articles
911       (gnus-message 7 "Fetching headers for %s..." group)
912       (save-excursion
913         (set-buffer nntp-server-buffer)
914         (unless (eq 'nov (gnus-retrieve-headers articles group))
915           (nnvirtual-convert-headers))
916         ;; Save these headers for later processing.
917         (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
918         (when (file-exists-p file)
919           (gnus-agent-braid-nov group articles file))
920         (write-region-as-coding-system
921          gnus-agent-file-coding-system
922          (point-min) (point-max) file nil 'silent)
923         (gnus-agent-save-alist group articles nil)
924         (gnus-agent-enter-history
925          "last-header-fetched-for-session"
926          (list (cons group (nth (- (length  articles) 1) articles)))
927          (time-to-days (current-time)))
928         articles))))
929
930 (defsubst gnus-agent-copy-nov-line (article)
931   (let (b e)
932     (set-buffer gnus-agent-overview-buffer)
933     (setq b (point))
934     (if (eq article (read (current-buffer)))
935         (setq e (progn (forward-line 1) (point)))
936       (progn
937         (beginning-of-line)
938         (setq e b)))
939     (set-buffer nntp-server-buffer)
940     (insert-buffer-substring gnus-agent-overview-buffer b e)))
941
942 (defun gnus-agent-braid-nov (group articles file)
943   (set-buffer gnus-agent-overview-buffer)
944   (goto-char (point-min))
945   (set-buffer nntp-server-buffer)
946   (erase-buffer)
947   (nnheader-insert-file-contents file)
948   (goto-char (point-max))
949   (if (or (= (point-min) (point-max))
950           (progn
951             (forward-line -1)
952             (< (read (current-buffer)) (car articles))))
953       ;; We have only headers that are after the older headers,
954       ;; so we just append them.
955       (progn
956         (goto-char (point-max))
957         (insert-buffer-substring gnus-agent-overview-buffer))
958     ;; We do it the hard way.
959     (nnheader-find-nov-line (car articles))
960     (gnus-agent-copy-nov-line (car articles))
961     (pop articles)
962     (while (and articles
963                 (not (eobp)))
964       (while (and (not (eobp))
965                   (< (read (current-buffer)) (car articles)))
966         (forward-line 1))
967       (beginning-of-line)
968       (unless (eobp)
969         (gnus-agent-copy-nov-line (car articles))
970         (setq articles (cdr articles))))
971     (when articles
972       (let (b e)
973         (set-buffer gnus-agent-overview-buffer)
974         (setq b (point)
975               e (point-max))
976         (set-buffer nntp-server-buffer)
977         (insert-buffer-substring gnus-agent-overview-buffer b e)))))
978
979 (defun gnus-agent-load-alist (group &optional dir)
980   "Load the article-state alist for GROUP."
981   (setq gnus-agent-article-alist
982         (gnus-agent-read-file
983          (if dir
984              (concat dir ".agentview")
985            (gnus-agent-article-name ".agentview" group)))))
986
987 (defun gnus-agent-save-alist (group &optional articles state dir)
988   "Save the article-state alist for GROUP."
989   (let ((file-name-coding-system nnmail-pathname-coding-system)
990         (pathname-coding-system nnmail-pathname-coding-system))
991     (with-temp-file (if dir
992                         (concat dir ".agentview")
993                       (gnus-agent-article-name ".agentview" group))
994       (princ (setq gnus-agent-article-alist
995                    (nconc gnus-agent-article-alist
996                           (mapcar (lambda (article) (cons article state))
997                                   articles)))
998              (current-buffer))
999       (insert "\n"))))
1000
1001 (defun gnus-agent-article-name (article group)
1002   (concat (gnus-agent-directory) (gnus-agent-group-path group) "/"
1003           (if (stringp article) article (string-to-number article))))
1004
1005 ;;;###autoload
1006 (defun gnus-agent-batch-fetch ()
1007   "Start Gnus and fetch session."
1008   (interactive)
1009   (gnus)
1010   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1011     (gnus-agent-fetch-session))
1012   (gnus-group-exit))
1013
1014 (defun gnus-agent-fetch-session ()
1015   "Fetch all articles and headers that are eligible for fetching."
1016   (interactive)
1017   (unless gnus-agent-covered-methods
1018     (error "No servers are covered by the Gnus agent"))
1019   (unless gnus-plugged
1020     (error "Can't fetch articles while Gnus is unplugged"))
1021   (let ((methods gnus-agent-covered-methods)
1022         groups group gnus-command-method)
1023     (save-excursion
1024       (while methods
1025         (condition-case err
1026             (progn
1027               (setq gnus-command-method (car methods))
1028               (when (or (gnus-server-opened gnus-command-method)
1029                         (gnus-open-server gnus-command-method))
1030                 (setq groups (gnus-groups-from-server (car methods)))
1031                 (gnus-agent-with-fetch
1032                   (while (setq group (pop groups))
1033                     (when (<= (gnus-group-level group) gnus-agent-handle-level)
1034                       (gnus-agent-fetch-group-1 group gnus-command-method))))))
1035           (error 
1036            (unless (funcall gnus-agent-confirmation-function
1037                             (format "Error (%s).  Continue? " err))
1038              (error "Cannot fetch articles into the Gnus agent."))))
1039         (pop methods))
1040       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
1041
1042 (defun gnus-agent-fetch-group-1 (group method)
1043   "Fetch GROUP."
1044   (let ((gnus-command-method method)
1045         (gnus-newsgroup-name group)
1046         gnus-newsgroup-dependencies gnus-newsgroup-headers
1047         gnus-newsgroup-scored gnus-headers gnus-score
1048         gnus-use-cache articles arts
1049         category predicate info marks score-param
1050         (gnus-summary-expunge-below gnus-summary-expunge-below)
1051         (gnus-summary-mark-below gnus-summary-mark-below)
1052         (gnus-orphan-score gnus-orphan-score)
1053         ;; Maybe some other gnus-summary local variables should also
1054         ;; be put here.
1055         )
1056     (unless (gnus-check-group group)
1057       (error "Can't open server for %s" group))
1058     ;; Fetch headers.
1059     (when (and (or (gnus-active group) (gnus-activate-group group))
1060                (setq articles (gnus-agent-fetch-headers group))
1061                (progn
1062                  ;; Parse them and see which articles we want to fetch.
1063                  (setq gnus-newsgroup-dependencies
1064                        (make-vector (length articles) 0))
1065                  ;; No need to call `gnus-get-newsgroup-headers-xover' with
1066                  ;; the entire .overview for group as we still have the just
1067                  ;; downloaded headers in `gnus-agent-overview-buffer'.
1068                  (let ((nntp-server-buffer gnus-agent-overview-buffer))
1069                    (setq gnus-newsgroup-headers
1070                          (gnus-get-newsgroup-headers-xover articles nil nil
1071                                                            group)))
1072                  ;; `gnus-agent-overview-buffer' may be killed for
1073                  ;; timeout reason.  If so, recreate it.
1074                  (gnus-agent-create-buffer)))
1075       (setq category (gnus-group-category group))
1076       (setq predicate
1077             (gnus-get-predicate
1078              (or (gnus-group-find-parameter group 'agent-predicate t)
1079                  (cadr category))))
1080       ;; Do we want to download everything, or nothing?
1081       (if (or (eq (caaddr predicate) 'gnus-agent-true)
1082               (eq (caaddr predicate) 'gnus-agent-false))
1083           ;; Yes.
1084           (setq arts (symbol-value
1085                       (cadr (assoc (caaddr predicate)
1086                                    '((gnus-agent-true articles)
1087                                      (gnus-agent-false nil))))))
1088         ;; No, we need to decide what we want.
1089         (setq score-param
1090               (let ((score-method
1091                      (or
1092                       (gnus-group-find-parameter group 'agent-score t)
1093                       (caddr category))))
1094                 (when score-method
1095                   (require 'gnus-score)
1096                   (if (eq score-method 'file)
1097                       (let ((entries
1098                              (gnus-score-load-files
1099                               (gnus-all-score-files group)))
1100                             list score-file)
1101                         (while (setq list (car entries))
1102                           (push (car list) score-file)
1103                           (setq list (cdr list))
1104                           (while list
1105                             (when (member (caar list)
1106                                           gnus-agent-scoreable-headers)
1107                               (push (car list) score-file))
1108                             (setq list (cdr list)))
1109                           (setq score-param
1110                                 (append score-param (list (nreverse score-file)))
1111                                 score-file nil entries (cdr entries)))
1112                         (list score-param))
1113                     (if (stringp (car score-method))
1114                         score-method
1115                       (list (list score-method)))))))
1116         (when score-param
1117           (gnus-score-headers score-param))
1118         (setq arts nil)
1119         (while (setq gnus-headers (pop gnus-newsgroup-headers))
1120           (setq gnus-score
1121                 (or (cdr (assq (mail-header-number gnus-headers)
1122                                gnus-newsgroup-scored))
1123                     gnus-summary-default-score))
1124           (when (funcall predicate)
1125             (push (mail-header-number gnus-headers)
1126                   arts))))
1127       ;; Fetch the articles.
1128       (when arts
1129         (gnus-agent-fetch-articles group arts)))
1130     ;; Perhaps we have some additional articles to fetch.
1131     (setq arts (assq 'download (gnus-info-marks
1132                                 (setq info (gnus-get-info group)))))
1133     (when (cdr arts)
1134       (gnus-agent-fetch-articles
1135        group (gnus-uncompress-range (cdr arts)))
1136       (setq marks (delq arts (gnus-info-marks info)))
1137       (gnus-info-set-marks info marks)
1138       (gnus-dribble-enter
1139        (concat "(gnus-group-set-info '"
1140                (gnus-prin1-to-string info)
1141                ")")))))
1142
1143 ;;;
1144 ;;; Agent Category Mode
1145 ;;;
1146
1147 (defvar gnus-category-mode-hook nil
1148   "Hook run in `gnus-category-mode' buffers.")
1149
1150 (defvar gnus-category-line-format "     %(%20c%): %g\n"
1151   "Format of category lines.")
1152
1153 (defvar gnus-category-mode-line-format "Gnus: %%b"
1154   "The format specification for the category mode line.")
1155
1156 (defvar gnus-agent-short-article 100
1157   "Articles that have fewer lines than this are short.")
1158
1159 (defvar gnus-agent-long-article 200
1160   "Articles that have more lines than this are long.")
1161
1162 (defvar gnus-agent-low-score 0
1163   "Articles that have a score lower than this have a low score.")
1164
1165 (defvar gnus-agent-high-score 0
1166   "Articles that have a score higher than this have a high score.")
1167
1168
1169 ;;; Internal variables.
1170
1171 (defvar gnus-category-buffer "*Agent Category*")
1172
1173 (defvar gnus-category-line-format-alist
1174   `((?c gnus-tmp-name ?s)
1175     (?g gnus-tmp-groups ?d)))
1176
1177 (defvar gnus-category-mode-line-format-alist
1178   `((?u user-defined ?s)))
1179
1180 (defvar gnus-category-line-format-spec nil)
1181 (defvar gnus-category-mode-line-format-spec nil)
1182
1183 (defvar gnus-category-mode-map nil)
1184 (put 'gnus-category-mode 'mode-class 'special)
1185
1186 (unless gnus-category-mode-map
1187   (setq gnus-category-mode-map (make-sparse-keymap))
1188   (suppress-keymap gnus-category-mode-map)
1189
1190   (gnus-define-keys gnus-category-mode-map
1191     "q" gnus-category-exit
1192     "k" gnus-category-kill
1193     "c" gnus-category-copy
1194     "a" gnus-category-add
1195     "p" gnus-category-edit-predicate
1196     "g" gnus-category-edit-groups
1197     "s" gnus-category-edit-score
1198     "l" gnus-category-list
1199
1200     "\C-c\C-i" gnus-info-find-node
1201     "\C-c\C-b" gnus-bug))
1202
1203 (defvar gnus-category-menu-hook nil
1204   "*Hook run after the creation of the menu.")
1205
1206 (defun gnus-category-make-menu-bar ()
1207   (gnus-turn-off-edit-menu 'category)
1208   (unless (boundp 'gnus-category-menu)
1209     (easy-menu-define
1210      gnus-category-menu gnus-category-mode-map ""
1211      '("Categories"
1212        ["Add" gnus-category-add t]
1213        ["Kill" gnus-category-kill t]
1214        ["Copy" gnus-category-copy t]
1215        ["Edit predicate" gnus-category-edit-predicate t]
1216        ["Edit score" gnus-category-edit-score t]
1217        ["Edit groups" gnus-category-edit-groups t]
1218        ["Exit" gnus-category-exit t]))
1219
1220     (gnus-run-hooks 'gnus-category-menu-hook)))
1221
1222 (defun gnus-category-mode ()
1223   "Major mode for listing and editing agent categories.
1224
1225 All normal editing commands are switched off.
1226 \\<gnus-category-mode-map>
1227 For more in-depth information on this mode, read the manual
1228 (`\\[gnus-info-find-node]').
1229
1230 The following commands are available:
1231
1232 \\{gnus-category-mode-map}"
1233   (interactive)
1234   (when (gnus-visual-p 'category-menu 'menu)
1235     (gnus-category-make-menu-bar))
1236   (kill-all-local-variables)
1237   (gnus-simplify-mode-line)
1238   (setq major-mode 'gnus-category-mode)
1239   (setq mode-name "Category")
1240   (gnus-set-default-directory)
1241   (setq mode-line-process nil)
1242   (use-local-map gnus-category-mode-map)
1243   (buffer-disable-undo)
1244   (setq truncate-lines t)
1245   (setq buffer-read-only t)
1246   (gnus-run-hooks 'gnus-category-mode-hook))
1247
1248 (defalias 'gnus-category-position-point 'gnus-goto-colon)
1249
1250 (defun gnus-category-insert-line (category)
1251   (let* ((gnus-tmp-name (car category))
1252          (gnus-tmp-groups (length (cadddr category))))
1253     (beginning-of-line)
1254     (gnus-add-text-properties
1255      (point)
1256      (prog1 (1+ (point))
1257        ;; Insert the text.
1258        (eval gnus-category-line-format-spec))
1259      (list 'gnus-category gnus-tmp-name))))
1260
1261 (defun gnus-enter-category-buffer ()
1262   "Go to the Category buffer."
1263   (interactive)
1264   (gnus-category-setup-buffer)
1265   (gnus-configure-windows 'category)
1266   (gnus-category-prepare))
1267
1268 (defun gnus-category-setup-buffer ()
1269   (unless (get-buffer gnus-category-buffer)
1270     (save-excursion
1271       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
1272       (gnus-category-mode))))
1273
1274 (defun gnus-category-prepare ()
1275   (gnus-set-format 'category-mode)
1276   (gnus-set-format 'category t)
1277   (let ((alist gnus-category-alist)
1278         (buffer-read-only nil))
1279     (erase-buffer)
1280     (while alist
1281       (gnus-category-insert-line (pop alist)))
1282     (goto-char (point-min))
1283     (gnus-category-position-point)))
1284
1285 (defun gnus-category-name ()
1286   (or (get-text-property (gnus-point-at-bol) 'gnus-category)
1287       (error "No category on the current line")))
1288
1289 (defun gnus-category-read ()
1290   "Read the category alist."
1291   (setq gnus-category-alist
1292         (or (gnus-agent-read-file
1293              (nnheader-concat gnus-agent-directory "lib/categories"))
1294             (list (list 'default 'short nil nil)))))
1295
1296 (defun gnus-category-write ()
1297   "Write the category alist."
1298   (setq gnus-category-predicate-cache nil
1299         gnus-category-group-cache nil)
1300   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
1301   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
1302     (prin1 gnus-category-alist (current-buffer))))
1303
1304 (defun gnus-category-edit-predicate (category)
1305   "Edit the predicate for CATEGORY."
1306   (interactive (list (gnus-category-name)))
1307   (let ((info (assq category gnus-category-alist)))
1308     (gnus-edit-form
1309      (cadr info) (format "Editing the predicate for category %s" category)
1310      `(lambda (predicate)
1311         (setcar (cdr (assq ',category gnus-category-alist)) predicate)
1312         (gnus-category-write)
1313         (gnus-category-list)))))
1314
1315 (defun gnus-category-edit-score (category)
1316   "Edit the score expression for CATEGORY."
1317   (interactive (list (gnus-category-name)))
1318   (let ((info (assq category gnus-category-alist)))
1319     (gnus-edit-form
1320      (caddr info)
1321      (format "Editing the score expression for category %s" category)
1322      `(lambda (groups)
1323         (setcar (nthcdr 2 (assq ',category gnus-category-alist)) groups)
1324         (gnus-category-write)
1325         (gnus-category-list)))))
1326
1327 (defun gnus-category-edit-groups (category)
1328   "Edit the group list for CATEGORY."
1329   (interactive (list (gnus-category-name)))
1330   (let ((info (assq category gnus-category-alist)))
1331     (gnus-edit-form
1332      (cadddr info) (format "Editing the group list for category %s" category)
1333      `(lambda (groups)
1334         (setcar (nthcdr 3 (assq ',category gnus-category-alist)) groups)
1335         (gnus-category-write)
1336         (gnus-category-list)))))
1337
1338 (defun gnus-category-kill (category)
1339   "Kill the current category."
1340   (interactive (list (gnus-category-name)))
1341   (let ((info (assq category gnus-category-alist))
1342         (buffer-read-only nil))
1343     (gnus-delete-line)
1344     (setq gnus-category-alist (delq info gnus-category-alist))
1345     (gnus-category-write)))
1346
1347 (defun gnus-category-copy (category to)
1348   "Copy the current category."
1349   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
1350   (let ((info (assq category gnus-category-alist)))
1351     (push (list to (gnus-copy-sequence (cadr info))
1352                 (gnus-copy-sequence (caddr info)) nil)
1353           gnus-category-alist)
1354     (gnus-category-write)
1355     (gnus-category-list)))
1356
1357 (defun gnus-category-add (category)
1358   "Create a new category."
1359   (interactive "SCategory name: ")
1360   (when (assq category gnus-category-alist)
1361     (error "Category %s already exists" category))
1362   (push (list category 'false nil nil)
1363         gnus-category-alist)
1364   (gnus-category-write)
1365   (gnus-category-list))
1366
1367 (defun gnus-category-list ()
1368   "List all categories."
1369   (interactive)
1370   (gnus-category-prepare))
1371
1372 (defun gnus-category-exit ()
1373   "Return to the group buffer."
1374   (interactive)
1375   (kill-buffer (current-buffer))
1376   (gnus-configure-windows 'group t))
1377
1378 ;; To avoid having 8-bit characters in the source file.
1379 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
1380
1381 (defvar gnus-category-predicate-alist
1382   '((spam . gnus-agent-spam-p)
1383     (short . gnus-agent-short-p)
1384     (long . gnus-agent-long-p)
1385     (low . gnus-agent-low-scored-p)
1386     (high . gnus-agent-high-scored-p)
1387     (true . gnus-agent-true)
1388     (false . gnus-agent-false))
1389   "Mapping from short score predicate symbols to predicate functions.")
1390
1391 (defun gnus-agent-spam-p ()
1392   "Say whether an article is spam or not."
1393   (unless gnus-agent-spam-hashtb
1394     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
1395   (if (not (equal (mail-header-references gnus-headers) ""))
1396       nil
1397     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
1398       (prog1
1399           (gnus-gethash string gnus-agent-spam-hashtb)
1400         (gnus-sethash string t gnus-agent-spam-hashtb)))))
1401
1402 (defun gnus-agent-short-p ()
1403   "Say whether an article is short or not."
1404   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
1405
1406 (defun gnus-agent-long-p ()
1407   "Say whether an article is long or not."
1408   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
1409
1410 (defun gnus-agent-low-scored-p ()
1411   "Say whether an article has a low score or not."
1412   (< gnus-score gnus-agent-low-score))
1413
1414 (defun gnus-agent-high-scored-p ()
1415   "Say whether an article has a high score or not."
1416   (> gnus-score gnus-agent-high-score))
1417
1418 (defun gnus-category-make-function (cat)
1419   "Make a function from category CAT."
1420   `(lambda () ,(gnus-category-make-function-1 cat)))
1421
1422 (defun gnus-agent-true ()
1423   "Return t."
1424   t)
1425
1426 (defun gnus-agent-false ()
1427   "Return nil."
1428   nil)
1429
1430 (defun gnus-category-make-function-1 (cat)
1431   "Make a function from category CAT."
1432   (cond
1433    ;; Functions are just returned as is.
1434    ((or (symbolp cat)
1435         (gnus-functionp cat))
1436     `(,(or (cdr (assq cat gnus-category-predicate-alist))
1437            cat)))
1438    ;; More complex category.
1439    ((consp cat)
1440     `(,(cond
1441         ((memq (car cat) '(& and))
1442          'and)
1443         ((memq (car cat) '(| or))
1444          'or)
1445         ((memq (car cat) gnus-category-not)
1446          'not))
1447       ,@(mapcar 'gnus-category-make-function-1 (cdr cat))))
1448    (t
1449     (error "Unknown category type: %s" cat))))
1450
1451 (defun gnus-get-predicate (predicate)
1452   "Return the predicate for CATEGORY."
1453   (or (cdr (assoc predicate gnus-category-predicate-cache))
1454       (cdar (push (cons predicate
1455                         (gnus-category-make-function predicate))
1456                   gnus-category-predicate-cache))))
1457
1458 (defun gnus-group-category (group)
1459   "Return the category GROUP belongs to."
1460   (unless gnus-category-group-cache
1461     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
1462     (let ((cs gnus-category-alist)
1463           groups cat)
1464       (while (setq cat (pop cs))
1465         (setq groups (cadddr cat))
1466         (while groups
1467           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
1468   (or (gnus-gethash group gnus-category-group-cache)
1469       (assq 'default gnus-category-alist)))
1470
1471 (defun gnus-agent-expire ()
1472   "Expire all old articles."
1473   (interactive)
1474   (let ((methods gnus-agent-covered-methods)
1475         (day (- (time-to-days (current-time)) gnus-agent-expire-days))
1476         gnus-command-method sym group articles
1477         history overview file histories elem art nov-file low info
1478         unreads marked article orig lowest highest)
1479     (save-excursion
1480       (setq overview (gnus-get-buffer-create " *expire overview*"))
1481       (while (setq gnus-command-method (pop methods))
1482         (when (file-exists-p (gnus-agent-lib-file "active"))
1483           (with-temp-buffer
1484             (insert-file-contents-as-coding-system
1485              gnus-agent-file-coding-system (gnus-agent-lib-file "active"))
1486             (gnus-active-to-gnus-format
1487              gnus-command-method
1488              (setq orig (gnus-make-hashtable
1489                          (count-lines (point-min) (point-max))))))
1490           (let ((expiry-hashtb (gnus-make-hashtable 1023)))
1491             (gnus-agent-open-history)
1492             (set-buffer
1493              (setq gnus-agent-current-history
1494                    (setq history (gnus-agent-history-buffer))))
1495             (goto-char (point-min))
1496             (when (> (buffer-size) 1)
1497               (goto-char (point-min))
1498               (while (not (eobp))
1499                 (skip-chars-forward "^\t")
1500                 (if (> (read (current-buffer)) day)
1501                     ;; New article; we don't expire it.
1502                     (forward-line 1)
1503                   ;; Old article.  Schedule it for possible nuking.
1504                   (while (not (eolp))
1505                     (setq sym (let ((obarray expiry-hashtb) s)
1506                                 (setq s (read (current-buffer)))
1507                                 (if (stringp s) (intern s) s)))
1508                     (if (boundp sym)
1509                         (set sym (cons (cons (read (current-buffer)) (point))
1510                                        (symbol-value sym)))
1511                       (set sym (list (cons (read (current-buffer)) (point)))))
1512                     (skip-chars-forward " "))
1513                   (forward-line 1)))
1514               ;; We now have all articles that can possibly be expired.
1515               (mapatoms
1516                (lambda (sym)
1517                  (setq group (symbol-name sym)
1518                        articles (sort (symbol-value sym) 'car-less-than-car)
1519                        low (car (gnus-active group))
1520                        info (gnus-get-info group)
1521                        unreads (ignore-errors
1522                                  (gnus-list-of-unread-articles group))
1523                        marked (nconc
1524                                (gnus-uncompress-range
1525                                 (cdr (assq 'tick (gnus-info-marks info))))
1526                                (gnus-uncompress-range
1527                                 (cdr (assq 'dormant (gnus-info-marks info))))
1528                                (gnus-uncompress-range
1529                                 (cdr (assq 'save (gnus-info-marks info))))
1530                                (gnus-uncompress-range
1531                                 (cdr (assq 'reply (gnus-info-marks info)))))
1532                        nov-file (gnus-agent-article-name ".overview" group)
1533                        lowest nil
1534                        highest nil)
1535                  (gnus-agent-load-alist group)
1536                  (gnus-message 5 "Expiring articles in %s" group)
1537                  (set-buffer overview)
1538                  (erase-buffer)
1539                  (when (file-exists-p nov-file)
1540                    (nnheader-insert-file-contents nov-file))
1541                  (goto-char (point-min))
1542                  (setq article 0)
1543                  (while (setq elem (pop articles))
1544                    (setq article (car elem))
1545                    (when (or (null low)
1546                              (< article low)
1547                              gnus-agent-expire-all
1548                              (and (not (memq article unreads))
1549                                   (not (memq article marked))))
1550                      ;; Find and nuke the NOV line.
1551                      (while (and (not (eobp))
1552                                  (or (not (numberp
1553                                            (setq art (read (current-buffer)))))
1554                                      (< art article)))
1555                        (if (and (numberp art)
1556                                 (file-exists-p
1557                                  (gnus-agent-article-name
1558                                   (number-to-string art) group)))
1559                            (progn
1560                              (unless lowest
1561                                (setq lowest art))
1562                              (setq highest art)
1563                              (forward-line 1))
1564                          ;; Remove old NOV lines that have no articles.
1565                          (gnus-delete-line)))
1566                      (if (or (eobp)
1567                              (/= art article))
1568                          (beginning-of-line)
1569                        (gnus-delete-line))
1570                      ;; Nuke the article.
1571                      (when (file-exists-p
1572                             (setq file (gnus-agent-article-name
1573                                         (number-to-string article)
1574                                         group)))
1575                        (delete-file file))
1576                      ;; Schedule the history line for nuking.
1577                      (push (cdr elem) histories)))
1578                  (gnus-make-directory (file-name-directory nov-file))
1579                  (write-region-as-coding-system
1580                   gnus-agent-file-coding-system
1581                   (point-min) (point-max) nov-file nil 'silent)
1582                  ;; Delete the unwanted entries in the alist.
1583                  (setq gnus-agent-article-alist
1584                        (sort gnus-agent-article-alist 'car-less-than-car))
1585                  (let* ((alist gnus-agent-article-alist)
1586                         (prev (cons nil alist))
1587                         (first prev)
1588                         expired)
1589                    (while (and alist
1590                                (<= (caar alist) article))
1591                      (if (or (not (cdar alist))
1592                              (not (file-exists-p
1593                                    (gnus-agent-article-name
1594                                     (number-to-string
1595                                      (caar alist))
1596                                     group))))
1597                          (progn
1598                            (push (caar alist) expired)
1599                            (setcdr prev (setq alist (cdr alist))))
1600                        (setq prev alist
1601                              alist (cdr alist))))
1602                    (setq gnus-agent-article-alist (cdr first))
1603                    (gnus-agent-save-alist group)
1604                    ;; Mark all articles up to the first article
1605                    ;; in `gnus-article-alist' as read.
1606                    (when (and info (caar gnus-agent-article-alist))
1607                      (setcar (nthcdr 2 info)
1608                              (gnus-range-add
1609                               (nth 2 info)
1610                               (cons 1 (- (caar gnus-agent-article-alist) 1)))))
1611                    ;; Maybe everything has been expired from `gnus-article-alist'
1612                    ;; and so the above marking as read could not be conducted,
1613                    ;; or there are expired article within the range of the alist.
1614                    (when (and info
1615                               expired
1616                               (or (not (caar gnus-agent-article-alist))
1617                                   (> (car expired)
1618                                      (caar gnus-agent-article-alist))))
1619                      (setcar (nthcdr 2 info)
1620                              (gnus-add-to-range
1621                               (nth 2 info)
1622                               (nreverse expired))))
1623                    (gnus-dribble-enter
1624                     (concat "(gnus-group-set-info '"
1625                             (gnus-prin1-to-string info)
1626                             ")")))
1627                  (when lowest
1628                    (if (gnus-gethash group orig)
1629                        (setcar (gnus-gethash group orig) lowest)
1630                      (gnus-sethash group (cons lowest highest) orig))))
1631                expiry-hashtb)
1632               (set-buffer history)
1633               (setq histories (nreverse (sort histories '<)))
1634               (while histories
1635                 (goto-char (pop histories))
1636                 (gnus-delete-line))
1637               (gnus-agent-save-history)
1638               (gnus-agent-close-history)
1639               (gnus-write-active-file-as-coding-system
1640                gnus-agent-file-coding-system
1641                (gnus-agent-lib-file "active") orig))
1642             (gnus-message 4 "Expiry...done")))))))
1643
1644 ;;;###autoload
1645 (defun gnus-agent-batch ()
1646   (interactive)
1647   (let ((init-file-user "")
1648         (gnus-always-read-dribble-file t))
1649     (gnus))
1650   (gnus-group-send-drafts)
1651   (gnus-agent-fetch-session))
1652
1653 ;;;
1654 ;;; Advice
1655 ;;;
1656
1657 (defadvice gnus-group-get-new-news (after gnus-agent-advice
1658                                           activate preactivate)
1659   "Update modeline."
1660   (unless (interactive-p)
1661     (gnus-agent-toggle-plugged gnus-plugged)))
1662
1663 (provide 'gnus-agent)
1664
1665 ;;; gnus-agent.el ends here