Synch with Oort Gnus.
[elisp/gnus.git-] / lisp / nnml.el
1 ;;; nnml.el --- mail spool access for Gnus
2 ;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Simon Josefsson <simon@josefsson.org> (adding MARKS)
6 ;;      Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;;      Masanobu UMEDA <umerin@flab.flab.fujitsu.junet>
8 ;; Keywords: news, mail
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26
27 ;;; Commentary:
28
29 ;; Based on nnspool.el by Masanobu UMEDA <umerin@flab.flab.fujitsu.junet>.
30 ;; For an overview of what the interface functions do, please see the
31 ;; Gnus sources.
32
33 ;;; Code:
34
35 (eval-when-compile (require 'cl))
36 (eval-when-compile (require 'gnus-clfns))
37
38 (require 'gnus)
39 (require 'nnheader)
40 (require 'nnmail)
41 (require 'nnoo)
42
43 (eval-and-compile
44   (autoload 'gnus-article-unpropagatable-p "gnus-sum"))
45
46 (nnoo-declare nnml)
47
48 (defvoo nnml-directory message-directory
49   "Spool directory for the nnml mail backend.
50
51 This variable is a virtual server slot.  See the Gnus manual for details.")
52
53 (defvoo nnml-active-file
54     (expand-file-name "active" nnml-directory)
55   "Mail active file.
56
57 This variable is a virtual server slot.  See the Gnus manual for details.")
58
59 (defvoo nnml-newsgroups-file
60     (expand-file-name "newsgroups" nnml-directory)
61   "Mail newsgroups description file.
62
63 This variable is a virtual server slot.  See the Gnus manual for details.")
64
65 (defvoo nnml-get-new-mail t
66   "If non-nil, nnml will check the incoming mail file and split the mail.
67
68 This variable is a virtual server slot.  See the Gnus manual for details.")
69
70 (defvoo nnml-nov-is-evil nil
71   "If non-nil, Gnus will never generate and use nov databases for mail spools.
72 Using nov databases will speed up header fetching considerably.
73 This variable shouldn't be flipped much.  If you have, for some reason,
74 set this to t, and want to set it to nil again, you should always run
75 the `nnml-generate-nov-databases' command.  The function will go
76 through all nnml directories and generate nov databases for them
77 all.  This may very well take some time.
78
79 This variable is a virtual server slot.  See the Gnus manual for details.")
80
81 (defvoo nnml-marks-is-evil nil
82   "If non-nil, Gnus will never generate and use marks file for mail spools.
83 Using marks files makes it possible to backup and restore mail groups
84 separately from `.newsrc.eld'.  If you have, for some reason, set this
85 to t, and want to set it to nil again, you should always remove the
86 corresponding marks file (usually named `.marks' in the nnml group
87 directory, but see `nnml-marks-file-name') for the group.  Then the
88 marks file will be regenerated properly by Gnus.
89
90 This variable is a virtual server slot.  See the Gnus manual for details.")
91
92 (defvoo nnml-filenames-are-evil t
93   "If non-nil, Gnus will not assume that the articles file name
94 is the same as the article number listed in the nov database.  This
95 variable should be set if any of the files are compressed.
96
97 This variable is a virtual server slot.  See the Gnus manual for details.")
98
99 (defvoo nnml-prepare-save-mail-hook nil
100   "Hook run narrowed to an article before saving.
101
102 This variable is a virtual server slot.  See the Gnus manual for details.")
103
104 (defvoo nnml-inhibit-expiry nil
105   "If non-nil, inhibit expiry.
106
107 This variable is a virtual server slot.  See the Gnus manual for details.")
108
109
110 \f
111
112 (defconst nnml-version "nnml 1.0"
113   "nnml version.")
114
115 (defvoo nnml-nov-file-name ".overview")
116 (defvoo nnml-marks-file-name ".marks")
117
118 (defvoo nnml-current-directory nil)
119 (defvoo nnml-current-group nil)
120 (defvoo nnml-status-string "")
121 (defvoo nnml-nov-buffer-alist nil)
122 (defvoo nnml-group-alist nil)
123 (defvoo nnml-active-timestamp nil)
124 (defvoo nnml-article-file-alist nil)
125
126 (defvoo nnml-generate-active-function 'nnml-generate-active-info)
127
128 (defvar nnml-nov-buffer-file-name nil)
129
130 (defvoo nnml-file-coding-system nnmail-file-coding-system)
131
132 (defvoo nnml-marks nil)
133
134 (defvar nnml-marks-modtime (gnus-make-hashtable))
135
136 \f
137 ;;; Interface functions.
138
139 (nnoo-define-basics nnml)
140
141 (deffoo nnml-retrieve-headers (sequence &optional group server fetch-old)
142   (when (nnml-possibly-change-directory group server)
143     (save-excursion
144       (set-buffer nntp-server-buffer)
145       (erase-buffer)
146       (let* ((file nil)
147              (number (length sequence))
148              (count 0)
149              (file-name-coding-system nnmail-pathname-coding-system)
150              (pathname-coding-system nnmail-pathname-coding-system)
151              beg article)
152         (if (stringp (car sequence))
153             'headers
154           (if (nnml-retrieve-headers-with-nov sequence fetch-old)
155               'nov
156             (while sequence
157               (setq article (car sequence))
158               (setq file (nnml-article-to-file article))
159               (when (and file
160                          (file-exists-p file)
161                          (not (file-directory-p file)))
162                 (insert (format "221 %d Article retrieved.\n" article))
163                 (setq beg (point))
164                 (nnheader-insert-head file)
165                 (goto-char beg)
166                 (if (re-search-forward "\n\r?\n" nil t)
167                     (forward-char -1)
168                   (goto-char (point-max))
169                   (insert "\n\n"))
170                 (insert ".\n")
171                 (delete-region (point) (point-max)))
172               (setq sequence (cdr sequence))
173               (setq count (1+ count))
174               (and (numberp nnmail-large-newsgroup)
175                    (> number nnmail-large-newsgroup)
176                    (zerop (% count 20))
177                    (nnheader-message 6 "nnml: Receiving headers... %d%%"
178                                      (/ (* count 100) number))))
179
180             (and (numberp nnmail-large-newsgroup)
181                  (> number nnmail-large-newsgroup)
182                  (nnheader-message 6 "nnml: Receiving headers...done"))
183
184             (nnheader-fold-continuation-lines)
185             'headers))))))
186
187 (deffoo nnml-open-server (server &optional defs)
188   (nnoo-change-server 'nnml server defs)
189   (when (not (file-exists-p nnml-directory))
190     (ignore-errors (make-directory nnml-directory t)))
191   (cond
192    ((not (file-exists-p nnml-directory))
193     (nnml-close-server)
194     (nnheader-report 'nnml "Couldn't create directory: %s" nnml-directory))
195    ((not (file-directory-p (file-truename nnml-directory)))
196     (nnml-close-server)
197     (nnheader-report 'nnml "Not a directory: %s" nnml-directory))
198    (t
199     (nnheader-report 'nnml "Opened server %s using directory %s"
200                      server nnml-directory)
201     t)))
202
203 (deffoo nnml-request-regenerate (server)
204   (nnml-possibly-change-directory nil server)
205   (nnml-generate-nov-databases server)
206   t)
207
208 (deffoo nnml-request-article (id &optional group server buffer)
209   (nnml-possibly-change-directory group server)
210   (let* ((nntp-server-buffer (or buffer nntp-server-buffer))
211          (file-name-coding-system nnmail-pathname-coding-system)
212          (pathname-coding-system nnmail-pathname-coding-system)
213          path gpath group-num)
214     (if (stringp id)
215         (when (and (setq group-num (nnml-find-group-number id))
216                    (cdr
217                     (assq (cdr group-num)
218                           (nnheader-article-to-file-alist
219                            (setq gpath
220                                  (nnmail-group-pathname
221                                   (car group-num)
222                                   nnml-directory))))))
223           (setq path (concat gpath (int-to-string (cdr group-num)))))
224       (setq path (nnml-article-to-file id)))
225     (cond
226      ((not path)
227       (nnheader-report 'nnml "No such article: %s" id))
228      ((not (file-exists-p path))
229       (nnheader-report 'nnml "No such file: %s" path))
230      ((file-directory-p path)
231       (nnheader-report 'nnml "File is a directory: %s" path))
232      ((not (save-excursion (let ((nnmail-file-coding-system
233                                   nnml-file-coding-system))
234                              (nnmail-find-file path))))
235       (nnheader-report 'nnml "Couldn't read file: %s" path))
236      (t
237       (nnheader-report 'nnml "Article %s retrieved" id)
238       ;; We return the article number.
239       (cons (if group-num (car group-num) group)
240             (string-to-int (file-name-nondirectory path)))))))
241
242 (deffoo nnml-request-group (group &optional server dont-check)
243   (let ((file-name-coding-system nnmail-pathname-coding-system)
244         (pathname-coding-system nnmail-pathname-coding-system))
245     (cond
246      ((not (nnml-possibly-change-directory group server))
247       (nnheader-report 'nnml "Invalid group (no such directory)"))
248      ((not (file-exists-p nnml-current-directory))
249       (nnheader-report 'nnml "Directory %s does not exist"
250                        nnml-current-directory))
251      ((not (file-directory-p nnml-current-directory))
252       (nnheader-report 'nnml "%s is not a directory" nnml-current-directory))
253      (dont-check
254       (nnheader-report 'nnml "Group %s selected" group)
255       t)
256      (t
257       (nnheader-re-read-dir nnml-current-directory)
258       (nnmail-activate 'nnml)
259       (let ((active (nth 1 (assoc group nnml-group-alist))))
260         (if (not active)
261             (nnheader-report 'nnml "No such group: %s" group)
262           (nnheader-report 'nnml "Selected group %s" group)
263           (nnheader-insert "211 %d %d %d %s\n"
264                            (max (1+ (- (cdr active) (car active))) 0)
265                            (car active) (cdr active) group)))))))
266
267 (deffoo nnml-request-scan (&optional group server)
268   (setq nnml-article-file-alist nil)
269   (nnml-possibly-change-directory group server)
270   (nnmail-get-new-mail 'nnml 'nnml-save-nov nnml-directory group))
271
272 (deffoo nnml-close-group (group &optional server)
273   (setq nnml-article-file-alist nil)
274   t)
275
276 (deffoo nnml-request-create-group (group &optional server args)
277   (nnml-possibly-change-directory nil server)
278   (nnmail-activate 'nnml)
279   (cond
280    ((assoc group nnml-group-alist)
281     t)
282    ((and (file-exists-p (nnmail-group-pathname group nnml-directory))
283          (not (file-directory-p (nnmail-group-pathname group nnml-directory))))
284     (nnheader-report 'nnml "%s is a file"
285                      (nnmail-group-pathname group nnml-directory)))
286    (t
287     (let (active)
288       (push (list group (setq active (cons 1 0)))
289             nnml-group-alist)
290       (nnml-possibly-create-directory group)
291       (nnml-possibly-change-directory group server)
292       (let ((articles (nnml-directory-articles nnml-current-directory)))
293         (when articles
294           (setcar active (apply 'min articles))
295           (setcdr active (apply 'max articles))))
296       (nnmail-save-active nnml-group-alist nnml-active-file)
297       t))))
298
299 (deffoo nnml-request-list (&optional server)
300   (save-excursion
301     (let ((nnmail-file-coding-system nnmail-active-file-coding-system)
302           (file-name-coding-system nnmail-pathname-coding-system)
303           (pathname-coding-system nnmail-pathname-coding-system))
304       (nnmail-find-file nnml-active-file))
305     (setq nnml-group-alist (nnmail-get-active))
306     t))
307
308 (deffoo nnml-request-newgroups (date &optional server)
309   (nnml-request-list server))
310
311 (deffoo nnml-request-list-newsgroups (&optional server)
312   (save-excursion
313     (nnmail-find-file nnml-newsgroups-file)))
314
315 (deffoo nnml-request-expire-articles (articles group &optional server force)
316   (nnml-possibly-change-directory group server)
317   (let ((active-articles
318          (nnml-directory-articles nnml-current-directory))
319         (is-old t)
320         article rest mod-time number)
321     (nnmail-activate 'nnml)
322
323     (setq active-articles (sort active-articles '<))
324     ;; Articles not listed in active-articles are already gone,
325     ;; so don't try to expire them.
326     (setq articles (gnus-sorted-intersection articles active-articles))
327
328     (while (and articles is-old)
329       (if (and (setq article (nnml-article-to-file (setq number (pop articles))))
330                (setq mod-time (nth 5 (file-attributes article)))
331                (nnml-deletable-article-p group number)
332                (setq is-old (nnmail-expired-article-p group mod-time force
333                                                       nnml-inhibit-expiry)))
334           (progn
335             ;; Allow a special target group.
336             (unless (eq nnmail-expiry-target 'delete)
337               (with-temp-buffer
338                 (nnml-request-article number group server (current-buffer))
339                 (let (nnml-current-directory
340                       nnml-current-group
341                       nnml-article-file-alist)
342                   (nnmail-expiry-target-group nnmail-expiry-target group)))
343               ;; Maybe directory is changed during nnmail-expiry-target-group.
344               (nnml-possibly-change-directory group server))
345             (nnheader-message 5 "Deleting article %s in %s"
346                               number group)
347             (condition-case ()
348                 (funcall nnmail-delete-file-function article)
349               (file-error
350                (push number rest)))
351             (setq active-articles (delq number active-articles))
352             (nnml-nov-delete-article group number))
353         (push number rest)))
354     (let ((active (nth 1 (assoc group nnml-group-alist))))
355       (when active
356         (setcar active (or (and active-articles
357                                 (apply 'min active-articles))
358                            (1+ (cdr active)))))
359       (nnmail-save-active nnml-group-alist nnml-active-file))
360     (nnml-save-nov)
361     (nconc rest articles)))
362
363 (deffoo nnml-request-move-article
364     (article group server accept-form &optional last)
365   (let ((buf (get-buffer-create " *nnml move*"))
366         result)
367     (nnml-possibly-change-directory group server)
368     (nnml-update-file-alist)
369     (and
370      (nnml-deletable-article-p group article)
371      (nnml-request-article article group server)
372      (let (nnml-current-directory
373            nnml-current-group
374            nnml-article-file-alist)
375        (save-excursion
376          (set-buffer buf)
377          (insert-buffer-substring nntp-server-buffer)
378          (setq result (eval accept-form))
379          (kill-buffer (current-buffer))
380          result))
381      (progn
382        (nnml-possibly-change-directory group server)
383        (condition-case ()
384            (funcall nnmail-delete-file-function
385                     (nnml-article-to-file  article))
386          (file-error nil))
387        (nnml-nov-delete-article group article)
388        (when last
389          (nnml-save-nov)
390          (nnmail-save-active nnml-group-alist nnml-active-file))))
391     result))
392
393 (deffoo nnml-request-accept-article (group &optional server last)
394   (nnml-possibly-change-directory group server)
395   (nnmail-check-syntax)
396   (let (result)
397     (when nnmail-cache-accepted-message-ids
398       (nnmail-cache-insert (nnmail-fetch-field "message-id")))
399     (if (stringp group)
400         (and
401          (nnmail-activate 'nnml)
402          (setq result (car (nnml-save-mail
403                             (list (cons group (nnml-active-number group))))))
404          (progn
405            (nnmail-save-active nnml-group-alist nnml-active-file)
406            (and last (nnml-save-nov))))
407       (and
408        (nnmail-activate 'nnml)
409        (if (and (not (setq result (nnmail-article-group 'nnml-active-number)))
410                 (yes-or-no-p "Moved to `junk' group; delete article? "))
411            (setq result 'junk)
412          (setq result (car (nnml-save-mail result))))
413        (when last
414          (nnmail-save-active nnml-group-alist nnml-active-file)
415          (when nnmail-cache-accepted-message-ids
416            (nnmail-cache-close))
417          (nnml-save-nov))))
418     result))
419
420 (deffoo nnml-request-post (&optional server)
421   (nnmail-do-request-post 'nnml-request-accept-article server))
422
423 (deffoo nnml-request-replace-article (article group buffer)
424   (nnml-possibly-change-directory group)
425   (save-excursion
426     (set-buffer buffer)
427     (nnml-possibly-create-directory group)
428     (let ((chars (nnmail-insert-lines))
429           (art (concat (int-to-string article) "\t"))
430           headers)
431       (when (ignore-errors
432               (nnmail-write-region
433                (point-min) (point-max)
434                (or (nnml-article-to-file article)
435                    (expand-file-name (int-to-string article)
436                                      nnml-current-directory))
437                nil (if (nnheader-be-verbose 5) nil 'nomesg))
438               t)
439         (setq headers (nnml-parse-head chars article))
440         ;; Replace the NOV line in the NOV file.
441         (save-excursion
442           (set-buffer (nnml-open-nov group))
443           (goto-char (point-min))
444           (if (or (looking-at art)
445                   (search-forward (concat "\n" art) nil t))
446               ;; Delete the old NOV line.
447               (delete-region (progn (beginning-of-line) (point))
448                              (progn (forward-line 1) (point)))
449             ;; The line isn't here, so we have to find out where
450             ;; we should insert it.  (This situation should never
451             ;; occur, but one likes to make sure...)
452             (while (and (looking-at "[0-9]+\t")
453                         (< (string-to-int
454                             (buffer-substring
455                              (match-beginning 0) (match-end 0)))
456                            article)
457                         (zerop (forward-line 1)))))
458           (beginning-of-line)
459           (nnheader-insert-nov headers)
460           (nnml-save-nov)
461           t)))))
462
463 (deffoo nnml-request-delete-group (group &optional force server)
464   (nnml-possibly-change-directory group server)
465   (when force
466     ;; Delete all articles in GROUP.
467     (let ((articles
468            (directory-files
469             nnml-current-directory t
470             (concat nnheader-numerical-short-files
471                     "\\|" (regexp-quote nnml-nov-file-name) "$"
472                     "\\|" (regexp-quote nnml-marks-file-name) "$")))
473           article)
474       (while articles
475         (setq article (pop articles))
476         (when (file-writable-p article)
477           (nnheader-message 5 "Deleting article %s in %s..." article group)
478           (funcall nnmail-delete-file-function article))))
479     ;; Try to delete the directory itself.
480     (ignore-errors (delete-directory nnml-current-directory)))
481   ;; Remove the group from all structures.
482   (setq nnml-group-alist
483         (delq (assoc group nnml-group-alist) nnml-group-alist)
484         nnml-current-group nil
485         nnml-current-directory nil)
486   ;; Save the active file.
487   (nnmail-save-active nnml-group-alist nnml-active-file)
488   t)
489
490 (deffoo nnml-request-rename-group (group new-name &optional server)
491   (nnml-possibly-change-directory group server)
492   (let ((new-dir (nnmail-group-pathname new-name nnml-directory))
493         (old-dir (nnmail-group-pathname group nnml-directory)))
494     (when (ignore-errors
495             (make-directory new-dir t)
496             t)
497       ;; We move the articles file by file instead of renaming
498       ;; the directory -- there may be subgroups in this group.
499       ;; One might be more clever, I guess.
500       (let ((files (nnheader-article-to-file-alist old-dir)))
501         (while files
502           (rename-file
503            (concat old-dir (cdar files))
504            (concat new-dir (cdar files)))
505           (pop files)))
506       ;; Move .overview file.
507       (let ((overview (concat old-dir nnml-nov-file-name)))
508         (when (file-exists-p overview)
509           (rename-file overview (concat new-dir nnml-nov-file-name))))
510       ;; Move .marks file.
511       (let ((marks (concat old-dir nnml-marks-file-name)))
512         (when (file-exists-p marks)
513           (rename-file marks (concat new-dir nnml-marks-file-name))))
514       (when (<= (length (directory-files old-dir)) 2)
515         (ignore-errors (delete-directory old-dir)))
516       ;; That went ok, so we change the internal structures.
517       (let ((entry (assoc group nnml-group-alist)))
518         (when entry
519           (setcar entry new-name))
520         (setq nnml-current-directory nil
521               nnml-current-group nil)
522         ;; Save the new group alist.
523         (nnmail-save-active nnml-group-alist nnml-active-file)
524         t))))
525
526 (deffoo nnml-set-status (article name value &optional group server)
527   (nnml-possibly-change-directory group server)
528   (let ((file (nnml-article-to-file article)))
529     (cond
530      ((not (file-exists-p file))
531       (nnheader-report 'nnml "File %s does not exist" file))
532      (t
533       (with-temp-file file
534         (nnheader-insert-file-contents file)
535         (nnmail-replace-status name value))
536       t))))
537
538 \f
539 ;;; Internal functions.
540
541 (defun nnml-article-to-file (article)
542   (nnml-update-file-alist)
543   (let (file)
544     (if (setq file (cdr (assq article nnml-article-file-alist)))
545         (expand-file-name file nnml-current-directory)
546       (if (not nnheader-directory-files-is-safe)
547           ;; Just to make sure nothing went wrong when reading over NFS --
548           ;; check once more.
549           (when (file-exists-p
550                  (setq file (expand-file-name (number-to-string article)
551                                               nnml-current-directory)))
552             (nnml-update-file-alist t)
553             file)))))
554
555 (defun nnml-deletable-article-p (group article)
556   "Say whether ARTICLE in GROUP can be deleted."
557   (let (path)
558     (when (setq path (nnml-article-to-file article))
559       (when (file-writable-p path)
560         (or (not nnmail-keep-last-article)
561             (not (eq (cdr (nth 1 (assoc group nnml-group-alist)))
562                      article)))))))
563
564 ;; Find an article number in the current group given the Message-ID.
565 (defun nnml-find-group-number (id)
566   (save-excursion
567     (set-buffer (get-buffer-create " *nnml id*"))
568     (let ((alist nnml-group-alist)
569           number)
570       ;; We want to look through all .overview files, but we want to
571       ;; start with the one in the current directory.  It seems most
572       ;; likely that the article we are looking for is in that group.
573       (if (setq number (nnml-find-id nnml-current-group id))
574           (cons nnml-current-group number)
575         ;; It wasn't there, so we look through the other groups as well.
576         (while (and (not number)
577                     alist)
578           (or (string= (caar alist) nnml-current-group)
579               (setq number (nnml-find-id (caar alist) id)))
580           (or number
581               (setq alist (cdr alist))))
582         (and number
583              (cons (caar alist) number))))))
584
585 (defun nnml-find-id (group id)
586   (erase-buffer)
587   (let ((nov (expand-file-name nnml-nov-file-name
588                                (nnmail-group-pathname group nnml-directory)))
589         number found)
590     (when (file-exists-p nov)
591       (nnheader-insert-file-contents nov)
592       (while (and (not found)
593                   (search-forward id nil t)) ; We find the ID.
594         ;; And the id is in the fourth field.
595         (if (not (and (search-backward "\t" nil t 4)
596                       (not (search-backward"\t" (gnus-point-at-bol) t))))
597             (forward-line 1)
598           (beginning-of-line)
599           (setq found t)
600           ;; We return the article number.
601           (setq number
602                 (ignore-errors (read (current-buffer))))))
603       number)))
604
605 (defun nnml-retrieve-headers-with-nov (articles &optional fetch-old)
606   (if (or gnus-nov-is-evil nnml-nov-is-evil)
607       nil
608     (let ((nov (expand-file-name nnml-nov-file-name nnml-current-directory)))
609       (when (file-exists-p nov)
610         (save-excursion
611           (set-buffer nntp-server-buffer)
612           (erase-buffer)
613           (nnheader-insert-file-contents nov)
614           (if (and fetch-old
615                    (not (numberp fetch-old)))
616               t                         ; Don't remove anything.
617             (nnheader-nov-delete-outside-range
618              (if fetch-old (max 1 (- (car articles) fetch-old))
619                (car articles))
620              (car (last articles)))
621             t))))))
622
623 (defun nnml-possibly-change-directory (group &optional server)
624   (when (and server
625              (not (nnml-server-opened server)))
626     (nnml-open-server server))
627   (if (not group)
628       t
629     (let ((pathname (nnmail-group-pathname group nnml-directory))
630           (file-name-coding-system nnmail-pathname-coding-system)
631           (pathname-coding-system nnmail-pathname-coding-system))
632       (when (not (equal pathname nnml-current-directory))
633         (setq nnml-current-directory pathname
634               nnml-current-group group
635               nnml-article-file-alist nil))
636       (file-exists-p nnml-current-directory))))
637
638 (defun nnml-possibly-create-directory (group)
639   (let ((dir (nnmail-group-pathname group nnml-directory)))
640     (unless (file-exists-p dir)
641       (make-directory (directory-file-name dir) t)
642       (nnheader-message 5 "Creating mail directory %s" dir))))
643
644 (defun nnml-save-mail (group-art)
645   "Called narrowed to an article."
646   (let (chars headers)
647     (setq chars (nnmail-insert-lines))
648     (nnmail-insert-xref group-art)
649     (run-hooks 'nnmail-prepare-save-mail-hook)
650     (run-hooks 'nnml-prepare-save-mail-hook)
651     (goto-char (point-min))
652     (while (looking-at "From ")
653       (replace-match "X-From-Line: ")
654       (forward-line 1))
655     ;; We save the article in all the groups it belongs in.
656     (let ((ga group-art)
657           first)
658       (while ga
659         (nnml-possibly-create-directory (caar ga))
660         (let ((file (concat (nnmail-group-pathname
661                              (caar ga) nnml-directory)
662                             (int-to-string (cdar ga)))))
663           (if first
664               ;; It was already saved, so we just make a hard link.
665               (funcall nnmail-crosspost-link-function first file t)
666             ;; Save the article.
667             (nnmail-write-region (point-min) (point-max) file nil
668                                  (if (nnheader-be-verbose 5) nil 'nomesg))
669             (setq first file)))
670         (setq ga (cdr ga))))
671     ;; Generate a nov line for this article.  We generate the nov
672     ;; line after saving, because nov generation destroys the
673     ;; header.
674     (setq headers (nnml-parse-head chars))
675     ;; Output the nov line to all nov databases that should have it.
676     (let ((ga group-art))
677       (while ga
678         (nnml-add-nov (caar ga) (cdar ga) headers)
679         (setq ga (cdr ga))))
680     group-art))
681
682 (defun nnml-active-number (group)
683   "Compute the next article number in GROUP."
684   (let ((active (cadr (assoc group nnml-group-alist))))
685     ;; The group wasn't known to nnml, so we just create an active
686     ;; entry for it.
687     (unless active
688       ;; Perhaps the active file was corrupt?  See whether
689       ;; there are any articles in this group.
690       (nnml-possibly-create-directory group)
691       (nnml-possibly-change-directory group)
692       (unless nnml-article-file-alist
693         (setq nnml-article-file-alist
694               (sort
695                (nnml-current-group-article-to-file-alist)
696                'car-less-than-car)))
697       (setq active
698             (if nnml-article-file-alist
699                 (cons (caar nnml-article-file-alist)
700                       (caar (last nnml-article-file-alist)))
701               (cons 1 0)))
702       (push (list group active) nnml-group-alist))
703     (setcdr active (1+ (cdr active)))
704     (while (file-exists-p
705             (expand-file-name (int-to-string (cdr active))
706                               (nnmail-group-pathname group nnml-directory)))
707       (setcdr active (1+ (cdr active))))
708     (cdr active)))
709
710 (defun nnml-add-nov (group article headers)
711   "Add a nov line for the GROUP base."
712   (save-excursion
713     (set-buffer (nnml-open-nov group))
714     (goto-char (point-max))
715     (mail-header-set-number headers article)
716     (nnheader-insert-nov headers)))
717
718 (defsubst nnml-header-value ()
719   (buffer-substring (match-end 0) (progn (end-of-line) (point))))
720
721 (defun nnml-parse-head (chars &optional number)
722   "Parse the head of the current buffer."
723   (save-excursion
724     (save-restriction
725       (unless (zerop (buffer-size))
726         (narrow-to-region
727          (goto-char (point-min))
728          (if (re-search-forward "\n\r?\n" nil t) (1- (point)) (point-max))))
729       ;; Fold continuation lines.
730       (goto-char (point-min))
731       (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
732         (replace-match " " t t))
733       ;; Remove any tabs; they are too confusing.
734       (subst-char-in-region (point-min) (point-max) ?\t ? )
735       ;; Remove any ^M's; they are too confusing.
736       (subst-char-in-region (point-min) (point-max) ?\r ? )
737       (let ((headers (nnheader-parse-head t)))
738         (mail-header-set-chars headers chars)
739         (mail-header-set-number headers number)
740         headers))))
741
742 (defun nnml-get-nov-buffer (group)
743   (let ((buffer (get-buffer-create (format " *nnml overview %s*" group))))
744     (save-excursion
745       (set-buffer buffer)
746       (set (make-local-variable 'nnml-nov-buffer-file-name)
747            (expand-file-name
748             nnml-nov-file-name
749             (nnmail-group-pathname group nnml-directory)))
750       (erase-buffer)
751       (when (file-exists-p nnml-nov-buffer-file-name)
752         (nnheader-insert-file-contents nnml-nov-buffer-file-name)))
753     buffer))
754
755 (defun nnml-open-nov (group)
756   (or (cdr (assoc group nnml-nov-buffer-alist))
757       (let ((buffer (nnml-get-nov-buffer group)))
758         (push (cons group buffer) nnml-nov-buffer-alist)
759         buffer)))
760
761 (defun nnml-save-nov ()
762   (save-excursion
763     (while nnml-nov-buffer-alist
764       (when (buffer-name (cdar nnml-nov-buffer-alist))
765         (set-buffer (cdar nnml-nov-buffer-alist))
766         (when (buffer-modified-p)
767           (nnmail-write-region 1 (point-max) nnml-nov-buffer-file-name
768                                nil 'nomesg))
769         (set-buffer-modified-p nil)
770         (kill-buffer (current-buffer)))
771       (setq nnml-nov-buffer-alist (cdr nnml-nov-buffer-alist)))))
772
773 ;;;###autoload
774 (defun nnml-generate-nov-databases (&optional server)
775   "Generate NOV databases in all nnml directories."
776   (interactive (list (or (nnoo-current-server 'nnml) "")))
777   ;; Read the active file to make sure we don't re-use articles
778   ;; numbers in empty groups.
779   (nnmail-activate 'nnml)
780   (unless (nnml-server-opened server)
781     (nnml-open-server server))
782   (setq nnml-directory (expand-file-name nnml-directory))
783   ;; Recurse down the directories.
784   (nnml-generate-nov-databases-1 nnml-directory nil t)
785   ;; Save the active file.
786   (nnmail-save-active nnml-group-alist nnml-active-file))
787
788 (defun nnml-generate-nov-databases-1 (dir &optional seen no-active)
789   "Regenerate the NOV database in DIR."
790   (interactive "DRegenerate NOV in: ")
791   (setq dir (file-name-as-directory dir))
792   ;; Only scan this sub-tree if we haven't been here yet.
793   (unless (member (file-truename dir) seen)
794     (push (file-truename dir) seen)
795     ;; We descend recursively
796     (let ((dirs (directory-files dir t nil t))
797           dir)
798       (while (setq dir (pop dirs))
799         (when (and (not (string-match "^\\." (file-name-nondirectory dir)))
800                    (file-directory-p dir))
801           (nnml-generate-nov-databases-1 dir seen))))
802     ;; Do this directory.
803     (let ((files (sort (nnheader-article-to-file-alist dir)
804                        'car-less-than-car)))
805       (if (not files)
806           (let* ((group (nnheader-file-to-group
807                          (directory-file-name dir) nnml-directory))
808                  (info (cadr (assoc group nnml-group-alist))))
809             (when info
810               (setcar info (1+ (cdr info)))))
811         (funcall nnml-generate-active-function dir)
812         ;; Generate the nov file.
813         (nnml-generate-nov-file dir files)
814         (unless no-active
815           (nnmail-save-active nnml-group-alist nnml-active-file))))))
816
817 (eval-when-compile (defvar files))
818 (defun nnml-generate-active-info (dir)
819   ;; Update the active info for this group.
820   (let* ((group (nnheader-file-to-group
821                  (directory-file-name dir) nnml-directory))
822          (entry (assoc group nnml-group-alist))
823          (last (or (caadr entry) 0)))
824     (setq nnml-group-alist (delq entry nnml-group-alist))
825     (push (list group
826                 (cons (or (caar files) (1+ last))
827                       (max last
828                            (or (let ((f files))
829                                  (while (cdr f) (setq f (cdr f)))
830                                  (caar f))
831                                0))))
832           nnml-group-alist)))
833
834 (defun nnml-generate-nov-file (dir files)
835   (let* ((dir (file-name-as-directory dir))
836          (nov (concat dir nnml-nov-file-name))
837          (nov-buffer (get-buffer-create " *nov*"))
838          chars file headers)
839     (save-excursion
840       ;; Init the nov buffer.
841       (set-buffer nov-buffer)
842       (buffer-disable-undo)
843       (erase-buffer)
844       (set-buffer nntp-server-buffer)
845       ;; Delete the old NOV file.
846       (when (file-exists-p nov)
847         (funcall nnmail-delete-file-function nov))
848       (while files
849         (unless (file-directory-p (setq file (concat dir (cdar files))))
850           (erase-buffer)
851           (nnheader-insert-file-contents file)
852           (narrow-to-region
853            (goto-char (point-min))
854            (progn
855              (re-search-forward "\n\r?\n" nil t)
856              (setq chars (- (point-max) (point)))
857              (max 1 (1- (point)))))
858           (unless (zerop (buffer-size))
859             (goto-char (point-min))
860             (setq headers (nnml-parse-head chars (caar files)))
861             (save-excursion
862               (set-buffer nov-buffer)
863               (goto-char (point-max))
864               (nnheader-insert-nov headers)))
865           (widen))
866         (setq files (cdr files)))
867       (save-excursion
868         (set-buffer nov-buffer)
869         (nnmail-write-region 1 (point-max) nov nil 'nomesg)
870         (kill-buffer (current-buffer))))))
871
872 (defun nnml-nov-delete-article (group article)
873   (save-excursion
874     (set-buffer (nnml-open-nov group))
875     (when (nnheader-find-nov-line article)
876       (delete-region (point) (progn (forward-line 1) (point)))
877       (when (bobp)
878         (let ((active (cadr (assoc group nnml-group-alist)))
879               num)
880           (when active
881             (if (eobp)
882                 (setf (car active) (1+ (cdr active)))
883               (when (and (setq num (ignore-errors (read (current-buffer))))
884                          (numberp num))
885                 (setf (car active) num)))))))
886     t))
887
888 (defun nnml-update-file-alist (&optional force)
889   (when (or (not nnml-article-file-alist)
890             force)
891     (setq nnml-article-file-alist
892           (nnml-current-group-article-to-file-alist))))
893
894 (defun nnml-directory-articles (dir)
895   "Return a list of all article files in a directory.
896 Use the nov database for that directory if available."
897   (if (or gnus-nov-is-evil nnml-nov-is-evil
898           (not (file-exists-p
899                 (expand-file-name nnml-nov-file-name dir))))
900       (nnheader-directory-articles dir)
901     ;; build list from .overview if available
902     ;; We would use nnml-open-nov, except that nnml-nov-buffer-alist is
903     ;; defvoo'd, and we might get called when it hasn't been swapped in.
904     (save-excursion
905       (let ((list nil)
906             art
907             (buffer (nnml-get-nov-buffer nnml-current-group)))
908         (set-buffer buffer)
909         (goto-char (point-min))
910         (while (not (eobp))
911           (setq art (read (current-buffer)))
912           (push art list)
913           (forward-line 1))
914         list))))
915
916 (defun nnml-current-group-article-to-file-alist ()
917   "Return an alist of article/file pairs in the current group.
918 Use the nov database for the current group if available."
919   (if (or gnus-nov-is-evil
920           nnml-nov-is-evil
921           nnml-filenames-are-evil
922           (not (file-exists-p
923                 (expand-file-name nnml-nov-file-name
924                                   nnml-current-directory))))
925       (nnheader-article-to-file-alist nnml-current-directory)
926     ;; build list from .overview if available
927     (save-excursion
928       (let ((alist nil)
929             art
930             (buffer (nnml-get-nov-buffer nnml-current-group)))
931         (set-buffer buffer)
932         (goto-char (point-min))
933         (while (not (eobp))
934           (setq art (read (current-buffer)))
935           ;; assume file name is unadorned (ie. not compressed etc)
936           (push (cons art (int-to-string art)) alist)
937           (forward-line 1))
938         alist))))
939
940 (deffoo nnml-request-set-mark (group actions &optional server)
941   (nnml-possibly-change-directory group server)
942   (unless nnml-marks-is-evil
943     (nnml-open-marks group server)
944     (dolist (action actions)
945       (let ((range (nth 0 action))
946             (what  (nth 1 action))
947             (marks (nth 2 action)))
948         (assert (or (eq what 'add) (eq what 'del)) t
949                 "Unknown request-set-mark action: %s" what)
950         (dolist (mark marks)
951           (setq nnml-marks (gnus-update-alist-soft
952                             mark
953                             (funcall (if (eq what 'add) 'gnus-range-add
954                                        'gnus-remove-from-range)
955                                      (cdr (assoc mark nnml-marks)) range)
956                             nnml-marks)))))
957     (nnml-save-marks group server))
958   nil)
959
960 (deffoo nnml-request-update-info (group info &optional server)
961   (nnml-possibly-change-directory group server)
962   (when (and (not nnml-marks-is-evil) (nnml-marks-changed-p group))
963     (nnheader-message 8 "Updating marks for %s..." group)
964     (nnml-open-marks group server)
965     ;; Update info using `nnml-marks'.
966     (mapcar (lambda (pred)
967               (gnus-info-set-marks
968                info
969                (gnus-update-alist-soft
970                 (cdr pred)
971                 (cdr (assq (cdr pred) nnml-marks))
972                 (gnus-info-marks info))
973                t))
974             gnus-article-mark-lists)
975     (let ((seen (cdr (assq 'read nnml-marks))))
976       (gnus-info-set-read info
977                           (if (and (integerp (car seen))
978                                    (null (cdr seen)))
979                               (list (cons (car seen) (car seen)))
980                             seen)))
981     (nnheader-message 8 "Updating marks for %s...done" group))
982   info)
983
984 (defun nnml-marks-changed-p (group)
985   (let ((file (expand-file-name nnml-marks-file-name
986                                 (nnmail-group-pathname group nnml-directory))))
987     (if (null (gnus-gethash file nnml-marks-modtime))
988         t ;; never looked at marks file, assume it has changed
989       (not (eq (gnus-gethash file nnml-marks-modtime)
990                (nth 5 (file-attributes file)))))))
991
992 (defun nnml-save-marks (group server)
993   (let ((file-name-coding-system nnmail-pathname-coding-system)
994         (file (expand-file-name nnml-marks-file-name
995                                 (nnmail-group-pathname group nnml-directory))))
996     (condition-case err
997         (progn
998           (nnml-possibly-create-directory group)
999           (with-temp-file file
1000             (erase-buffer)
1001             (princ nnml-marks (current-buffer))
1002             (insert "\n"))
1003           (gnus-sethash file
1004                         (nth 5 (file-attributes file))
1005                         nnml-marks-modtime))
1006       (error (or (gnus-yes-or-no-p
1007                   (format "Could not write to %s (%s).  Continue? " file err))
1008                  (error "Cannot write to %s (%s)" err))))))
1009
1010 (defun nnml-open-marks (group server)
1011   (let ((file (expand-file-name
1012                nnml-marks-file-name
1013                (nnmail-group-pathname group nnml-directory))))
1014     (if (file-exists-p file)
1015         (condition-case err
1016             (with-temp-buffer
1017               (gnus-sethash file (nth 5 (file-attributes file))
1018                             nnml-marks-modtime)
1019               (nnheader-insert-file-contents file)
1020               (setq nnml-marks (read (current-buffer)))
1021               (dolist (el gnus-article-unpropagated-mark-lists)
1022                 (setq nnml-marks (gnus-remassoc el nnml-marks))))
1023           (error (or (gnus-yes-or-no-p
1024                       (format "Error reading nnml marks file %s (%s).  Continuing will use marks from .newsrc.eld.  Continue? " file err))
1025                      (error "Cannot read nnml marks file %s (%s)" file err))))
1026       ;; User didn't have a .marks file.  Probably first time
1027       ;; user of the .marks stuff.  Bootstrap it from .newsrc.eld.
1028       (let ((info (gnus-get-info
1029                    (gnus-group-prefixed-name
1030                     group
1031                     (gnus-server-to-method (format "nnml:%s" server))))))
1032         (nnheader-message 7 "Bootstrapping marks for %s..." group)
1033         (setq nnml-marks (gnus-info-marks info))
1034         (push (cons 'read (gnus-info-read info)) nnml-marks)
1035         (dolist (el gnus-article-unpropagated-mark-lists)
1036           (setq nnml-marks (gnus-remassoc el nnml-marks)))
1037         (nnml-save-marks group server)))))
1038
1039 (provide 'nnml)
1040
1041 ;;; nnml.el ends here