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