Feedback from the branch `t-gnus-6_13'.
[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
94     (if (memq system-type '(windows-nt ms-dos ms-windows))
95         'raw-text-dos 'raw-text))
96 (defvoo nnfolder-active-file-coding-system-for-write 
97     nnmail-active-file-coding-system)
98 (defvoo nnfolder-file-coding-system nnfolder-active-file-coding-system)
99 (defvoo nnfolder-file-coding-system-for-write nnheader-file-coding-system
100   "Coding system for save nnfolder file.
101 If NIL, NNFOLDER-FILE-CODING-SYSTEM is used.")
102
103 \f
104
105 ;;; Interface functions
106
107 (nnoo-define-basics nnfolder)
108
109 (deffoo nnfolder-retrieve-headers (articles &optional group server fetch-old)
110   (save-excursion
111     (set-buffer nntp-server-buffer)
112     (erase-buffer)
113     (let (article start stop)
114       (nnfolder-possibly-change-group group server)
115       (when nnfolder-current-buffer
116         (set-buffer nnfolder-current-buffer)
117         (goto-char (point-min))
118         (if (stringp (car articles))
119             'headers
120           (while (setq article (pop articles))
121             (set-buffer nnfolder-current-buffer)
122             (when (nnfolder-goto-article article)
123               (setq start (point))
124               (setq stop (if (search-forward "\n\n" nil t)
125                              (1- (point))
126                            (point-max)))
127               (set-buffer nntp-server-buffer)
128               (insert (format "221 %d Article retrieved.\n" article))
129               (insert-buffer-substring nnfolder-current-buffer start stop)
130               (goto-char (point-max))
131               (insert ".\n")))
132
133           (set-buffer nntp-server-buffer)
134           (nnheader-fold-continuation-lines)
135           'headers)))))
136
137 (deffoo nnfolder-open-server (server &optional defs)
138   (nnoo-change-server 'nnfolder server defs)
139   (nnmail-activate 'nnfolder t)
140   (gnus-make-directory nnfolder-directory)
141   (cond
142    ((not (file-exists-p nnfolder-directory))
143     (nnfolder-close-server)
144     (nnheader-report 'nnfolder "Couldn't create directory: %s"
145                      nnfolder-directory))
146    ((not (file-directory-p (file-truename nnfolder-directory)))
147     (nnfolder-close-server)
148     (nnheader-report 'nnfolder "Not a directory: %s" nnfolder-directory))
149    (t
150     (nnmail-activate 'nnfolder)
151     (nnheader-report 'nnfolder "Opened server %s using directory %s"
152                      server nnfolder-directory)
153     t)))
154
155 (deffoo nnfolder-request-close ()
156   (let ((alist nnfolder-buffer-alist))
157     (while alist
158       (nnfolder-close-group (caar alist) nil t)
159       (setq alist (cdr alist))))
160   (nnoo-close-server 'nnfolder)
161   (setq nnfolder-buffer-alist nil
162         nnfolder-group-alist nil))
163
164 (deffoo nnfolder-request-article (article &optional group server buffer)
165   (nnfolder-possibly-change-group group server)
166   (save-excursion
167     (set-buffer nnfolder-current-buffer)
168     (goto-char (point-min))
169     (when (nnfolder-goto-article article)
170       (let (start stop)
171         (setq start (point))
172         (forward-line 1)
173         (unless (and (nnmail-search-unix-mail-delim)
174                      (forward-line -1))
175           (goto-char (point-max)))
176         (setq stop (point))
177         (let ((nntp-server-buffer (or buffer nntp-server-buffer)))
178           (set-buffer nntp-server-buffer)
179           (erase-buffer)
180           (insert-buffer-substring nnfolder-current-buffer start stop)
181           (goto-char (point-min))
182           (while (looking-at "From ")
183             (delete-char 5)
184             (insert "X-From-Line: ")
185             (forward-line 1))
186           (if (numberp article)
187               (cons nnfolder-current-group article)
188             (goto-char (point-min))
189             (search-forward (concat "\n" nnfolder-article-marker))
190             (cons nnfolder-current-group
191                   (string-to-int
192                    (buffer-substring
193                     (point) (progn (end-of-line) (point)))))))))))
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     (nnmail-activate 'nnfolder)
585     (if dont-check
586         (setq nnfolder-current-group group
587               nnfolder-current-buffer nil)
588       ;; If we have to change groups, see if we don't already have the
589       ;; folder in memory.  If we do, verify the modtime and destroy
590       ;; the folder if needed so we can rescan it.
591       (setq nnfolder-current-buffer
592             (nth 1 (assoc group nnfolder-buffer-alist)))
593
594       ;; If the buffer is not live, make sure it isn't in the alist.  If it
595       ;; is live, verify that nobody else has touched the file since last
596       ;; time.
597       (when (and nnfolder-current-buffer
598                  (not (gnus-buffer-live-p nnfolder-current-buffer)))
599         (setq nnfolder-current-buffer nil))
600
601       (setq nnfolder-current-group group)
602
603       (when (or (not nnfolder-current-buffer)
604                 (not (verify-visited-file-modtime
605                       nnfolder-current-buffer)))
606         (save-excursion
607           (when (setq nnfolder-current-buffer (nnfolder-read-folder group))
608             (set-buffer nnfolder-current-buffer)
609             (push (list group nnfolder-current-buffer)
610                   nnfolder-buffer-alist)))))))
611
612 (defun nnfolder-save-mail (group-art-list)
613   "Called narrowed to an article."
614   (let* (save-list group-art)
615     (goto-char (point-min))
616     ;; The From line may have been quoted by movemail.
617     (when (looking-at ">From")
618       (delete-char 1))
619     ;; This might come from somewhere else.
620     (unless (looking-at "From ")
621       (insert "From nobody " (current-time-string) "\n")
622       (goto-char (point-min)))
623     ;; Quote all "From " lines in the article.
624     (forward-line 1)
625     (let (case-fold-search)
626       (while (re-search-forward "^From " nil t)
627         (beginning-of-line)
628         (insert "> ")))
629     (setq save-list group-art-list)
630     (nnmail-insert-lines)
631     (nnmail-insert-xref group-art-list)
632     (run-hooks 'nnmail-prepare-save-mail-hook)
633     (run-hooks 'nnfolder-prepare-save-mail-hook)
634
635     ;; Insert the mail into each of the destination groups.
636     (while (setq group-art (pop group-art-list))
637       ;; Kill any previous newsgroup markers.
638       (goto-char (point-min))
639       (if (search-forward "\n\n" nil t)
640           (forward-line -1)
641         (goto-char (point-max)))
642       (while (search-backward (concat "\n" nnfolder-article-marker) nil t)
643         (delete-region (1+ (point)) (progn (forward-line 2) (point))))
644
645       ;; Insert the new newsgroup marker.
646       (nnfolder-insert-newsgroup-line group-art)
647
648       (save-excursion
649         (let ((beg (point-min))
650               (end (point-max))
651               (obuf (current-buffer)))
652           (nnfolder-possibly-change-folder (car group-art))
653           (let ((buffer-read-only nil))
654             (nnfolder-normalize-buffer)
655             (insert-buffer-substring obuf beg end)))))
656
657     ;; Did we save it anywhere?
658     save-list))
659
660 (defun nnfolder-normalize-buffer ()
661   "Make sure there are two newlines at the end of the buffer."
662   (goto-char (point-max))
663   (skip-chars-backward "\n")
664   (delete-region (point) (point-max))
665   (insert "\n\n"))
666
667 (defun nnfolder-insert-newsgroup-line (group-art)
668   (save-excursion
669     (goto-char (point-min))
670     (unless (search-forward "\n\n" nil t)
671       (goto-char (point-max))
672       (insert "\n"))
673     (forward-char -1)
674     (insert (format (concat nnfolder-article-marker "%d   %s\n")
675                     (cdr group-art) (current-time-string)))))
676
677 (defun nnfolder-active-number (group)
678   ;; Find the next article number in GROUP.
679   (let ((active (cadr (assoc group nnfolder-group-alist))))
680     (if active
681         (setcdr active (1+ (cdr active)))
682       ;; This group is new, so we create a new entry for it.
683       ;; This might be a bit naughty... creating groups on the drop of
684       ;; a hat, but I don't know...
685       (push (list group (setq active (cons 1 1)))
686             nnfolder-group-alist))
687     (cdr active)))
688
689 (defun nnfolder-possibly-change-folder (group)
690   (let ((inf (assoc group nnfolder-buffer-alist)))
691     (if (and inf
692              (gnus-buffer-live-p (cadr inf)))
693         (set-buffer (cadr inf))
694       (when inf
695         (setq nnfolder-buffer-alist (delq inf nnfolder-buffer-alist)))
696       (when nnfolder-group-alist
697         (nnfolder-save-active nnfolder-group-alist nnfolder-active-file))
698       (push (list group (nnfolder-read-folder group))
699             nnfolder-buffer-alist))))
700
701 ;; This method has a problem if you've accidentally let the active list get
702 ;; out of sync with the files.  This could happen, say, if you've
703 ;; accidentally gotten new mail with something other than Gnus (but why
704 ;; would _that_ ever happen? :-).  In that case, we will be in the middle of
705 ;; processing the file, ready to add new X-Gnus article number markers, and
706 ;; we'll run across a message with no ID yet - the active list _may_not_ be
707 ;; ready for us yet.
708
709 ;; To handle this, I'm modifying this routine to maintain the maximum ID seen
710 ;; so far, and when we hit a message with no ID, we will _manually_ scan the
711 ;; rest of the message looking for any more, possibly higher IDs.  We'll
712 ;; assume the maximum that we find is the highest active.  Note that this
713 ;; shouldn't cost us much extra time at all, but will be a lot less
714 ;; vulnerable to glitches between the mbox and the active file.
715
716 (defun nnfolder-read-folder (group)
717   (let* ((file (nnfolder-group-pathname group))
718          (buffer (set-buffer
719                   (let ((nnheader-file-coding-system 
720                          nnfolder-file-coding-system))
721                     (nnheader-find-file-noselect file)))))
722     (if (equal (cadr (assoc group nnfolder-scantime-alist))
723                (nth 5 (file-attributes file)))
724         ;; This looks up-to-date, so we don't do any scanning.
725         (if (file-exists-p file)
726             buffer
727           (push (list group buffer) nnfolder-buffer-alist)
728           (set-buffer-modified-p t)
729           (save-buffer))
730       ;; Parse the damn thing.
731       (save-excursion
732         (goto-char (point-min))
733         ;; Remove any blank lines at the start.
734         (while (eq (following-char) ?\n)
735           (delete-char 1))
736         (nnmail-activate 'nnfolder)
737         ;; Read in the file.
738         (let ((delim "^From ")
739               (marker (concat "\n" nnfolder-article-marker))
740               (number "[0-9]+")
741               (active (or (cadr (assoc group nnfolder-group-alist))
742                           (cons 1 0)))
743               (scantime (assoc group nnfolder-scantime-alist))
744               (minid (lsh -1 -1))
745               maxid start end newscantime
746               buffer-read-only)
747           (buffer-disable-undo)
748           (setq maxid (cdr active))
749           (goto-char (point-min))
750
751           ;; Anytime the active number is 1 or 0, it is suspect.  In that
752           ;; case, search the file manually to find the active number.  Or,
753           ;; of course, if we're being paranoid.  (This would also be the
754           ;; place to build other lists from the header markers, such as
755           ;; expunge lists, etc., if we ever desired to abandon the active
756           ;; file entirely for mboxes.)
757           (when (or nnfolder-ignore-active-file
758                     (< maxid 2))
759             (while (and (search-forward marker nil t)
760                         (re-search-forward number nil t))
761               (let ((newnum (string-to-number (match-string 0))))
762                 (if (nnmail-within-headers-p)
763                     (setq maxid (max maxid newnum)
764                           minid (min minid newnum)))))
765             (setcar active (max 1 (min minid maxid)))
766             (setcdr active (max maxid (cdr active)))
767             (goto-char (point-min)))
768
769           ;; As long as we trust that the user will only insert unmarked mail
770           ;; at the end, go to the end and search backwards for the last
771           ;; marker.  Find the start of that message, and begin to search for
772           ;; unmarked messages from there.
773           (when (not (or nnfolder-distrust-mbox
774                          (< maxid 2)))
775             (goto-char (point-max))
776             (unless (re-search-backward marker nil t)
777               (goto-char (point-min)))
778             (when (nnmail-search-unix-mail-delim)
779               (goto-char (point-min))))
780
781           ;; Keep track of the active number on our own, and insert it back
782           ;; into the active list when we're done.  Also, prime the pump to
783           ;; cut down on the number of searches we do.
784           (unless (nnmail-search-unix-mail-delim)
785             (goto-char (point-max)))
786           (setq end (point-marker))
787           (while (not (= end (point-max)))
788             (setq start (marker-position end))
789             (goto-char end)
790             ;; There may be more than one "From " line, so we skip past
791             ;; them.
792             (while (looking-at delim)
793               (forward-line 1))
794             (set-marker end (if (nnmail-search-unix-mail-delim)
795                                 (point)
796                               (point-max)))
797             (goto-char start)
798             (when (not (search-forward marker end t))
799               (narrow-to-region start end)
800               (nnmail-insert-lines)
801               (nnfolder-insert-newsgroup-line
802                (cons nil (nnfolder-active-number nnfolder-current-group)))
803               (widen)))
804
805           (set-marker end nil)
806           ;; Make absolutely sure that the active list reflects reality!
807           (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
808           ;; Set the scantime for this group.
809           (setq newscantime (visited-file-modtime))
810           (if scantime
811               (setcdr scantime (list newscantime))
812             (push (list nnfolder-current-group newscantime)
813                   nnfolder-scantime-alist))
814           (current-buffer))))))
815
816 ;;;###autoload
817 (defun nnfolder-generate-active-file ()
818   "Look for mbox folders in the nnfolder directory and make them into groups.
819 This command does not work if you use short group names."
820   (interactive)
821   (nnmail-activate 'nnfolder)
822   (let ((files (directory-files nnfolder-directory))
823         file)
824     (while (setq file (pop files))
825       (when (and (not (backup-file-name-p file))
826                  (message-mail-file-mbox-p
827                   (nnheader-concat nnfolder-directory file)))
828         (let ((oldgroup (assoc file nnfolder-group-alist)))
829           (if oldgroup
830               (nnheader-message 5 "Refreshing group %s..." file)
831             (nnheader-message 5 "Adding group %s..." file))
832           (if oldgroup
833               (setq nnfolder-group-alist
834                     (delq oldgroup (copy-sequence nnfolder-group-alist))))
835           (push (list file (cons 1 0)) nnfolder-group-alist)
836           (nnfolder-possibly-change-folder file)
837           (nnfolder-possibly-change-group file)
838           (nnfolder-close-group file))))
839     (nnheader-message 5 "")))
840
841 (defun nnfolder-group-pathname (group)
842   "Make pathname for GROUP."
843   (setq group
844         (encode-coding-string group nnmail-pathname-coding-system))
845   (let ((dir (file-name-as-directory (expand-file-name nnfolder-directory))))
846     ;; If this file exists, we use it directly.
847     (if (or nnmail-use-long-file-names
848             (file-exists-p (concat dir group)))
849         (concat dir group)
850       ;; If not, we translate dots into slashes.
851       (concat dir (nnheader-replace-chars-in-string group ?. ?/)))))
852
853 (defun nnfolder-save-buffer ()
854   "Save the buffer."
855   (when (buffer-modified-p)
856     (run-hooks 'nnfolder-save-buffer-hook)
857     (gnus-make-directory (file-name-directory (buffer-file-name)))
858     (let* ((coding-system-for-write
859             (or nnfolder-file-coding-system-for-write
860                 nnfolder-file-coding-system))
861            (output-coding-system coding-system-for-write))
862       (save-buffer))))
863
864 (defun nnfolder-save-active (group-alist active-file)
865   (let ((nnmail-active-file-coding-system
866          (or nnfolder-active-file-coding-system-for-write
867              nnfolder-active-file-coding-system)))
868     (nnmail-save-active group-alist active-file)))
869
870 (provide 'nnfolder)
871
872 ;;; nnfolder.el ends here