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