See ChangeLog for the log entries
[gnus] / 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             (search-forward (concat "\n" nnfolder-article-marker))
188             (cons nnfolder-current-group
189                   (string-to-int
190                    (buffer-substring
191                     (point) (progn (end-of-line) (point)))))))))))
192
193 (deffoo nnfolder-request-group (group &optional server dont-check)
194   (nnfolder-possibly-change-group group server t)
195   (save-excursion
196     (if (not (assoc group nnfolder-group-alist))
197         (nnheader-report 'nnfolder "No such group: %s" group)
198       (if dont-check
199           (progn
200             (nnheader-report 'nnfolder "Selected group %s" group)
201             t)
202         (let* ((active (assoc group nnfolder-group-alist))
203                (group (car active))
204                (range (cadr active)))
205           (cond
206            ((null active)
207             (nnheader-report 'nnfolder "No such group: %s" group))
208            ((null nnfolder-current-group)
209             (nnheader-report 'nnfolder "Empty group: %s" group))
210            (t
211             (nnheader-report 'nnfolder "Selected group %s" group)
212             (nnheader-insert "211 %d %d %d %s\n"
213                              (1+ (- (cdr range) (car range)))
214                              (car range) (cdr range) group))))))))
215
216 (deffoo nnfolder-request-scan (&optional group server)
217   (nnfolder-possibly-change-group nil server)
218   (when nnfolder-get-new-mail
219     (nnfolder-possibly-change-group group server)
220     (nnmail-get-new-mail
221      'nnfolder
222      (lambda ()
223        (let ((bufs nnfolder-buffer-alist))
224          (save-excursion
225            (while bufs
226              (if (not (gnus-buffer-live-p (nth 1 (car bufs))))
227                  (setq nnfolder-buffer-alist
228                        (delq (car bufs) nnfolder-buffer-alist))
229                (set-buffer (nth 1 (car bufs)))
230                (nnfolder-save-buffer)
231                (kill-buffer (current-buffer)))
232              (setq bufs (cdr bufs))))))
233      nnfolder-directory
234      group)))
235
236 ;; Don't close the buffer if we're not shutting down the server.  This way,
237 ;; we can keep the buffer in the group buffer cache, and not have to grovel
238 ;; over the buffer again unless we add new mail to it or modify it in some
239 ;; way.
240
241 (deffoo nnfolder-close-group (group &optional server force)
242   ;; Make sure we _had_ the group open.
243   (when (or (assoc group nnfolder-buffer-alist)
244             (equal group nnfolder-current-group))
245     (let ((inf (assoc group nnfolder-buffer-alist)))
246       (when inf
247         (when (and nnfolder-current-group
248                    nnfolder-current-buffer)
249           (push (list nnfolder-current-group nnfolder-current-buffer)
250                 nnfolder-buffer-alist))
251         (setq nnfolder-buffer-alist
252               (delq inf nnfolder-buffer-alist))
253         (setq nnfolder-current-buffer (cadr inf)
254               nnfolder-current-group (car inf))))
255     (when (and nnfolder-current-buffer
256                (buffer-name nnfolder-current-buffer))
257       (save-excursion
258         (set-buffer nnfolder-current-buffer)
259         ;; If the buffer was modified, write the file out now.
260         (nnfolder-save-buffer)
261         ;; If we're shutting the server down, we need to kill the
262         ;; buffer and remove it from the open buffer list.  Or, of
263         ;; course, if we're trying to minimize our space impact.
264         (kill-buffer (current-buffer))
265         (setq nnfolder-buffer-alist (delq (assoc group nnfolder-buffer-alist)
266                                           nnfolder-buffer-alist)))))
267   (setq nnfolder-current-group nil
268         nnfolder-current-buffer nil)
269   t)
270
271 (deffoo nnfolder-request-create-group (group &optional server args)
272   (nnfolder-possibly-change-group nil server)
273   (nnmail-activate 'nnfolder)
274   (when group
275     (unless (assoc group nnfolder-group-alist)
276       (push (list group (cons 1 0)) nnfolder-group-alist)
277       (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
278       (nnfolder-read-folder group)))
279   t)
280
281 (deffoo nnfolder-request-list (&optional server)
282   (nnfolder-possibly-change-group nil server)
283   (save-excursion
284     (let ((nnmail-file-coding-system nnfolder-active-file-coding-system))
285       (nnmail-find-file nnfolder-active-file)
286       (setq nnfolder-group-alist (nnmail-get-active)))
287     t))
288
289 (deffoo nnfolder-request-newgroups (date &optional server)
290   (nnfolder-possibly-change-group nil server)
291   (nnfolder-request-list server))
292
293 (deffoo nnfolder-request-list-newsgroups (&optional server)
294   (nnfolder-possibly-change-group nil server)
295   (save-excursion
296     (let ((nnmail-file-coding-system nnfolder-file-coding-system))
297       (nnmail-find-file nnfolder-newsgroups-file))))
298
299 ;; Return a list consisting of all article numbers existing in the
300 ;; current folder.
301
302 (defun nnfolder-existing-articles ()
303   (save-excursion
304     (when nnfolder-current-buffer
305       (set-buffer nnfolder-current-buffer)
306       (goto-char (point-min))
307       (let ((marker (concat "\n" nnfolder-article-marker))
308             (number "[0-9]+")
309             numbers)
310       
311         (while (and (search-forward marker nil t)
312                     (re-search-forward number nil t))
313           (let ((newnum (string-to-number (match-string 0))))
314             (if (nnmail-within-headers-p)
315                 (push newnum numbers))))
316         numbers))))
317
318 (deffoo nnfolder-request-expire-articles
319   (articles newsgroup &optional server force)
320   (nnfolder-possibly-change-group newsgroup server)
321   (let* ((is-old t)
322          ;; The articles we have deleted so far.
323          (deleted-articles nil)
324          ;; The articles that really exist and will
325          ;; be expired if they are old enough.
326          (maybe-expirable
327           (gnus-intersection articles (nnfolder-existing-articles))))
328     (nnmail-activate 'nnfolder)
329
330     (save-excursion
331       (set-buffer nnfolder-current-buffer)
332       ;; Since messages are sorted in arrival order and expired in the
333       ;; same order, we can stop as soon as we find a message that is
334       ;; too old.
335       (while (and maybe-expirable is-old)
336         (goto-char (point-min))
337         (when (and (nnfolder-goto-article (car maybe-expirable))
338                    (search-forward (concat "\n" nnfolder-article-marker)
339                                    nil t))
340           (forward-sexp)
341           (when (setq is-old
342                     (nnmail-expired-article-p
343                      newsgroup
344                      (buffer-substring
345                       (point) (progn (end-of-line) (point)))
346                      force nnfolder-inhibit-expiry))
347                 (nnheader-message 5 "Deleting article %d..."
348                               (car maybe-expirable) newsgroup)
349             (nnfolder-delete-mail)
350             ;; Must remember which articles were actually deleted
351             (push (car maybe-expirable) deleted-articles)))
352         (setq maybe-expirable (cdr maybe-expirable)))
353       (unless nnfolder-inhibit-expiry
354         (nnheader-message 5 "Deleting articles...done"))
355       (nnfolder-save-buffer)
356       (nnfolder-adjust-min-active newsgroup)
357       (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
358       (gnus-sorted-complement articles (nreverse deleted-articles)))))
359
360 (deffoo nnfolder-request-move-article (article group server
361                                                accept-form &optional last)
362   (save-excursion
363     (let ((buf (get-buffer-create " *nnfolder move*"))
364           result)
365       (and
366        (nnfolder-request-article article group server)
367        (save-excursion
368          (set-buffer buf)
369          (erase-buffer)
370          (insert-buffer-substring nntp-server-buffer)
371          (goto-char (point-min))
372          (while (re-search-forward
373                  (concat "^" nnfolder-article-marker)
374                  (save-excursion (and (search-forward "\n\n" nil t) (point))) 
375                  t)
376            (delete-region (progn (beginning-of-line) (point))
377                           (progn (forward-line 1) (point))))
378          (setq result (eval accept-form))
379          (kill-buffer buf)
380          result)
381        (save-excursion
382          (nnfolder-possibly-change-group group server)
383          (set-buffer nnfolder-current-buffer)
384          (goto-char (point-min))
385          (when (nnfolder-goto-article article)
386            (nnfolder-delete-mail))
387          (when last
388            (nnfolder-save-buffer)
389            (nnfolder-adjust-min-active group)
390            (nnfolder-save-active nnfolder-group-alist nnfolder-active-file))))
391       result)))
392
393 (deffoo nnfolder-request-accept-article (group &optional server last)
394   (save-excursion
395     (nnfolder-possibly-change-group group server)
396     (nnmail-check-syntax)
397     (let ((buf (current-buffer))
398           result art-group)
399       (goto-char (point-min))
400       (when (looking-at "X-From-Line: ")
401         (replace-match "From "))
402       (and
403        (nnfolder-request-list)
404        (save-excursion
405          (set-buffer buf)
406          (goto-char (point-min))
407          (if (search-forward "\n\n" nil t)
408              (forward-line -1)
409            (goto-char (point-max)))
410          (while (re-search-backward (concat "^" nnfolder-article-marker) nil t)
411            (delete-region (point) (progn (forward-line 1) (point))))
412          (when nnmail-cache-accepted-message-ids
413            (nnmail-cache-insert (nnmail-fetch-field "message-id")))
414          (setq result (if (stringp group)
415                           (list (cons group (nnfolder-active-number group)))
416                         (setq art-group
417                               (nnmail-article-group 'nnfolder-active-number))))
418          (if (and (null result)
419                   (yes-or-no-p "Moved to `junk' group; delete article? "))
420              (setq result 'junk)
421            (setq result
422                  (car (nnfolder-save-mail result)))))
423        (when last
424          (save-excursion
425            (nnfolder-possibly-change-folder (or (caar art-group) group))
426            (nnfolder-save-buffer)
427            (when nnmail-cache-accepted-message-ids
428              (nnmail-cache-close)))))
429       (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
430       (unless result
431         (nnheader-report 'nnfolder "Couldn't store article"))
432       result)))
433
434 (deffoo nnfolder-request-replace-article (article group buffer)
435   (nnfolder-possibly-change-group group)
436   (save-excursion
437     (set-buffer buffer)
438     (goto-char (point-min))
439     (let (xfrom)
440       (while (re-search-forward "^X-From-Line: \\(.*\\)$" nil t)
441         (setq xfrom (match-string 1))
442         (gnus-delete-line))
443       (goto-char (point-min))
444       (if xfrom
445           (insert "From " xfrom "\n")
446         (unless (looking-at "From ")
447           (insert "From nobody " (current-time-string) "\n"))))
448     (nnfolder-normalize-buffer)
449     (set-buffer nnfolder-current-buffer)
450     (goto-char (point-min))
451     (if (not (nnfolder-goto-article article))
452         nil
453       (nnfolder-delete-mail)
454       (insert-buffer-substring buffer)
455       (nnfolder-save-buffer)
456       t)))
457
458 (deffoo nnfolder-request-delete-group (group &optional force server)
459   (nnfolder-close-group group server t)
460   ;; Delete all articles in GROUP.
461   (if (not force)
462       ()                                ; Don't delete the articles.
463     ;; Delete the file that holds the group.
464     (ignore-errors
465       (delete-file (nnfolder-group-pathname group))))
466   ;; Remove the group from all structures.
467   (setq nnfolder-group-alist
468         (delq (assoc group nnfolder-group-alist) nnfolder-group-alist)
469         nnfolder-current-group nil
470         nnfolder-current-buffer nil)
471   ;; Save the active file.
472   (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
473   t)
474
475 (deffoo nnfolder-request-rename-group (group new-name &optional server)
476   (nnfolder-possibly-change-group group server)
477   (save-excursion
478     (set-buffer nnfolder-current-buffer)
479     (and (file-writable-p buffer-file-name)
480          (ignore-errors
481            (rename-file
482             buffer-file-name
483             (let ((new-file (nnfolder-group-pathname new-name)))
484               (gnus-make-directory (file-name-directory new-file))
485               new-file))
486            t)
487          ;; That went ok, so we change the internal structures.
488          (let ((entry (assoc group nnfolder-group-alist)))
489            (and entry (setcar entry new-name))
490            (setq nnfolder-current-buffer nil
491                  nnfolder-current-group nil)
492            ;; Save the new group alist.
493            (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
494            ;; We kill the buffer instead of renaming it and stuff.
495            (kill-buffer (current-buffer))
496            t))))
497
498 (defun nnfolder-request-regenerate (server)
499   (nnfolder-possibly-change-group nil server)
500   (nnfolder-generate-active-file)
501   t)
502
503 \f
504 ;;; Internal functions.
505
506 (defun nnfolder-adjust-min-active (group)
507   ;; Find the lowest active article in this group.
508   (let* ((active (cadr (assoc group nnfolder-group-alist)))
509          (marker (concat "\n" nnfolder-article-marker))
510          (number "[0-9]+")
511          (activemin (cdr active)))
512     (save-excursion
513       (set-buffer nnfolder-current-buffer)
514       (goto-char (point-min))
515       (while (and (search-forward marker nil t)
516                   (re-search-forward number nil t))
517         (let ((newnum (string-to-number (match-string 0))))
518           (if (nnmail-within-headers-p)
519               (setq activemin (min activemin newnum)))))
520       (setcar active activemin))))
521
522 (defun nnfolder-article-string (article)
523   (if (numberp article)
524       (concat "\n" nnfolder-article-marker (int-to-string article) " ")
525     (concat "\nMessage-ID: " article)))
526
527 (defun nnfolder-goto-article (article)
528   "Place point at the start of the headers of ARTICLE.
529 ARTICLE can be an article number or a Message-ID.
530 Returns t if successful, nil otherwise."
531   (let ((art-string (nnfolder-article-string article))
532         start found)
533     ;; It is likely that we are at or before the delimiter line.
534     ;; We therefore go to the end of the previous line, and start
535     ;; searching from there.
536     (beginning-of-line)
537     (unless (bobp)
538       (forward-char -1))
539     (setq start (point))
540     ;; First search forward.
541     (while (and (setq found (search-forward art-string nil t))
542                 (not (nnmail-within-headers-p))))
543     ;; If unsuccessful, search backward from where we started,
544     (unless found
545       (goto-char start)
546       (while (and (setq found (search-backward art-string nil t))
547                   (not (nnmail-within-headers-p)))))
548     (when found
549       (nnmail-search-unix-mail-delim-backward))))
550
551 (defun nnfolder-delete-mail (&optional leave-delim)
552   "Delete the message that point is in.
553 If optional argument LEAVE-DELIM is t, then mailbox delimiter is not
554 deleted.  Point is left where the deleted region was."
555   (save-restriction
556     (narrow-to-region
557      (save-excursion
558        ;; In case point is at the beginning of the message already.
559        (forward-line 1)
560        (nnmail-search-unix-mail-delim-backward)
561        (if leave-delim (progn (forward-line 1) (point))
562          (point)))
563      (progn
564        (forward-line 1)
565        (if (nnmail-search-unix-mail-delim)
566            (point)
567          (point-max))))
568     (run-hooks 'nnfolder-delete-mail-hook)
569     (delete-region (point-min) (point-max))))
570
571 (defun nnfolder-possibly-change-group (group &optional server dont-check)
572   ;; Change servers.
573   (when (and server
574              (not (nnfolder-server-opened server)))
575     (nnfolder-open-server server))
576   (unless (gnus-buffer-live-p nnfolder-current-buffer)
577     (setq nnfolder-current-buffer nil
578           nnfolder-current-group nil))
579   ;; Change group.
580   (when (and group
581              (not (equal group nnfolder-current-group)))
582     (let ((pathname-coding-system nnmail-pathname-coding-system))
583       (nnmail-activate 'nnfolder)
584       (when (and (not (assoc group nnfolder-group-alist))
585                  (not (file-exists-p
586                        (nnfolder-group-pathname group))))
587         ;; The group doesn't exist, so we create a new entry for it.
588         (push (list group (cons 1 0)) nnfolder-group-alist)
589         (nnfolder-save-active nnfolder-group-alist nnfolder-active-file))
590
591       (if dont-check
592           (setq nnfolder-current-group group
593                 nnfolder-current-buffer nil)
594         (let (inf file)
595           ;; If we have to change groups, see if we don't already have the
596           ;; folder in memory.  If we do, verify the modtime and destroy
597           ;; the folder if needed so we can rescan it.
598           (setq nnfolder-current-buffer
599                 (nth 1 (assoc group nnfolder-buffer-alist)))
600
601           ;; If the buffer is not live, make sure it isn't in the alist.  If it
602           ;; is live, verify that nobody else has touched the file since last
603           ;; time.
604           (when (and nnfolder-current-buffer
605                      (not (gnus-buffer-live-p nnfolder-current-buffer)))
606             (setq nnfolder-buffer-alist (delq inf nnfolder-buffer-alist)
607                   nnfolder-current-buffer nil))
608
609           (setq nnfolder-current-group group)
610
611           (when (or (not nnfolder-current-buffer)
612                     (not (verify-visited-file-modtime
613                           nnfolder-current-buffer)))
614             (save-excursion
615               (setq file (nnfolder-group-pathname group))
616               ;; See whether we need to create the new file.
617               (unless (file-exists-p file)
618                 (gnus-make-directory (file-name-directory file))
619                 (let ((nnmail-file-coding-system 
620                        (or nnfolder-file-coding-system-for-write
621                            nnfolder-file-coding-system-for-write)))
622                   (nnmail-write-region 1 1 file t 'nomesg)))
623               (when (setq nnfolder-current-buffer (nnfolder-read-folder group))
624                 (set-buffer nnfolder-current-buffer)
625                 (push (list group nnfolder-current-buffer)
626                       nnfolder-buffer-alist)))))))))
627
628 (defun nnfolder-save-mail (group-art-list)
629   "Called narrowed to an article."
630   (let* (save-list group-art)
631     (goto-char (point-min))
632     ;; The From line may have been quoted by movemail.
633     (when (looking-at ">From")
634       (delete-char 1))
635     ;; This might come from somewhere else.
636     (unless (looking-at "From ")
637       (insert "From nobody " (current-time-string) "\n")
638       (goto-char (point-min)))
639     ;; Quote all "From " lines in the article.
640     (forward-line 1)
641     (let (case-fold-search)
642       (while (re-search-forward "^From " nil t)
643         (beginning-of-line)
644         (insert "> ")))
645     (setq save-list group-art-list)
646     (nnmail-insert-lines)
647     (nnmail-insert-xref group-art-list)
648     (run-hooks 'nnmail-prepare-save-mail-hook)
649     (run-hooks 'nnfolder-prepare-save-mail-hook)
650
651     ;; Insert the mail into each of the destination groups.
652     (while (setq group-art (pop group-art-list))
653       ;; Kill any previous newsgroup markers.
654       (goto-char (point-min))
655       (if (search-forward "\n\n" nil t)
656           (forward-line -1)
657         (goto-char (point-max)))
658       (while (search-backward (concat "\n" nnfolder-article-marker) nil t)
659         (delete-region (1+ (point)) (progn (forward-line 2) (point))))
660
661       ;; Insert the new newsgroup marker.
662       (nnfolder-insert-newsgroup-line group-art)
663
664       (save-excursion
665         (let ((beg (point-min))
666               (end (point-max))
667               (obuf (current-buffer)))
668           (nnfolder-possibly-change-folder (car group-art))
669           (let ((buffer-read-only nil))
670             (nnfolder-normalize-buffer)
671             (insert-buffer-substring obuf beg end)))))
672
673     ;; Did we save it anywhere?
674     save-list))
675
676 (defun nnfolder-normalize-buffer ()
677   "Make sure there are two newlines at the end of the buffer."
678   (goto-char (point-max))
679   (skip-chars-backward "\n")
680   (delete-region (point) (point-max))
681   (insert "\n\n"))
682
683 (defun nnfolder-insert-newsgroup-line (group-art)
684   (save-excursion
685     (goto-char (point-min))
686     (unless (search-forward "\n\n" nil t)
687       (goto-char (point-max))
688       (insert "\n"))
689     (forward-char -1)
690     (insert (format (concat nnfolder-article-marker "%d   %s\n")
691                     (cdr group-art) (current-time-string)))))
692
693 (defun nnfolder-active-number (group)
694   ;; Find the next article number in GROUP.
695   (let ((active (cadr (assoc group nnfolder-group-alist))))
696     (if active
697         (setcdr active (1+ (cdr active)))
698       ;; This group is new, so we create a new entry for it.
699       ;; This might be a bit naughty... creating groups on the drop of
700       ;; a hat, but I don't know...
701       (push (list group (setq active (cons 1 1)))
702             nnfolder-group-alist))
703     (cdr active)))
704
705 (defun nnfolder-possibly-change-folder (group)
706   (let ((inf (assoc group nnfolder-buffer-alist)))
707     (if (and inf
708              (gnus-buffer-live-p (cadr inf)))
709         (set-buffer (cadr inf))
710       (when inf
711         (setq nnfolder-buffer-alist (delq inf nnfolder-buffer-alist)))
712       (when nnfolder-group-alist
713         (nnfolder-save-active nnfolder-group-alist nnfolder-active-file))
714       (push (list group (nnfolder-read-folder group))
715             nnfolder-buffer-alist))))
716
717 ;; This method has a problem if you've accidentally let the active list get
718 ;; out of sync with the files.  This could happen, say, if you've
719 ;; accidentally gotten new mail with something other than Gnus (but why
720 ;; would _that_ ever happen? :-).  In that case, we will be in the middle of
721 ;; processing the file, ready to add new X-Gnus article number markers, and
722 ;; we'll run across a message with no ID yet - the active list _may_not_ be
723 ;; ready for us yet.
724
725 ;; To handle this, I'm modifying this routine to maintain the maximum ID seen
726 ;; so far, and when we hit a message with no ID, we will _manually_ scan the
727 ;; rest of the message looking for any more, possibly higher IDs.  We'll
728 ;; assume the maximum that we find is the highest active.  Note that this
729 ;; shouldn't cost us much extra time at all, but will be a lot less
730 ;; vulnerable to glitches between the mbox and the active file.
731
732 (defun nnfolder-read-folder (group)
733   (let* ((file (nnfolder-group-pathname group))
734          (buffer (set-buffer
735                   (let ((nnheader-file-coding-system 
736                          nnfolder-file-coding-system))
737                     (nnheader-find-file-noselect file)))))
738     (if (equal (cadr (assoc group nnfolder-scantime-alist))
739                (nth 5 (file-attributes file)))
740         ;; This looks up-to-date, so we don't do any scanning.
741         (if (file-exists-p file)
742             buffer
743           (push (list group buffer) nnfolder-buffer-alist)
744           (set-buffer-modified-p t)
745           (save-buffer))
746       ;; Parse the damn thing.
747       (save-excursion
748         (goto-char (point-min))
749         ;; Remove any blank lines at the start.
750         (while (eq (following-char) ?\n)
751           (delete-char 1))
752         (nnmail-activate 'nnfolder)
753         ;; Read in the file.
754         (let ((delim "^From ")
755               (marker (concat "\n" nnfolder-article-marker))
756               (number "[0-9]+")
757               (active (or (cadr (assoc group nnfolder-group-alist))
758                           (cons 1 0)))
759               (scantime (assoc group nnfolder-scantime-alist))
760               (minid (lsh -1 -1))
761               maxid start end newscantime
762               buffer-read-only)
763           (buffer-disable-undo)
764           (setq maxid (cdr active))
765           (goto-char (point-min))
766
767           ;; Anytime the active number is 1 or 0, it is suspect.  In that
768           ;; case, search the file manually to find the active number.  Or,
769           ;; of course, if we're being paranoid.  (This would also be the
770           ;; place to build other lists from the header markers, such as
771           ;; expunge lists, etc., if we ever desired to abandon the active
772           ;; file entirely for mboxes.)
773           (when (or nnfolder-ignore-active-file
774                     (< maxid 2))
775             (while (and (search-forward marker nil t)
776                         (re-search-forward number nil t))
777               (let ((newnum (string-to-number (match-string 0))))
778                 (if (nnmail-within-headers-p)
779                     (setq maxid (max maxid newnum)
780                           minid (min minid newnum)))))
781             (setcar active (max 1 (min minid maxid)))
782             (setcdr active (max maxid (cdr active)))
783             (goto-char (point-min)))
784
785           ;; As long as we trust that the user will only insert unmarked mail
786           ;; at the end, go to the end and search backwards for the last
787           ;; marker.  Find the start of that message, and begin to search for
788           ;; unmarked messages from there.
789           (when (not (or nnfolder-distrust-mbox
790                          (< maxid 2)))
791             (goto-char (point-max))
792             (unless (re-search-backward marker nil t)
793               (goto-char (point-min)))
794             (when (nnmail-search-unix-mail-delim)
795               (goto-char (point-min))))
796
797           ;; Keep track of the active number on our own, and insert it back
798           ;; into the active list when we're done.  Also, prime the pump to
799           ;; cut down on the number of searches we do.
800           (unless (nnmail-search-unix-mail-delim)
801             (goto-char (point-max)))
802           (setq end (point-marker))
803           (while (not (= end (point-max)))
804             (setq start (marker-position end))
805             (goto-char end)
806             ;; There may be more than one "From " line, so we skip past
807             ;; them.
808             (while (looking-at delim)
809               (forward-line 1))
810             (set-marker end (if (nnmail-search-unix-mail-delim)
811                                 (point)
812                               (point-max)))
813             (goto-char start)
814             (when (not (search-forward marker end t))
815               (narrow-to-region start end)
816               (nnmail-insert-lines)
817               (nnfolder-insert-newsgroup-line
818                (cons nil (nnfolder-active-number nnfolder-current-group)))
819               (widen)))
820
821           (set-marker end nil)
822           ;; Make absolutely sure that the active list reflects reality!
823           (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
824           ;; Set the scantime for this group.
825           (setq newscantime (visited-file-modtime))
826           (if scantime
827               (setcdr scantime (list newscantime))
828             (push (list nnfolder-current-group newscantime)
829                   nnfolder-scantime-alist))
830           (current-buffer))))))
831
832 ;;;###autoload
833 (defun nnfolder-generate-active-file ()
834   "Look for mbox folders in the nnfolder directory and make them into groups.
835 This command does not work if you use short group names."
836   (interactive)
837   (nnmail-activate 'nnfolder)
838   (let ((files (directory-files nnfolder-directory))
839         file)
840     (while (setq file (pop files))
841       (when (and (not (backup-file-name-p file))
842                  (message-mail-file-mbox-p
843                   (nnheader-concat nnfolder-directory file)))
844         (let ((oldgroup (assoc file nnfolder-group-alist)))
845           (if oldgroup
846               (nnheader-message 5 "Refreshing group %s..." file)
847             (nnheader-message 5 "Adding group %s..." file))
848           (if oldgroup
849               (setq nnfolder-group-alist
850                     (delq oldgroup (copy-sequence nnfolder-group-alist))))
851           (push (list file (cons 1 0)) nnfolder-group-alist)
852           (nnfolder-possibly-change-folder file)
853           (nnfolder-possibly-change-group file)
854           (nnfolder-close-group file))))
855     (nnheader-message 5 "")))
856
857 (defun nnfolder-group-pathname (group)
858   "Make pathname for GROUP."
859   (setq group
860         (mm-encode-coding-string group nnmail-pathname-coding-system))
861   (let ((dir (file-name-as-directory (expand-file-name nnfolder-directory))))
862     ;; If this file exists, we use it directly.
863     (if (or nnmail-use-long-file-names
864             (file-exists-p (concat dir group)))
865         (concat dir group)
866       ;; If not, we translate dots into slashes.
867       (concat dir (nnheader-replace-chars-in-string group ?. ?/)))))
868
869 (defun nnfolder-save-buffer ()
870   "Save the buffer."
871   (when (buffer-modified-p)
872     (run-hooks 'nnfolder-save-buffer-hook)
873     (gnus-make-directory (file-name-directory (buffer-file-name)))
874     (let ((coding-system-for-write 
875            (or nnfolder-file-coding-system-for-write
876                nnfolder-file-coding-system)))
877       (save-buffer))))
878
879 (defun nnfolder-save-active (group-alist active-file)
880   (let ((nnmail-active-file-coding-system
881          (or nnfolder-active-file-coding-system-for-write
882              nnfolder-active-file-coding-system)))
883     (nnmail-save-active group-alist active-file)))
884
885 (provide 'nnfolder)
886
887 ;;; nnfolder.el ends here