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