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