New branch `t-gnus-6_15'
[elisp/gnus.git-] / lisp / nnfolder.el
1 ;;; nnfolder.el --- mail folder access for Gnus
2 ;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: ShengHuo Zhu <zsh@cs.rochester.edu> (adding NOV)
6 ;;      Scott Byer <byer@mv.us.adobe.com>
7 ;;      Lars Magne Ingebrigtsen <larsi@gnus.org>
8 ;;      Masanobu UMEDA <umerin@flab.flab.fujitsu.junet>
9 ;; Keywords: mail
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
25 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
27
28 ;;; Commentary:
29
30 ;;; Code:
31
32 (eval-when-compile (require 'cl))
33 (eval-when-compile (require 'gnus-clfns))
34
35 (require 'nnheader)
36 (require 'message)
37 (require 'nnmail)
38 (require 'nnoo)
39 (require 'gnus-util)
40 (require 'gnus-range)
41
42 (eval-and-compile
43   (autoload 'gnus-intersection "gnus-range"))
44
45 (nnoo-declare nnfolder)
46
47 (defvoo nnfolder-directory (expand-file-name message-directory)
48   "The name of the nnfolder directory.")
49
50 (defvoo nnfolder-nov-directory nil
51   "The name of the nnfolder NOV directory.
52 If nil, `nnfolder-directory' is used.")
53
54 (defvoo nnfolder-active-file
55     (nnheader-concat nnfolder-directory "active")
56   "The name of the active file.")
57
58 ;; I renamed this variable to something more in keeping with the general GNU
59 ;; style. -SLB
60
61 (defvoo nnfolder-ignore-active-file nil
62   "If non-nil, the active file is ignored.
63 This causes nnfolder to do some extra work in order to determine the
64 true active ranges of an mbox file.  Note that the active file is
65 still saved, but its values are not used.  This costs some extra time
66 when scanning an mbox when opening it.")
67
68 (defvoo nnfolder-distrust-mbox nil
69   "If non-nil, the folder will be distrusted.
70 This means that nnfolder will not trust the user with respect to
71 inserting unaccounted for mail in the middle of an mbox file.  This
72 can greatly slow down scans, which now must scan the entire file for
73 unmarked messages.  When nil, scans occur forward from the last marked
74 message, a huge time saver for large mailboxes.")
75
76 (defvoo nnfolder-newsgroups-file
77     (concat (file-name-as-directory nnfolder-directory) "newsgroups")
78   "Mail newsgroups description file.")
79
80 (defvoo nnfolder-get-new-mail t
81   "If non-nil, nnfolder will check the incoming mail file and split the mail.")
82
83 (defvoo nnfolder-prepare-save-mail-hook nil
84   "Hook run narrowed to an article before saving.")
85
86 (defvoo nnfolder-save-buffer-hook nil
87   "Hook run before saving the nnfolder mbox buffer.")
88
89 (defvoo nnfolder-inhibit-expiry nil
90   "If non-nil, inhibit expiry.")
91
92 \f
93
94 (defconst nnfolder-version "nnfolder 2.0"
95   "nnfolder version.")
96
97 (defconst nnfolder-article-marker "X-Gnus-Article-Number: "
98   "String used to demarcate what the article number for a message is.")
99
100 (defvoo nnfolder-current-group nil)
101 (defvoo nnfolder-current-buffer nil)
102 (defvoo nnfolder-status-string "")
103 (defvoo nnfolder-group-alist nil)
104 (defvoo nnfolder-buffer-alist nil)
105 (defvoo nnfolder-scantime-alist nil)
106 (defvoo nnfolder-active-timestamp nil)
107 (defvoo nnfolder-active-file-coding-system nnheader-text-coding-system)
108 (defvoo nnfolder-active-file-coding-system-for-write 
109     nnmail-active-file-coding-system)
110 (defvoo nnfolder-file-coding-system nnheader-text-coding-system)
111 (defvoo nnfolder-file-coding-system-for-write nnheader-file-coding-system
112   "Coding system for save nnfolder file.
113 If NIL, NNFOLDER-FILE-CODING-SYSTEM is used.")
114
115 (defvoo nnfolder-nov-is-evil nil
116   "If non-nil, Gnus will never generate and use nov databases for mail groups.
117 Using nov databases will speed up header fetching considerably.
118 This variable shouldn't be flipped much.  If you have, for some reason,
119 set this to t, and want to set it to nil again, you should always run
120 the `nnfolder-generate-active-file' command.  The function will go
121 through all nnfolder directories and generate nov databases for them
122 all.  This may very well take some time.")
123
124 (defvoo nnfolder-nov-file-suffix ".nov")
125
126 (defvoo nnfolder-nov-buffer-alist nil)
127
128 (defvar nnfolder-nov-buffer-file-name nil)
129
130 \f
131
132 ;;; Interface functions
133
134 (nnoo-define-basics nnfolder)
135
136 (deffoo nnfolder-retrieve-headers (articles &optional group server fetch-old)
137   (save-excursion
138     (set-buffer nntp-server-buffer)
139     (erase-buffer)
140     (let (article start stop)
141       (nnfolder-possibly-change-group group server)
142       (when nnfolder-current-buffer
143         (set-buffer nnfolder-current-buffer)
144         (goto-char (point-min))
145         (if (stringp (car articles))
146             'headers
147           (if (nnfolder-retrieve-headers-with-nov articles fetch-old)
148               'nov
149             (setq articles (gnus-sorted-intersection 
150                             ;; Is ARTICLES sorted?
151                             (sort articles '<)
152                             (nnfolder-existing-articles)))
153             (while (setq article (pop articles))
154               (set-buffer nnfolder-current-buffer)
155               (when (nnfolder-goto-article article)
156                 (setq start (point))
157                 (setq stop (if (search-forward "\n\n" nil t)
158                                (1- (point))
159                              (point-max)))
160                 (set-buffer nntp-server-buffer)
161                 (insert (format "221 %d Article retrieved.\n" article))
162                 (insert-buffer-substring nnfolder-current-buffer start stop)
163                 (goto-char (point-max))
164                 (insert ".\n")))
165             (set-buffer nntp-server-buffer)
166             (nnheader-fold-continuation-lines)
167             'headers))))))
168
169 (deffoo nnfolder-open-server (server &optional defs)
170   (nnoo-change-server 'nnfolder server defs)
171   (nnmail-activate 'nnfolder t)
172   (gnus-make-directory nnfolder-directory)
173   (unless (or gnus-nov-is-evil nnfolder-nov-is-evil)
174     (and nnfolder-nov-directory
175          (gnus-make-directory nnfolder-nov-directory)))
176   (cond
177    ((not (file-exists-p nnfolder-directory))
178     (nnfolder-close-server)
179     (nnheader-report 'nnfolder "Couldn't create directory: %s"
180                      nnfolder-directory))
181    ((not (file-directory-p (file-truename nnfolder-directory)))
182     (nnfolder-close-server)
183     (nnheader-report 'nnfolder "Not a directory: %s" nnfolder-directory))
184    (t
185     (nnmail-activate 'nnfolder)
186     (nnheader-report 'nnfolder "Opened server %s using directory %s"
187                      server nnfolder-directory)
188     t)))
189
190 (deffoo nnfolder-request-close ()
191   (let ((alist nnfolder-buffer-alist))
192     (while alist
193       (nnfolder-close-group (caar alist) nil t)
194       (setq alist (cdr alist))))
195   (nnoo-close-server 'nnfolder)
196   (setq nnfolder-buffer-alist nil
197         nnfolder-group-alist nil))
198
199 (deffoo nnfolder-request-article (article &optional group server buffer)
200   (nnfolder-possibly-change-group group server)
201   (save-excursion
202     (set-buffer nnfolder-current-buffer)
203     (goto-char (point-min))
204     (when (nnfolder-goto-article article)
205       (let (start stop)
206         (setq start (point))
207         (forward-line 1)
208         (unless (and (nnmail-search-unix-mail-delim)
209                      (forward-line -1))
210           (goto-char (point-max)))
211         (setq stop (point))
212         (let ((nntp-server-buffer (or buffer nntp-server-buffer)))
213           (set-buffer nntp-server-buffer)
214           (erase-buffer)
215           (insert-buffer-substring nnfolder-current-buffer start stop)
216           (goto-char (point-min))
217           (while (looking-at "From ")
218             (delete-char 5)
219             (insert "X-From-Line: ")
220             (forward-line 1))
221           (if (numberp article)
222               (cons nnfolder-current-group article)
223             (goto-char (point-min))
224             (cons nnfolder-current-group
225                   (if (search-forward (concat "\n" nnfolder-article-marker) 
226                                       nil t)
227                       (string-to-int
228                        (buffer-substring
229                         (point) (progn (end-of-line) (point))))
230                     -1))))))))
231
232 (deffoo nnfolder-request-group (group &optional server dont-check)
233   (nnfolder-possibly-change-group group server t)
234   (save-excursion
235     (if (not (assoc group nnfolder-group-alist))
236         (nnheader-report 'nnfolder "No such group: %s" group)
237       (if dont-check
238           (progn
239             (nnheader-report 'nnfolder "Selected group %s" group)
240             t)
241         (let* ((active (assoc group nnfolder-group-alist))
242                (group (car active))
243                (range (cadr active)))
244           (cond
245            ((null active)
246             (nnheader-report 'nnfolder "No such group: %s" group))
247            ((null nnfolder-current-group)
248             (nnheader-report 'nnfolder "Empty group: %s" group))
249            (t
250             (nnheader-report 'nnfolder "Selected group %s" group)
251             (nnheader-insert "211 %d %d %d %s\n"
252                              (1+ (- (cdr range) (car range)))
253                              (car range) (cdr range) group))))))))
254
255 (deffoo nnfolder-request-scan (&optional group server)
256   (nnfolder-possibly-change-group nil server)
257   (when nnfolder-get-new-mail
258     (nnfolder-possibly-change-group group server)
259     (nnmail-get-new-mail
260      'nnfolder
261      (lambda ()
262        (let ((bufs nnfolder-buffer-alist))
263          (save-excursion
264            (while bufs
265              (if (not (gnus-buffer-live-p (nth 1 (car bufs))))
266                  (setq nnfolder-buffer-alist
267                        (delq (car bufs) nnfolder-buffer-alist))
268                (set-buffer (nth 1 (car bufs)))
269                (nnfolder-save-buffer)
270                (kill-buffer (current-buffer)))
271              (setq bufs (cdr bufs))))))
272      nnfolder-directory
273      group)))
274
275 ;; Don't close the buffer if we're not shutting down the server.  This way,
276 ;; we can keep the buffer in the group buffer cache, and not have to grovel
277 ;; over the buffer again unless we add new mail to it or modify it in some
278 ;; way.
279
280 (deffoo nnfolder-close-group (group &optional server force)
281   ;; Make sure we _had_ the group open.
282   (when (or (assoc group nnfolder-buffer-alist)
283             (equal group nnfolder-current-group))
284     (let ((inf (assoc group nnfolder-buffer-alist)))
285       (when inf
286         (when (and nnfolder-current-group
287                    nnfolder-current-buffer)
288           (push (list nnfolder-current-group nnfolder-current-buffer)
289                 nnfolder-buffer-alist))
290         (setq nnfolder-buffer-alist
291               (delq inf nnfolder-buffer-alist))
292         (setq nnfolder-current-buffer (cadr inf)
293               nnfolder-current-group (car inf))))
294     (when (and nnfolder-current-buffer
295                (buffer-name nnfolder-current-buffer))
296       (save-excursion
297         (set-buffer nnfolder-current-buffer)
298         ;; If the buffer was modified, write the file out now.
299         (nnfolder-save-buffer)
300         ;; If we're shutting the server down, we need to kill the
301         ;; buffer and remove it from the open buffer list.  Or, of
302         ;; course, if we're trying to minimize our space impact.
303         (kill-buffer (current-buffer))
304         (setq nnfolder-buffer-alist (delq (assoc group nnfolder-buffer-alist)
305                                           nnfolder-buffer-alist)))))
306   (setq nnfolder-current-group nil
307         nnfolder-current-buffer nil)
308   t)
309
310 (deffoo nnfolder-request-create-group (group &optional server args)
311   (nnfolder-possibly-change-group nil server)
312   (nnmail-activate 'nnfolder)
313   (when group
314     (unless (assoc group nnfolder-group-alist)
315       (push (list group (cons 1 0)) nnfolder-group-alist)
316       (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
317       (nnfolder-read-folder group)))
318   t)
319
320 (deffoo nnfolder-request-list (&optional server)
321   (nnfolder-possibly-change-group nil server)
322   (save-excursion
323     (let ((nnmail-file-coding-system nnfolder-active-file-coding-system))
324       (nnmail-find-file nnfolder-active-file)
325       (setq nnfolder-group-alist (nnmail-get-active)))
326     t))
327
328 (deffoo nnfolder-request-newgroups (date &optional server)
329   (nnfolder-possibly-change-group nil server)
330   (nnfolder-request-list server))
331
332 (deffoo nnfolder-request-list-newsgroups (&optional server)
333   (nnfolder-possibly-change-group nil server)
334   (save-excursion
335     (let ((nnmail-file-coding-system nnfolder-file-coding-system))
336       (nnmail-find-file nnfolder-newsgroups-file))))
337
338 ;; Return a list consisting of all article numbers existing in the
339 ;; current folder.
340
341 (defun nnfolder-existing-articles ()
342   (save-excursion
343     (when nnfolder-current-buffer
344       (set-buffer nnfolder-current-buffer)
345       (goto-char (point-min))
346       (let ((marker (concat "\n" nnfolder-article-marker))
347             (number "[0-9]+")
348             numbers)
349         (while (and (search-forward marker nil t)
350                     (re-search-forward number nil t))
351           (let ((newnum (string-to-number (match-string 0))))
352             (if (nnmail-within-headers-p)
353                 (push newnum numbers))))
354         ;; The article numbers are increasing, so this result is sorted.
355         (nreverse numbers)))))
356
357 (deffoo nnfolder-request-expire-articles
358     (articles newsgroup &optional server force)
359   (nnfolder-possibly-change-group newsgroup server)
360   (let* ((is-old t)
361          ;; The articles we have deleted so far.
362          (deleted-articles nil)
363          ;; The articles that really exist and will
364          ;; be expired if they are old enough.
365          (maybe-expirable
366           (gnus-sorted-intersection articles (nnfolder-existing-articles))))
367     (nnmail-activate 'nnfolder)
368
369     (save-excursion
370       (set-buffer nnfolder-current-buffer)
371       ;; Since messages are sorted in arrival order and expired in the
372       ;; same order, we can stop as soon as we find a message that is
373       ;; too old.
374       (while (and maybe-expirable is-old)
375         (goto-char (point-min))
376         (when (and (nnfolder-goto-article (car maybe-expirable))
377                    (search-forward (concat "\n" nnfolder-article-marker)
378                                    nil t))
379           (forward-sexp)
380           (when (setq is-old
381                       (nnmail-expired-article-p
382                        newsgroup
383                        (buffer-substring
384                         (point) (progn (end-of-line) (point)))
385                        force nnfolder-inhibit-expiry))
386             (unless (eq nnmail-expiry-target 'delete)
387               (with-temp-buffer
388                 (nnfolder-request-article (car maybe-expirable) 
389                                           newsgroup server (current-buffer))
390                 (let ((nnml-current-directory nil))
391                   (nnmail-expiry-target-group
392                    nnmail-expiry-target newsgroup))))
393             (nnheader-message 5 "Deleting article %d in %s..."
394                               (car maybe-expirable) newsgroup)
395             (nnfolder-delete-mail)
396             (unless (or gnus-nov-is-evil nnfolder-nov-is-evil)
397               (nnfolder-nov-delete-article newsgroup (car maybe-expirable)))
398             ;; Must remember which articles were actually deleted
399             (push (car maybe-expirable) deleted-articles)))
400         (setq maybe-expirable (cdr maybe-expirable)))
401       (unless nnfolder-inhibit-expiry
402         (nnheader-message 5 "Deleting articles...done"))
403       (nnfolder-save-buffer)
404       (nnfolder-adjust-min-active newsgroup)
405       (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
406       (gnus-sorted-complement articles (nreverse deleted-articles)))))
407
408 (deffoo nnfolder-request-move-article (article group server
409                                                accept-form &optional last)
410   (save-excursion
411     (let ((buf (get-buffer-create " *nnfolder move*"))
412           result)
413       (and
414        (nnfolder-request-article article group server)
415        (save-excursion
416          (set-buffer buf)
417          (erase-buffer)
418          (insert-buffer-substring nntp-server-buffer)
419          (goto-char (point-min))
420          (while (re-search-forward
421                  (concat "^" nnfolder-article-marker)
422                  (save-excursion (and (search-forward "\n\n" nil t) (point))) 
423                  t)
424            (delete-region (progn (beginning-of-line) (point))
425                           (progn (forward-line 1) (point))))
426          (setq result (eval accept-form))
427          (kill-buffer buf)
428          result)
429        (save-excursion
430          (nnfolder-possibly-change-group group server)
431          (set-buffer nnfolder-current-buffer)
432          (goto-char (point-min))
433          (when (nnfolder-goto-article article)
434            (nnfolder-delete-mail))
435          (unless (or gnus-nov-is-evil nnfolder-nov-is-evil)
436            (nnfolder-nov-delete-article group article))
437          (when last
438            (nnfolder-save-buffer)
439            (nnfolder-adjust-min-active group)
440            (nnfolder-save-active nnfolder-group-alist nnfolder-active-file))))
441       result)))
442
443 (deffoo nnfolder-request-accept-article (group &optional server last)
444   (save-excursion
445     (nnfolder-possibly-change-group group server)
446     (nnmail-check-syntax)
447     (let ((buf (current-buffer))
448           result art-group)
449       (goto-char (point-min))
450       (when (looking-at "X-From-Line: ")
451         (replace-match "From "))
452       (and
453        (nnfolder-request-list)
454        (save-excursion
455          (set-buffer buf)
456          (goto-char (point-min))
457          (if (search-forward "\n\n" nil t)
458              (forward-line -1)
459            (goto-char (point-max)))
460          (while (re-search-backward (concat "^" nnfolder-article-marker) nil t)
461            (delete-region (point) (progn (forward-line 1) (point))))
462          (when nnmail-cache-accepted-message-ids
463            (nnmail-cache-insert (nnmail-fetch-field "message-id")))
464          (setq result (if (stringp group)
465                           (list (cons group (nnfolder-active-number group)))
466                         (setq art-group
467                               (nnmail-article-group 'nnfolder-active-number))))
468          (if (and (null result)
469                   (yes-or-no-p "Moved to `junk' group; delete article? "))
470              (setq result 'junk)
471            (setq result
472                  (car (nnfolder-save-mail result)))))
473        (when last
474          (save-excursion
475            (nnfolder-possibly-change-folder (or (caar art-group) group))
476            (nnfolder-save-buffer)
477            (when nnmail-cache-accepted-message-ids
478              (nnmail-cache-close)))))
479       (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
480       (unless result
481         (nnheader-report 'nnfolder "Couldn't store article"))
482       result)))
483
484 (deffoo nnfolder-request-replace-article (article group buffer)
485   (nnfolder-possibly-change-group group)
486   (save-excursion
487     (set-buffer buffer)
488     (goto-char (point-min))
489     (let (xfrom)
490       (while (re-search-forward "^X-From-Line: \\(.*\\)$" nil t)
491         (setq xfrom (match-string 1))
492         (gnus-delete-line))
493       (goto-char (point-min))
494       (if xfrom
495           (insert "From " xfrom "\n")
496         (unless (looking-at "From ")
497           (insert "From nobody " (current-time-string) "\n"))))
498     (nnfolder-normalize-buffer)
499     (set-buffer nnfolder-current-buffer)
500     (goto-char (point-min))
501     (if (not (nnfolder-goto-article article))
502         nil
503       (nnfolder-delete-mail)
504       (insert-buffer-substring buffer)
505       (unless (or gnus-nov-is-evil nnfolder-nov-is-evil)
506         (save-excursion
507           (set-buffer buffer)
508           (let ((headers (nnfolder-parse-head article 
509                                               (point-min) (point-max))))
510             (with-current-buffer (nnfolder-open-nov group)
511               (if (nnheader-find-nov-line article)
512                   (delete-region (point) (progn (forward-line 1) (point))))
513               (nnheader-insert-nov headers)))))
514       (nnfolder-save-buffer)
515       t)))
516
517 (deffoo nnfolder-request-delete-group (group &optional force server)
518   (nnfolder-close-group group server t)
519   ;; Delete all articles in GROUP.
520   (if (not force)
521       ()                                ; Don't delete the articles.
522     ;; Delete the file that holds the group.
523     (ignore-errors
524       (delete-file (nnfolder-group-pathname group))
525       (delete-file (nnfolder-group-nov-pathname group))))
526   ;; Remove the group from all structures.
527   (setq nnfolder-group-alist
528         (delq (assoc group nnfolder-group-alist) nnfolder-group-alist)
529         nnfolder-current-group nil
530         nnfolder-current-buffer nil)
531   ;; Save the active file.
532   (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
533   t)
534
535 (deffoo nnfolder-request-rename-group (group new-name &optional server)
536   (nnfolder-possibly-change-group group server)
537   (save-excursion
538     (set-buffer nnfolder-current-buffer)
539     (and (file-writable-p buffer-file-name)
540          (ignore-errors
541            (let ((new-file (nnfolder-group-pathname new-name)))
542              (gnus-make-directory (file-name-directory new-file))
543              (rename-file buffer-file-name new-file)
544              (setq new-file (nnfolder-group-nov-pathname new-name))
545              (rename-file (nnfolder-group-nov-pathname group)
546                           new-file))
547            t)
548          ;; That went ok, so we change the internal structures.
549          (let ((entry (assoc group nnfolder-group-alist)))
550            (and entry (setcar entry new-name))
551            (setq nnfolder-current-buffer nil
552                  nnfolder-current-group nil)
553            ;; Save the new group alist.
554            (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
555            ;; We kill the buffer instead of renaming it and stuff.
556            (kill-buffer (current-buffer))
557            t))))
558
559 (deffoo nnfolder-request-regenerate (server)
560   (nnfolder-possibly-change-group nil server)
561   (nnfolder-generate-active-file)
562   t)
563
564 \f
565 ;;; Internal functions.
566
567 (defun nnfolder-adjust-min-active (group)
568   ;; Find the lowest active article in this group.
569   (let* ((active (cadr (assoc group nnfolder-group-alist)))
570          (marker (concat "\n" nnfolder-article-marker))
571          (number "[0-9]+")
572          (activemin (cdr active)))
573     (save-excursion
574       (set-buffer nnfolder-current-buffer)
575       (goto-char (point-min))
576       (while (and (search-forward marker nil t)
577                   (re-search-forward number nil t))
578         (let ((newnum (string-to-number (match-string 0))))
579           (if (nnmail-within-headers-p)
580               (setq activemin (min activemin newnum)))))
581       (setcar active activemin))))
582
583 (defun nnfolder-article-string (article)
584   (if (numberp article)
585       (concat "\n" nnfolder-article-marker (int-to-string article) " ")
586     (concat "\nMessage-ID: " article)))
587
588 (defun nnfolder-goto-article (article)
589   "Place point at the start of the headers of ARTICLE.
590 ARTICLE can be an article number or a Message-ID.
591 Returns t if successful, nil otherwise."
592   (let ((art-string (nnfolder-article-string article))
593         start found)
594     ;; It is likely that we are at or before the delimiter line.
595     ;; We therefore go to the end of the previous line, and start
596     ;; searching from there.
597     (beginning-of-line)
598     (unless (bobp)
599       (forward-char -1))
600     (setq start (point))
601     ;; First search forward.
602     (while (and (setq found (search-forward art-string nil t))
603                 (not (nnmail-within-headers-p))))
604     ;; If unsuccessful, search backward from where we started,
605     (unless found
606       (goto-char start)
607       (while (and (setq found (search-backward art-string nil t))
608                   (not (nnmail-within-headers-p)))))
609     (when found
610       (nnmail-search-unix-mail-delim-backward))))
611
612 (defun nnfolder-delete-mail (&optional leave-delim)
613   "Delete the message that point is in.
614 If optional argument LEAVE-DELIM is t, then mailbox delimiter is not
615 deleted.  Point is left where the deleted region was."
616   (save-restriction
617     (narrow-to-region
618      (save-excursion
619        ;; In case point is at the beginning of the message already.
620        (forward-line 1)
621        (nnmail-search-unix-mail-delim-backward)
622        (if leave-delim (progn (forward-line 1) (point))
623          (point)))
624      (progn
625        (forward-line 1)
626        (if (nnmail-search-unix-mail-delim)
627            (point)
628          (point-max))))
629     (run-hooks 'nnfolder-delete-mail-hook)
630     (delete-region (point-min) (point-max))))
631
632 (defun nnfolder-possibly-change-group (group &optional server dont-check)
633   ;; Change servers.
634   (when (and server
635              (not (nnfolder-server-opened server)))
636     (nnfolder-open-server server))
637   (unless (gnus-buffer-live-p nnfolder-current-buffer)
638     (setq nnfolder-current-buffer nil
639           nnfolder-current-group nil))
640   ;; Change group.
641   (when (and group
642              (not (equal group nnfolder-current-group)))
643     (let ((file-name-coding-system nnmail-pathname-coding-system)
644           (pathname-coding-system nnmail-pathname-coding-system))
645       (nnmail-activate 'nnfolder)
646       (when (and (not (assoc group nnfolder-group-alist))
647                  (not (file-exists-p
648                        (nnfolder-group-pathname group))))
649         ;; The group doesn't exist, so we create a new entry for it.
650         (push (list group (cons 1 0)) nnfolder-group-alist)
651         (nnfolder-save-active nnfolder-group-alist nnfolder-active-file))
652
653       (if dont-check
654           (setq nnfolder-current-group group
655                 nnfolder-current-buffer nil)
656         (let (inf file)
657           ;; If we have to change groups, see if we don't already have the
658           ;; folder in memory.  If we do, verify the modtime and destroy
659           ;; the folder if needed so we can rescan it.
660           (setq nnfolder-current-buffer
661                 (nth 1 (assoc group nnfolder-buffer-alist)))
662
663           ;; If the buffer is not live, make sure it isn't in the alist.  If it
664           ;; is live, verify that nobody else has touched the file since last
665           ;; time.
666           (when (and nnfolder-current-buffer
667                      (not (gnus-buffer-live-p nnfolder-current-buffer)))
668             (setq nnfolder-buffer-alist (delq inf nnfolder-buffer-alist)
669                   nnfolder-current-buffer nil))
670
671           (setq nnfolder-current-group group)
672
673           (when (or (not nnfolder-current-buffer)
674                     (not (verify-visited-file-modtime
675                           nnfolder-current-buffer)))
676             (save-excursion
677               (setq file (nnfolder-group-pathname group))
678               ;; See whether we need to create the new file.
679               (unless (file-exists-p file)
680                 (gnus-make-directory (file-name-directory file))
681                 (let ((nnmail-file-coding-system 
682                        (or nnfolder-file-coding-system-for-write
683                            nnfolder-file-coding-system-for-write)))
684                   (nnmail-write-region 1 1 file t 'nomesg)))
685               (when (setq nnfolder-current-buffer (nnfolder-read-folder group))
686                 (set-buffer nnfolder-current-buffer)
687                 (push (list group nnfolder-current-buffer)
688                       nnfolder-buffer-alist)))))))))
689
690 (defun nnfolder-save-mail (group-art-list)
691   "Called narrowed to an article."
692   (let* (save-list group-art)
693     (goto-char (point-min))
694     ;; The From line may have been quoted by movemail.
695     (when (looking-at ">From")
696       (delete-char 1))
697     ;; This might come from somewhere else.
698     (unless (looking-at "From ")
699       (insert "From nobody " (current-time-string) "\n")
700       (goto-char (point-min)))
701     ;; Quote all "From " lines in the article.
702     (forward-line 1)
703     (let (case-fold-search)
704       (while (re-search-forward "^From " nil t)
705         (beginning-of-line)
706         (insert "> ")))
707     (setq save-list group-art-list)
708     (nnmail-insert-lines)
709     (nnmail-insert-xref group-art-list)
710     (run-hooks 'nnmail-prepare-save-mail-hook)
711     (run-hooks 'nnfolder-prepare-save-mail-hook)
712
713     ;; Insert the mail into each of the destination groups.
714     (while (setq group-art (pop group-art-list))
715       ;; Kill any previous newsgroup markers.
716       (goto-char (point-min))
717       (if (search-forward "\n\n" nil t)
718           (forward-line -1)
719         (goto-char (point-max)))
720       (while (search-backward (concat "\n" nnfolder-article-marker) nil t)
721         (delete-region (1+ (point)) (progn (forward-line 2) (point))))
722
723       ;; Insert the new newsgroup marker.
724       (nnfolder-insert-newsgroup-line group-art)
725
726       (save-excursion
727         (let ((beg (point-min))
728               (end (point-max))
729               (obuf (current-buffer)))
730           (nnfolder-possibly-change-folder (car group-art))
731           (let ((buffer-read-only nil))
732             (nnfolder-normalize-buffer)
733             (insert-buffer-substring obuf beg end))
734           (unless (or gnus-nov-is-evil nnfolder-nov-is-evil)
735             (set-buffer obuf)
736             (nnfolder-add-nov (car group-art) (cdr group-art)
737                               (nnfolder-parse-head nil beg end))))))
738
739     ;; Did we save it anywhere?
740     save-list))
741
742 (defun nnfolder-normalize-buffer ()
743   "Make sure there are two newlines at the end of the buffer."
744   (goto-char (point-max))
745   (skip-chars-backward "\n")
746   (delete-region (point) (point-max))
747   (insert "\n\n"))
748
749 (defun nnfolder-insert-newsgroup-line (group-art)
750   (save-excursion
751     (goto-char (point-min))
752     (unless (search-forward "\n\n" nil t)
753       (goto-char (point-max))
754       (insert "\n"))
755     (forward-char -1)
756     (insert (format (concat nnfolder-article-marker "%d   %s\n")
757                     (cdr group-art) (current-time-string)))))
758
759 (defun nnfolder-active-number (group)
760   ;; Find the next article number in GROUP.
761   (let ((active (cadr (assoc group nnfolder-group-alist))))
762     (if active
763         (setcdr active (1+ (cdr active)))
764       ;; This group is new, so we create a new entry for it.
765       ;; This might be a bit naughty... creating groups on the drop of
766       ;; a hat, but I don't know...
767       (push (list group (setq active (cons 1 1)))
768             nnfolder-group-alist))
769     (cdr active)))
770
771 (defun nnfolder-possibly-change-folder (group)
772   (let ((inf (assoc group nnfolder-buffer-alist)))
773     (if (and inf
774              (gnus-buffer-live-p (cadr inf)))
775         (set-buffer (cadr inf))
776       (when inf
777         (setq nnfolder-buffer-alist (delq inf nnfolder-buffer-alist)))
778       (when nnfolder-group-alist
779         (nnfolder-save-active nnfolder-group-alist nnfolder-active-file))
780       (push (list group (nnfolder-read-folder group))
781             nnfolder-buffer-alist))))
782
783 ;; This method has a problem if you've accidentally let the active list get
784 ;; out of sync with the files.  This could happen, say, if you've
785 ;; accidentally gotten new mail with something other than Gnus (but why
786 ;; would _that_ ever happen? :-).  In that case, we will be in the middle of
787 ;; processing the file, ready to add new X-Gnus article number markers, and
788 ;; we'll run across a message with no ID yet - the active list _may_not_ be
789 ;; ready for us yet.
790
791 ;; To handle this, I'm modifying this routine to maintain the maximum ID seen
792 ;; so far, and when we hit a message with no ID, we will _manually_ scan the
793 ;; rest of the message looking for any more, possibly higher IDs.  We'll
794 ;; assume the maximum that we find is the highest active.  Note that this
795 ;; shouldn't cost us much extra time at all, but will be a lot less
796 ;; vulnerable to glitches between the mbox and the active file.
797
798 (defun nnfolder-read-folder (group)
799   (let* ((file (nnfolder-group-pathname group))
800          (nov  (nnfolder-group-nov-pathname group))
801          (buffer (set-buffer
802                   (let ((nnheader-file-coding-system 
803                          nnfolder-file-coding-system))
804                     (nnheader-find-file-noselect file)))))
805     (if (equal (cadr (assoc group nnfolder-scantime-alist))
806                (nth 5 (file-attributes file)))
807         ;; This looks up-to-date, so we don't do any scanning.
808         (if (file-exists-p file)
809             buffer
810           (push (list group buffer) nnfolder-buffer-alist)
811           (set-buffer-modified-p t)
812           (nnfolder-save-buffer))
813       ;; Parse the damn thing.
814       (save-excursion
815         (goto-char (point-min))
816         ;; Remove any blank lines at the start.
817         (while (eq (following-char) ?\n)
818           (delete-char 1))
819         (nnmail-activate 'nnfolder)
820         ;; Read in the file.
821         (let ((delim "^From ")
822               (marker (concat "\n" nnfolder-article-marker))
823               (number "[0-9]+")
824               (active (or (cadr (assoc group nnfolder-group-alist))
825                           (cons 1 0)))
826               (scantime (assoc group nnfolder-scantime-alist))
827               (minid (lsh -1 -1))
828               maxid start end newscantime
829               novbuf articles newnum
830               buffer-read-only)
831           (buffer-disable-undo)
832           (setq maxid (cdr active))
833
834           (unless (or gnus-nov-is-evil nnfolder-nov-is-evil
835                       (and (file-exists-p nov)
836                            (file-newer-than-file-p nov file)))
837             (unless (file-exists-p nov)
838               (gnus-make-directory (file-name-directory nov)))
839             (with-current-buffer
840                 (setq novbuf (nnfolder-open-nov group))
841               (goto-char (point-min))
842               (while (not (eobp))
843                 (push (read novbuf) articles)
844                 (forward-line 1))
845               (setq articles (nreverse articles))))
846           (goto-char (point-min))
847
848           ;; Anytime the active number is 1 or 0, it is suspect.  In that
849           ;; case, search the file manually to find the active number.  Or,
850           ;; of course, if we're being paranoid.  (This would also be the
851           ;; place to build other lists from the header markers, such as
852           ;; expunge lists, etc., if we ever desired to abandon the active
853           ;; file entirely for mboxes.)
854           (when (or nnfolder-ignore-active-file
855                     novbuf
856                     (< maxid 2))
857             (while (and (search-forward marker nil t)
858                         (looking-at number))
859               (setq newnum (string-to-number (match-string 0)))
860               (when (nnmail-within-headers-p)
861                 (setq maxid (max maxid newnum)
862                       minid (min minid newnum))
863                 (when novbuf
864                   (if (memq newnum articles)
865                       (setq articles (delq newnum articles))
866                     (let ((headers (nnfolder-parse-head newnum)))
867                       (with-current-buffer novbuf
868                         (nnheader-find-nov-line newnum)
869                         (nnheader-insert-nov headers)))))))
870             (when (and novbuf articles)
871               (with-current-buffer novbuf
872                 (dolist (article articles)
873                   (when (nnheader-find-nov-line article)
874                     (delete-region (point) 
875                                    (progn (forward-line 1) (point)))))))
876             (setcar active (max 1 (min minid maxid)))
877             (setcdr active (max maxid (cdr active)))
878             (goto-char (point-min)))
879
880           ;; As long as we trust that the user will only insert unmarked mail
881           ;; at the end, go to the end and search backwards for the last
882           ;; marker.  Find the start of that message, and begin to search for
883           ;; unmarked messages from there.
884           (when (not (or nnfolder-distrust-mbox
885                          (< maxid 2)))
886             (goto-char (point-max))
887             (unless (re-search-backward marker nil t)
888               (goto-char (point-min)))
889             ;;(when (nnmail-search-unix-mail-delim)
890             ;;  (goto-char (point-min)))
891             )
892
893           ;; Keep track of the active number on our own, and insert it back
894           ;; into the active list when we're done.  Also, prime the pump to
895           ;; cut down on the number of searches we do.
896           (unless (nnmail-search-unix-mail-delim)
897             (goto-char (point-max)))
898           (setq end (point-marker))
899           (while (not (= end (point-max)))
900             (setq start (marker-position end))
901             (goto-char end)
902             ;; There may be more than one "From " line, so we skip past
903             ;; them.
904             (while (looking-at delim)
905               (forward-line 1))
906             (set-marker end (if (nnmail-search-unix-mail-delim)
907                                 (point)
908                               (point-max)))
909             (goto-char start)
910             (when (not (search-forward marker end t))
911               (narrow-to-region start end)
912               (nnmail-insert-lines)
913               (nnfolder-insert-newsgroup-line
914                (cons nil 
915                      (setq newnum
916                            (nnfolder-active-number nnfolder-current-group))))
917               (when novbuf
918                 (let ((headers (nnfolder-parse-head newnum (point-min)
919                                                       (point-max))))
920                   (with-current-buffer novbuf
921                     (goto-char (point-max))
922                     (nnheader-insert-nov headers))))
923               (widen)))
924
925           (set-marker end nil)
926           ;; Make absolutely sure that the active list reflects reality!
927           (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
928
929           ;; Set the scantime for this group.
930           (setq newscantime (visited-file-modtime))
931           (if scantime
932               (setcdr scantime (list newscantime))
933             (push (list nnfolder-current-group newscantime)
934                   nnfolder-scantime-alist))
935           ;; Save nov.
936           (when novbuf
937             (nnfolder-save-nov))
938           (current-buffer))))))
939
940 ;;;###autoload
941 (defun nnfolder-generate-active-file ()
942   "Look for mbox folders in the nnfolder directory and make them into groups.
943 This command does not work if you use short group names."
944   (interactive)
945   (nnmail-activate 'nnfolder)
946   (unless (or gnus-nov-is-evil nnfolder-nov-is-evil)
947     (dolist (file (directory-files (or nnfolder-nov-directory 
948                                        nnfolder-directory)
949                                    t 
950                                    (concat 
951                                     (regexp-quote nnfolder-nov-file-suffix)
952                                     "$")))
953       (when (not (message-mail-file-mbox-p file))
954         (ignore-errors
955           (delete-file file)))))
956   (let ((files (directory-files nnfolder-directory))
957         file)
958     (while (setq file (pop files))
959       (when (and (not (backup-file-name-p file))
960                  (message-mail-file-mbox-p
961                   (nnheader-concat nnfolder-directory file)))
962         (let ((oldgroup (assoc file nnfolder-group-alist)))
963           (if oldgroup
964               (nnheader-message 5 "Refreshing group %s..." file)
965             (nnheader-message 5 "Adding group %s..." file))
966           (if oldgroup
967               (setq nnfolder-group-alist
968                     (delq oldgroup (copy-sequence nnfolder-group-alist))))
969           (push (list file (cons 1 0)) nnfolder-group-alist)
970           (nnfolder-possibly-change-folder file)
971           (nnfolder-possibly-change-group file)
972           (nnfolder-close-group file))))
973     (nnheader-message 5 "")))
974
975 (defun nnfolder-group-pathname (group)
976   "Make pathname for GROUP."
977   (setq group
978         (encode-coding-string group nnmail-pathname-coding-system))
979   (let ((dir (file-name-as-directory (expand-file-name nnfolder-directory))))
980     ;; If this file exists, we use it directly.
981     (if (or nnmail-use-long-file-names
982             (file-exists-p (concat dir group)))
983         (concat dir group)
984       ;; If not, we translate dots into slashes.
985       (concat dir (nnheader-replace-chars-in-string group ?. ?/)))))
986
987 (defun nnfolder-group-nov-pathname (group)
988   "Make pathname for GROUP NOV."
989   (let ((nnfolder-directory
990          (or nnfolder-nov-directory nnfolder-directory)))
991     (concat (nnfolder-group-pathname group) nnfolder-nov-file-suffix)))
992
993 (defun nnfolder-save-buffer ()
994   "Save the buffer."
995   (when (buffer-modified-p)
996     (run-hooks 'nnfolder-save-buffer-hook)
997     (gnus-make-directory (file-name-directory (buffer-file-name)))
998     (let* ((coding-system-for-write
999             (or nnfolder-file-coding-system-for-write
1000                 nnfolder-file-coding-system))
1001            (output-coding-system coding-system-for-write))
1002       (save-buffer)))
1003   (unless (or gnus-nov-is-evil nnfolder-nov-is-evil)
1004     (nnfolder-save-nov)))
1005
1006 (defun nnfolder-save-active (group-alist active-file)
1007   (let ((nnmail-active-file-coding-system
1008          (or nnfolder-active-file-coding-system-for-write
1009              nnfolder-active-file-coding-system)))
1010     (nnmail-save-active group-alist active-file)))
1011
1012 (defun nnfolder-open-nov (group)
1013   (or (cdr (assoc group nnfolder-nov-buffer-alist))
1014       (let ((buffer (get-buffer-create (format " *nnfolder overview %s*" group))))
1015         (save-excursion
1016           (set-buffer buffer)
1017           (set (make-local-variable 'nnfolder-nov-buffer-file-name)
1018                (nnfolder-group-nov-pathname group))
1019           (erase-buffer)
1020           (when (file-exists-p nnfolder-nov-buffer-file-name)
1021             (nnheader-insert-file-contents nnfolder-nov-buffer-file-name)))
1022         (push (cons group buffer) nnfolder-nov-buffer-alist)
1023         buffer)))
1024
1025 (defun nnfolder-save-nov ()
1026   (save-excursion
1027     (while nnfolder-nov-buffer-alist
1028       (when (buffer-name (cdar nnfolder-nov-buffer-alist))
1029         (set-buffer (cdar nnfolder-nov-buffer-alist))
1030         (when (buffer-modified-p)
1031           (gnus-make-directory (file-name-directory 
1032                                 nnfolder-nov-buffer-file-name))
1033           (nnmail-write-region 1 (point-max) nnfolder-nov-buffer-file-name
1034                                nil 'nomesg))
1035         (set-buffer-modified-p nil)
1036         (kill-buffer (current-buffer)))
1037       (setq nnfolder-nov-buffer-alist (cdr nnfolder-nov-buffer-alist)))))
1038
1039 (defun nnfolder-nov-delete-article (group article)
1040   (save-excursion
1041     (set-buffer (nnfolder-open-nov group))
1042     (when (nnheader-find-nov-line article)
1043       (delete-region (point) (progn (forward-line 1) (point))))
1044     t))
1045
1046 (defun nnfolder-retrieve-headers-with-nov (articles &optional fetch-old)
1047   (if (or gnus-nov-is-evil nnfolder-nov-is-evil)
1048       nil
1049     (let ((nov (nnfolder-group-nov-pathname nnfolder-current-group)))
1050       (when (file-exists-p nov)
1051         (save-excursion
1052           (set-buffer nntp-server-buffer)
1053           (erase-buffer)
1054           (nnheader-insert-file-contents nov)
1055           (if (and fetch-old
1056                    (not (numberp fetch-old)))
1057               t                         ; Don't remove anything.
1058             (nnheader-nov-delete-outside-range
1059              (if fetch-old (max 1 (- (car articles) fetch-old))
1060                (car articles))
1061              (car (last articles)))
1062             t))))))
1063
1064 (defun nnfolder-parse-head (&optional number b e)
1065   "Parse the head of the current buffer."
1066   (let ((buf (current-buffer))
1067         chars)
1068   (save-excursion
1069     (unless b
1070       (setq b (if (nnmail-search-unix-mail-delim-backward)
1071                   (point) (point-min)))
1072       (forward-line 1)
1073       (setq e (if (nnmail-search-unix-mail-delim)
1074                   (point) (point-max))))
1075     (setq chars (- e b))
1076     (unless (zerop chars)
1077       (goto-char b)
1078       (if (search-forward "\n\n" e t) (setq e (1- (point)))))
1079     (with-temp-buffer
1080       (insert-buffer-substring buf b e)
1081       ;; Fold continuation lines.
1082       (goto-char (point-min))
1083       (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
1084         (replace-match " " t t))
1085       ;; Remove any tabs; they are too confusing.
1086       (subst-char-in-region (point-min) (point-max) ?\t ? )
1087       (let ((headers (nnheader-parse-head t)))
1088         (mail-header-set-chars headers chars)
1089         (mail-header-set-number headers number)
1090         headers)))))
1091
1092 (defun nnfolder-add-nov (group article headers)
1093   "Add a nov line for the GROUP base."
1094   (save-excursion
1095     (set-buffer (nnfolder-open-nov group))
1096     (goto-char (point-max))
1097     (mail-header-set-number headers article)
1098     (nnheader-insert-nov headers)))
1099
1100 (provide 'nnfolder)
1101
1102 ;;; nnfolder.el ends here