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