* lisp/gnus-draft.el (gnus-draft-edit-message): Use
[elisp/gnus.git-] / lisp / nnmail.el
1 ;;; nnmail.el --- mail support functions for the Gnus mail backends
2 ;; Copyright (C) 1995,96,97,98,99 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;; Keywords: news, mail
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 (eval-when-compile (require 'cl))
29
30 (require 'nnheader)
31 (require 'message)
32 (require 'custom)
33 (require 'gnus-util)
34 (require 'mail-source)
35
36 (eval-and-compile
37   (autoload 'gnus-error "gnus-util")
38   (autoload 'gnus-buffer-live-p "gnus-util"))
39
40 (eval-when-compile (require 'static))
41
42 (static-condition-case nil
43     :symbol-for-testing-whether-colon-keyword-is-available-or-not
44   (void-variable
45    (defconst :user ':user)
46    (defconst :path ':path)
47    (defconst :predicate ':predicate)))
48
49 (defgroup nnmail nil
50   "Reading mail with Gnus."
51   :group 'gnus)
52
53 (defgroup nnmail-retrieve nil
54   "Retrieving new mail."
55   :group 'nnmail)
56
57 (defgroup nnmail-prepare nil
58   "Preparing (or mangling) new mail after retrival."
59   :group 'nnmail)
60
61 (defgroup nnmail-duplicate nil
62   "Handling of duplicate mail messages."
63   :group 'nnmail)
64
65 (defgroup nnmail-split nil
66   "Organizing the incomming mail in folders."
67   :group 'nnmail)
68
69 (defgroup nnmail-files nil
70   "Mail files."
71   :group 'gnus-files
72   :group 'nnmail)
73
74 (defgroup nnmail-expire nil
75   "Expiring old mail."
76   :group 'nnmail)
77
78 (defgroup nnmail-procmail nil
79   "Interfacing with procmail and other mail agents."
80   :group 'nnmail)
81
82 (defgroup nnmail-various nil
83   "Various mail options."
84   :group 'nnmail)
85
86 (defcustom nnmail-split-methods
87   '(("mail.misc" ""))
88   "*Incoming mail will be split according to this variable.
89
90 If you'd like, for instance, one mail group for mail from the
91 \"4ad-l\" mailing list, one group for junk mail and one for everything
92 else, you could do something like this:
93
94  (setq nnmail-split-methods
95        '((\"mail.4ad\" \"From:.*4ad\")
96          (\"mail.junk\" \"From:.*Lars\\\\|Subject:.*buy\")
97          (\"mail.misc\" \"\")))
98
99 As you can see, this variable is a list of lists, where the first
100 element in each \"rule\" is the name of the group (which, by the way,
101 does not have to be called anything beginning with \"mail\",
102 \"yonka.zow\" is a fine, fine name), and the second is a regexp that
103 nnmail will try to match on the header to find a fit.
104
105 The second element can also be a function.  In that case, it will be
106 called narrowed to the headers with the first element of the rule as
107 the argument.  It should return a non-nil value if it thinks that the
108 mail belongs in that group.
109
110 The last element should always have \"\" as the regexp.
111
112 This variable can also have a function as its value."
113   :group 'nnmail-split
114   :type '(choice (repeat :tag "Alist" (group (string :tag "Name") regexp))
115                  (function-item nnmail-split-fancy)
116                  (function :tag "Other")))
117
118 ;; Suggested by Erik Selberg <speed@cs.washington.edu>.
119 (defcustom nnmail-crosspost t
120   "If non-nil, do crossposting if several split methods match the mail.
121 If nil, the first match found will be used."
122   :group 'nnmail-split
123   :type 'boolean)
124
125 ;; Added by gord@enci.ucalgary.ca (Gordon Matzigkeit).
126 (defcustom nnmail-keep-last-article nil
127   "If non-nil, nnmail will never delete/move a group's last article.
128 It can be marked expirable, so it will be deleted when it is no longer last.
129
130 You may need to set this variable if other programs are putting
131 new mail into folder numbers that Gnus has marked as expired."
132   :group 'nnmail-procmail
133   :group 'nnmail-various
134   :type 'boolean)
135
136 (defcustom nnmail-use-long-file-names nil
137   "If non-nil the mail backends will use long file and directory names.
138 If nil, groups like \"mail.misc\" will end up in directories like
139 \"mail/misc/\"."
140   :group 'nnmail-files
141   :type 'boolean)
142
143 (defcustom nnmail-default-file-modes 384
144   "Set the mode bits of all new mail files to this integer."
145   :group 'nnmail-files
146   :type 'integer)
147
148 (defcustom nnmail-expiry-wait 7
149   "*Expirable articles that are older than this will be expired.
150 This variable can either be a number (which will be interpreted as a
151 number of days) -- this doesn't have to be an integer.  This variable
152 can also be `immediate' and `never'."
153   :group 'nnmail-expire
154   :type '(choice (const immediate)
155                  (integer :tag "days")
156                  (const never)))
157
158 (defcustom nnmail-expiry-wait-function nil
159   "Variable that holds function to specify how old articles should be before they are expired.
160   The function will be called with the name of the group that the
161 expiry is to be performed in, and it should return an integer that
162 says how many days an article can be stored before it is considered
163 \"old\".  It can also return the values `never' and `immediate'.
164
165 Eg.:
166
167 \(setq nnmail-expiry-wait-function
168       (lambda (newsgroup)
169         (cond ((string-match \"private\" newsgroup) 31)
170               ((string-match \"junk\" newsgroup) 1)
171               ((string-match \"important\" newsgroup) 'never)
172               (t 7))))"
173   :group 'nnmail-expire
174   :type '(choice (const :tag "nnmail-expiry-wait" nil)
175                  (function :format "%v" nnmail-)))
176
177 (defcustom nnmail-cache-accepted-message-ids nil
178   "If non-nil, put Message-IDs of Gcc'd articles into the duplicate cache."
179   :group 'nnmail
180   :type 'boolean)
181
182 (defcustom nnmail-spool-file '((file))
183   "*Where the mail backends will look for incoming mail.
184 This variable is a list of mail source specifiers.
185 This variable is obsolete; `mail-sources' should be used instead."
186   :group 'nnmail-files
187   :type 'sexp)
188
189 (defcustom nnmail-resplit-incoming nil
190   "*If non-nil, re-split incoming procmail sorted mail."
191   :group 'nnmail-procmail
192   :type 'boolean)
193
194 (defcustom nnmail-delete-file-function 'delete-file
195   "Function called to delete files in some mail backends."
196   :group 'nnmail-files
197   :type 'function)
198
199 (defcustom nnmail-crosspost-link-function
200   (if (string-match "windows-nt\\|emx" (symbol-name system-type))
201       'copy-file
202     'add-name-to-file)
203   "*Function called to create a copy of a file.
204 This is `add-name-to-file' by default, which means that crossposts
205 will use hard links.  If your file system doesn't allow hard
206 links, you could set this variable to `copy-file' instead."
207   :group 'nnmail-files
208   :type '(radio (function-item add-name-to-file)
209                 (function-item copy-file)
210                 (function :tag "Other")))
211
212 (defcustom nnmail-read-incoming-hook
213   (if (eq system-type 'windows-nt)
214       '(nnheader-ms-strip-cr)
215     nil)
216   "*Hook that will be run after the incoming mail has been transferred.
217 The incoming mail is moved from `nnmail-spool-file' (which normally is
218 something like \"/usr/spool/mail/$user\") to the user's home
219 directory.  This hook is called after the incoming mail box has been
220 emptied, and can be used to call any mail box programs you have
221 running (\"xwatch\", etc.)
222
223 Eg.
224
225 \(add-hook 'nnmail-read-incoming-hook
226            (lambda ()
227              (start-process \"mailsend\" nil
228                             \"/local/bin/mailsend\" \"read\" \"mbox\")))
229
230 If you have xwatch running, this will alert it that mail has been
231 read.
232
233 If you use `display-time', you could use something like this:
234
235 \(add-hook 'nnmail-read-incoming-hook
236           (lambda ()
237             ;; Update the displayed time, since that will clear out
238             ;; the flag that says you have mail.
239             (when (eq (process-status \"display-time\") 'run)
240               (display-time-filter display-time-process \"\"))))"
241   :group 'nnmail-prepare
242   :type 'hook)
243
244 (defcustom nnmail-prepare-incoming-hook nil
245   "Hook called before treating incoming mail.
246 The hook is run in a buffer with all the new, incoming mail."
247   :group 'nnmail-prepare
248   :type 'hook)
249
250 (defcustom nnmail-prepare-incoming-header-hook nil
251   "Hook called narrowed to the headers of each message.
252 This can be used to remove excessive spaces (and stuff like
253 that) from the headers before splitting and saving the messages."
254   :group 'nnmail-prepare
255   :type 'hook)
256
257 (defcustom nnmail-prepare-incoming-message-hook nil
258   "Hook called narrowed to each message."
259   :group 'nnmail-prepare
260   :type 'hook)
261
262 (defcustom nnmail-list-identifiers nil
263   "Regexp that matches list identifiers to be removed.
264 This can also be a list of regexps."
265   :group 'nnmail-prepare
266   :type '(choice (const :tag "none" nil)
267                  (regexp :value ".*")
268                  (repeat :value (".*") regexp)))
269
270 (defcustom nnmail-pre-get-new-mail-hook nil
271   "Hook called just before starting to handle new incoming mail."
272   :group 'nnmail-retrieve
273   :type 'hook)
274
275 (defcustom nnmail-post-get-new-mail-hook nil
276   "Hook called just after finishing handling new incoming mail."
277   :group 'nnmail-retrieve
278   :type 'hook)
279
280 (defcustom nnmail-split-hook nil
281   "Hook called before deciding where to split an article.
282 The functions in this hook are free to modify the buffer
283 contents in any way they choose -- the buffer contents are
284 discarded after running the split process."
285   :group 'nnmail-split
286   :type 'hook)
287
288 (defcustom nnmail-large-newsgroup 50
289   "*The number of the articles which indicates a large newsgroup.
290 If the number of the articles is greater than the value, verbose
291 messages will be shown to indicate the current status."
292   :group 'nnmail-various
293   :type 'integer)
294
295 (defcustom nnmail-split-fancy "mail.misc"
296   "Incoming mail can be split according to this fancy variable.
297 To enable this, set `nnmail-split-methods' to `nnmail-split-fancy'.
298
299 The format of this variable is SPLIT, where SPLIT can be one of
300 the following:
301
302 GROUP: Mail will be stored in GROUP (a string).
303
304 \(FIELD VALUE [- RESTRICT [- RESTRICT [...]]] SPLIT): If the message
305   field FIELD (a regexp) contains VALUE (a regexp), store the messages 
306   as specified by SPLIT.  If RESTRICT (a regexp) matches some string
307   after FIELD and before the end of the matched VALUE, return NIL,
308   otherwise process SPLIT.  Multiple RESTRICTs add up, further
309   restricting the possibility of processing SPLIT.
310
311 \(| SPLIT...): Process each SPLIT expression until one of them matches.
312   A SPLIT expression is said to match if it will cause the mail
313   message to be stored in one or more groups.
314
315 \(& SPLIT...): Process each SPLIT expression.
316
317 \(: FUNCTION optional args): Call FUNCTION with the optional args, in
318   the buffer containing the message headers.  The return value FUNCTION
319   should be a split, which is then recursively processed.
320
321 \(! FUNCTION SPLIT): Call FUNCTION with the result of SPLIT.  The
322   return value FUNCTION should be a split, which is then recursively
323   processed.
324
325 FIELD must match a complete field name.  VALUE must match a complete
326 word according to the `nnmail-split-fancy-syntax-table' syntax table.
327 You can use \".*\" in the regexps to match partial field names or words.
328
329 FIELD and VALUE can also be lisp symbols, in that case they are expanded
330 as specified in `nnmail-split-abbrev-alist'.
331
332 GROUP can contain \\& and \\N which will substitute from matching
333 \\(\\) patterns in the previous VALUE.
334
335 Example:
336
337 \(setq nnmail-split-methods 'nnmail-split-fancy
338       nnmail-split-fancy
339       ;; Messages from the mailer daemon are not crossposted to any of
340       ;; the ordinary groups.  Warnings are put in a separate group
341       ;; from real errors.
342       '(| (\"from\" mail (| (\"subject\" \"warn.*\" \"mail.warning\")
343                           \"mail.misc\"))
344           ;; Non-error messages are crossposted to all relevant
345           ;; groups, but we don't crosspost between the group for the
346           ;; (ding) list and the group for other (ding) related mail.
347           (& (| (any \"ding@ifi\\\\.uio\\\\.no\" \"ding.list\")
348                 (\"subject\" \"ding\" \"ding.misc\"))
349              ;; Other mailing lists...
350              (any \"procmail@informatik\\\\.rwth-aachen\\\\.de\" \"procmail.list\")
351              (any \"SmartList@informatik\\\\.rwth-aachen\\\\.de\" \"SmartList.list\")
352              ;; Both lists below have the same suffix, so prevent
353              ;; cross-posting to mkpkg.list of messages posted only to 
354              ;; the bugs- list, but allow cross-posting when the
355              ;; message was really cross-posted.
356              (any \"bugs-mypackage@somewhere\" \"mypkg.bugs\")
357              (any \"mypackage@somewhere\" - \"bugs-mypackage\" \"mypkg.list\")
358              ;; 
359              ;; People...
360              (any \"larsi@ifi\\\\.uio\\\\.no\" \"people.Lars Magne Ingebrigtsen\"))
361           ;; Unmatched mail goes to the catch all group.
362           \"misc.misc\"))"
363   :group 'nnmail-split
364   ;; Sigh!
365   :type 'sexp)
366
367 (defcustom nnmail-split-abbrev-alist
368   '((any . "from\\|to\\|cc\\|sender\\|apparently-to\\|resent-from\\|resent-to\\|resent-cc")
369     (mail . "mailer-daemon\\|postmaster\\|uucp")
370     (to . "to\\|cc\\|apparently-to\\|resent-to\\|resent-cc")
371     (from . "from\\|sender\\|resent-from")
372     (nato . "to\\|cc\\|resent-to\\|resent-cc")
373     (naany . "from\\|to\\|cc\\|sender\\|resent-from\\|resent-to\\|resent-cc"))
374   "*Alist of abbreviations allowed in `nnmail-split-fancy'."
375   :group 'nnmail-split
376   :type '(repeat (cons :format "%v" symbol regexp)))
377
378 (defcustom nnmail-message-id-cache-length 1000
379   "*The approximate number of Message-IDs nnmail will keep in its cache.
380 If this variable is nil, no checking on duplicate messages will be
381 performed."
382   :group 'nnmail-duplicate
383   :type '(choice (const :tag "disable" nil)
384                  (integer :format "%v")))
385
386 (defcustom nnmail-message-id-cache-file "~/.nnmail-cache"
387   "*The file name of the nnmail Message-ID cache."
388   :group 'nnmail-duplicate
389   :group 'nnmail-files
390   :type 'file)
391
392 (defcustom nnmail-treat-duplicates 'warn
393   "*If non-nil, nnmail keep a cache of Message-IDs to discover mail duplicates.
394 Three values are valid: nil, which means that nnmail is not to keep a
395 Message-ID cache; `warn', which means that nnmail should insert extra
396 headers to warn the user about the duplication (this is the default);
397 and `delete', which means that nnmail will delete duplicated mails.
398
399 This variable can also be a function.  It will be called from a buffer
400 narrowed to the article in question with the Message-ID as a
401 parameter.  It should return nil, `warn' or `delete'."
402   :group 'nnmail-duplicate
403   :type '(choice (const :tag "off" nil)
404                  (const warn)
405                  (const delete)))
406
407 (defcustom nnmail-extra-headers nil
408   "*Extra headers to parse."
409   :group 'nnmail
410   :type '(repeat symbol))
411
412 (defcustom nnmail-split-header-length-limit 512
413   "Header lines longer than this limit are excluded from the split function."
414   :group 'nnmail
415   :type 'integer)
416
417 ;;; Internal variables.
418
419 (defvar nnmail-split-history nil
420   "List of group/article elements that say where the previous split put messages.")
421
422 (defvar nnmail-split-fancy-syntax-table nil
423   "Syntax table used by `nnmail-split-fancy'.")
424 (unless (syntax-table-p nnmail-split-fancy-syntax-table)
425   (setq nnmail-split-fancy-syntax-table
426         (copy-syntax-table (standard-syntax-table)))
427   ;; support the %-hack
428   (modify-syntax-entry ?\% "." nnmail-split-fancy-syntax-table))
429
430 (defvar nnmail-prepare-save-mail-hook nil
431   "Hook called before saving mail.")
432
433 (defvar nnmail-split-tracing nil)
434 (defvar nnmail-split-trace nil)
435
436 \f
437
438 (defconst nnmail-version "nnmail 1.0"
439   "nnmail version.")
440
441 \f
442
443 (defun nnmail-request-post (&optional server)
444   (mail-send-and-exit nil))
445
446 (defvar nnmail-file-coding-system 'raw-text
447   "Coding system used in nnmail.")
448
449 (defvar nnmail-incoming-coding-system 'raw-text
450   "Coding system used in reading inbox")
451
452 (defvar nnmail-pathname-coding-system 'binary
453   "*Coding system for pathname.")
454
455 (defun nnmail-find-file (file)
456   "Insert FILE in server buffer safely."
457   (set-buffer nntp-server-buffer)
458   (delete-region (point-min) (point-max))
459   (let ((format-alist nil)
460         (after-insert-file-functions nil))
461     (condition-case ()
462         (let ((auto-mode-alist (nnheader-auto-mode-alist))
463               (pathname-coding-system nnmail-pathname-coding-system))
464           (insert-file-contents-as-coding-system
465            nnmail-file-coding-system file)
466           t)
467       (file-error nil))))
468
469 (defun nnmail-group-pathname (group dir &optional file)
470   "Make pathname for GROUP."
471   (concat
472    (let ((dir (file-name-as-directory (expand-file-name dir))))
473      (setq group (nnheader-translate-file-chars group))
474      ;; If this directory exists, we use it directly.
475      (if (or nnmail-use-long-file-names
476              (file-directory-p (concat dir group)))
477          (concat dir group "/")
478        ;; If not, we translate dots into slashes.
479        (concat dir
480                (encode-coding-string
481                 (nnheader-replace-chars-in-string group ?. ?/)
482                 nnmail-pathname-coding-system)
483                "/")))
484    (or file "")))
485
486 (defun nnmail-get-active ()
487   "Returns an assoc of group names and active ranges.
488 nn*-request-list should have been called before calling this function."
489   (let (group-assoc)
490     ;; Go through all groups from the active list.
491     (save-excursion
492       (set-buffer nntp-server-buffer)
493       (goto-char (point-min))
494       (while (re-search-forward
495               "^\\([^ \t]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)" nil t)
496         ;; We create an alist with `(GROUP (LOW . HIGH))' elements.
497         (push (list (match-string 1)
498                     (cons (string-to-int (match-string 3))
499                           (string-to-int (match-string 2))))
500               group-assoc)))
501     group-assoc))
502
503 (defvar nnmail-active-file-coding-system 'raw-text
504   "*Coding system for active file.")
505
506 (defun nnmail-save-active (group-assoc file-name)
507   "Save GROUP-ASSOC in ACTIVE-FILE."
508   (let ((coding-system-for-write nnmail-active-file-coding-system)
509         (output-coding-system nnmail-active-file-coding-system))
510     (when file-name
511       (with-temp-file file-name
512         (nnmail-generate-active group-assoc)))))
513
514 (defun nnmail-generate-active (alist)
515   "Generate an active file from group-alist ALIST."
516   (erase-buffer)
517   (let (group)
518     (while (setq group (pop alist))
519       (insert (format "%s %d %d y\n" (car group) (cdadr group)
520                       (caadr group))))))
521
522 (defun nnmail-get-split-group (file source)
523   "Find out whether this FILE is to be split into GROUP only.
524 If SOURCE is a directory spec, try to return the group name component."
525   (if (eq (car source) 'directory)
526       (let ((file (file-name-nondirectory file)))
527         (mail-source-bind (directory source)
528           (if (string-match (concat (regexp-quote suffix) "$") file)
529               (substring file 0 (match-beginning 0))
530             nil)))
531     nil))
532
533 (defun nnmail-process-babyl-mail-format (func artnum-func)
534   (let ((case-fold-search t)
535         (count 0)
536         start message-id content-length do-search end)
537     (while (not (eobp))
538       (goto-char (point-min))
539       (re-search-forward
540        "\f\n0, *unseen,+\n\\(\\*\\*\\* EOOH \\*\\*\\*\n\\)?" nil t)
541       (goto-char (match-end 0))
542       (delete-region (match-beginning 0) (match-end 0))
543       (narrow-to-region
544        (setq start (point))
545        (progn
546          ;; Skip all the headers in case there are more "From "s...
547          (or (search-forward "\n\n" nil t)
548              (search-forward-regexp "^[^:]*\\( .*\\|\\)$" nil t)
549              (search-forward "\1f\f"))
550          (point)))
551       ;; Unquote the ">From " line, if any.
552       (goto-char (point-min))
553       (when (looking-at ">From ")
554         (replace-match "X-From-Line: ") )
555       (run-hooks 'nnmail-prepare-incoming-header-hook)
556       (goto-char (point-max))
557       ;; Find the Message-ID header.
558       (save-excursion
559         (if (re-search-backward
560              "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]*>\\)" nil t)
561             (setq message-id (buffer-substring (match-beginning 1)
562                                                (match-end 1)))
563           ;; There is no Message-ID here, so we create one.
564           (save-excursion
565             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
566               (beginning-of-line)
567               (insert "Original-")))
568           (forward-line -1)
569           (insert "Message-ID: " (setq message-id (nnmail-message-id))
570                   "\n")))
571       ;; Look for a Content-Length header.
572       (if (not (save-excursion
573                  (and (re-search-backward
574                        "^Content-Length:[ \t]*\\([0-9]+\\)" start t)
575                       (setq content-length (string-to-int
576                                             (buffer-substring
577                                              (match-beginning 1)
578                                              (match-end 1))))
579                       ;; We destroy the header, since none of
580                       ;; the backends ever use it, and we do not
581                       ;; want to confuse other mailers by having
582                       ;; a (possibly) faulty header.
583                       (progn (insert "X-") t))))
584           (setq do-search t)
585         (widen)
586         (if (or (= (+ (point) content-length) (point-max))
587                 (save-excursion
588                   (goto-char (+ (point) content-length))
589                   (looking-at "\1f")))
590             (progn
591               (goto-char (+ (point) content-length))
592               (setq do-search nil))
593           (setq do-search t)))
594       (widen)
595       ;; Go to the beginning of the next article - or to the end
596       ;; of the buffer.
597       (when do-search
598         (if (re-search-forward "^\1f" nil t)
599             (goto-char (match-beginning 0))
600           (goto-char (1- (point-max)))))
601       (delete-char 1)                   ; delete ^_
602       (save-excursion
603         (save-restriction
604           (narrow-to-region start (point))
605           (goto-char (point-min))
606           (nnmail-check-duplication message-id func artnum-func)
607           (incf count)
608           (setq end (point-max))))
609       (goto-char end))
610     count))
611
612 (defsubst nnmail-search-unix-mail-delim ()
613   "Put point at the beginning of the next Unix mbox message."
614   ;; Algorithm used to find the the next article in the
615   ;; brain-dead Unix mbox format:
616   ;;
617   ;; 1) Search for "^From ".
618   ;; 2) If we find it, then see whether the previous
619   ;;    line is blank and the next line looks like a header.
620   ;; Then it's possible that this is a mail delim, and we use it.
621   (let ((case-fold-search nil)
622         found)
623     (while (not found)
624       (if (not (re-search-forward "^From " nil t))
625           (setq found 'no)
626         (save-excursion
627           (beginning-of-line)
628           (when (and (or (bobp)
629                          (save-excursion
630                            (forward-line -1)
631                            (eq (char-after) ?\n)))
632                      (save-excursion
633                        (forward-line 1)
634                        (while (looking-at ">From \\|From ")
635                          (forward-line 1))
636                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
637             (setq found 'yes)))))
638     (beginning-of-line)
639     (eq found 'yes)))
640
641 (defun nnmail-search-unix-mail-delim-backward ()
642   "Put point at the beginning of the current Unix mbox message."
643   ;; Algorithm used to find the the next article in the
644   ;; brain-dead Unix mbox format:
645   ;;
646   ;; 1) Search for "^From ".
647   ;; 2) If we find it, then see whether the previous
648   ;;    line is blank and the next line looks like a header.
649   ;; Then it's possible that this is a mail delim, and we use it.
650   (let ((case-fold-search nil)
651         found)
652     (while (not found)
653       (if (not (re-search-backward "^From " nil t))
654           (setq found 'no)
655         (save-excursion
656           (beginning-of-line)
657           (when (and (or (bobp)
658                          (save-excursion
659                            (forward-line -1)
660                            (eq (char-after) ?\n)))
661                      (save-excursion
662                        (forward-line 1)
663                        (while (looking-at ">From \\|From ")
664                          (forward-line 1))
665                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
666             (setq found 'yes)))))
667     (beginning-of-line)
668     (eq found 'yes)))
669
670 (defun nnmail-process-unix-mail-format (func artnum-func)
671   (let ((case-fold-search t)
672         (count 0)
673         start message-id content-length end skip head-end)
674     (goto-char (point-min))
675     (if (not (and (re-search-forward "^From " nil t)
676                   (goto-char (match-beginning 0))))
677         ;; Possibly wrong format?
678         (error "Error, unknown mail format! (Possibly corrupted.)")
679       ;; Carry on until the bitter end.
680       (while (not (eobp))
681         (setq start (point)
682               end nil)
683         ;; Find the end of the head.
684         (narrow-to-region
685          start
686          (if (search-forward "\n\n" nil t)
687              (1- (point))
688            ;; This will never happen, but just to be on the safe side --
689            ;; if there is no head-body delimiter, we search a bit manually.
690            (while (and (looking-at "From \\|[^ \t]+:")
691                        (not (eobp)))
692              (forward-line 1))
693            (point)))
694         ;; Find the Message-ID header.
695         (goto-char (point-min))
696         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
697             (setq message-id (match-string 1))
698           (save-excursion
699             (when (re-search-forward "^Message-ID[ \t]*:" nil t)
700               (beginning-of-line)
701               (insert "Original-")))
702           ;; There is no Message-ID here, so we create one.
703           (forward-line 1)
704           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
705         ;; Look for a Content-Length header.
706         (goto-char (point-min))
707         (if (not (re-search-forward
708                   "^Content-Length:[ \t]*\\([0-9]+\\)" nil t))
709             (setq content-length nil)
710           (setq content-length (string-to-int (match-string 1)))
711           ;; We destroy the header, since none of the backends ever
712           ;; use it, and we do not want to confuse other mailers by
713           ;; having a (possibly) faulty header.
714           (beginning-of-line)
715           (insert "X-"))
716         (run-hooks 'nnmail-prepare-incoming-header-hook)
717         ;; Find the end of this article.
718         (goto-char (point-max))
719         (widen)
720         (setq head-end (point))
721         ;; We try the Content-Length value.  The idea: skip over the header
722         ;; separator, then check what happens content-length bytes into the
723         ;; message body.  This should be either the end ot the buffer, the
724         ;; message separator or a blank line followed by the separator.
725         ;; The blank line should probably be deleted.  If neither of the
726         ;; three is met, the content-length header is probably invalid.
727         (when content-length
728           (forward-line 1)
729           (setq skip (+ (point) content-length))
730           (goto-char skip)
731           (cond ((or (= skip (point-max))
732                      (= (1+ skip) (point-max)))
733                  (setq end (point-max)))
734                 ((looking-at "From ")
735                  (setq end skip))
736                 ((looking-at "[ \t]*\n\\(From \\)")
737                  (setq end (match-beginning 1)))
738                 (t (setq end nil))))
739         (if end
740             (goto-char end)
741           ;; No Content-Length, so we find the beginning of the next
742           ;; article or the end of the buffer.
743           (goto-char head-end)
744           (or (nnmail-search-unix-mail-delim)
745               (goto-char (point-max))))
746         ;; Allow the backend to save the article.
747         (save-excursion
748           (save-restriction
749             (narrow-to-region start (point))
750             (goto-char (point-min))
751             (incf count)
752             (nnmail-check-duplication message-id func artnum-func)
753             (setq end (point-max))))
754         (goto-char end)))
755     count))
756
757 (defun nnmail-process-mmdf-mail-format (func artnum-func)
758   (let ((delim "^\^A\^A\^A\^A$")
759         (case-fold-search t)
760         (count 0)
761         start message-id end)
762     (goto-char (point-min))
763     (if (not (and (re-search-forward delim nil t)
764                   (forward-line 1)))
765         ;; Possibly wrong format?
766         (error "Error, unknown mail format! (Possibly corrupted.)")
767       ;; Carry on until the bitter end.
768       (while (not (eobp))
769         (setq start (point))
770         ;; Find the end of the head.
771         (narrow-to-region
772          start
773          (if (search-forward "\n\n" nil t)
774              (1- (point))
775            ;; This will never happen, but just to be on the safe side --
776            ;; if there is no head-body delimiter, we search a bit manually.
777            (while (and (looking-at "From \\|[^ \t]+:")
778                        (not (eobp)))
779              (forward-line 1))
780            (point)))
781         ;; Find the Message-ID header.
782         (goto-char (point-min))
783         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
784             (setq message-id (match-string 1))
785           ;; There is no Message-ID here, so we create one.
786           (save-excursion
787             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
788               (beginning-of-line)
789               (insert "Original-")))
790           (forward-line 1)
791           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
792         (run-hooks 'nnmail-prepare-incoming-header-hook)
793         ;; Find the end of this article.
794         (goto-char (point-max))
795         (widen)
796         (if (re-search-forward delim nil t)
797             (beginning-of-line)
798           (goto-char (point-max)))
799         ;; Allow the backend to save the article.
800         (save-excursion
801           (save-restriction
802             (narrow-to-region start (point))
803             (goto-char (point-min))
804             (incf count)
805             (nnmail-check-duplication message-id func artnum-func)
806             (setq end (point-max))))
807         (goto-char end)
808         (forward-line 2)))
809     count))
810
811 (defun nnmail-process-maildir-mail-format (func artnum-func)
812   ;; In a maildir, every file contains exactly one mail.
813   (let ((case-fold-search t)
814         message-id)
815     (goto-char (point-min))
816     ;; Find the end of the head.
817     (narrow-to-region
818      (point-min)
819      (if (search-forward "\n\n" nil t)
820          (1- (point))
821        ;; This will never happen, but just to be on the safe side --
822        ;; if there is no head-body delimiter, we search a bit manually.
823        (while (and (looking-at "From \\|[^ \t]+:")
824                    (not (eobp)))
825          (forward-line 1))
826        (point)))
827     ;; Find the Message-ID header.
828     (goto-char (point-min))
829     (if (re-search-forward "^Message-ID:[ \t]*\\(<[^>]+>\\)" nil t)
830         (setq message-id (match-string 1))
831       ;; There is no Message-ID here, so we create one.
832       (save-excursion
833         (when (re-search-backward "^Message-ID[ \t]*:" nil t)
834           (beginning-of-line)
835           (insert "Original-")))
836       (forward-line 1)
837       (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
838     (run-hooks 'nnmail-prepare-incoming-header-hook)
839     ;; Allow the backend to save the article.
840     (widen)
841     (save-excursion
842       (goto-char (point-min))
843       (nnmail-check-duplication message-id func artnum-func))
844     1))
845
846 (defun nnmail-split-incoming (incoming func &optional exit-func
847                                        group artnum-func)
848   "Go through the entire INCOMING file and pick out each individual mail.
849 FUNC will be called with the buffer narrowed to each mail."
850   (let (;; If this is a group-specific split, we bind the split
851         ;; methods to just this group.
852         (nnmail-split-methods (if (and group
853                                        (not nnmail-resplit-incoming))
854                                   (list (list group ""))
855                                 nnmail-split-methods)))
856     (save-excursion
857       ;; Insert the incoming file.
858       (set-buffer (get-buffer-create " *nnmail incoming*"))
859       (erase-buffer)
860       (let ((nnheader-file-coding-system nnmail-incoming-coding-system))
861         (nnheader-insert-file-contents incoming))
862       (prog1
863           (if (zerop (buffer-size))
864               0
865             (goto-char (point-min))
866             (save-excursion (run-hooks 'nnmail-prepare-incoming-hook))
867             ;; Handle both babyl, MMDF and unix mail formats, since
868             ;; movemail will use the former when fetching from a
869             ;; mailbox, the latter when fetching from a file.
870             (cond ((or (looking-at "\^L")
871                        (looking-at "BABYL OPTIONS:"))
872                    (nnmail-process-babyl-mail-format func artnum-func))
873                   ((looking-at "\^A\^A\^A\^A")
874                    (nnmail-process-mmdf-mail-format func artnum-func))
875                   ((looking-at "Return-Path:")
876                    (nnmail-process-maildir-mail-format func artnum-func))
877                   (t
878                    (nnmail-process-unix-mail-format func artnum-func))))
879         (when exit-func
880           (funcall exit-func))
881         (kill-buffer (current-buffer))))))
882
883 (defun nnmail-article-group (func &optional trace)
884   "Look at the headers and return an alist of groups that match.
885 FUNC will be called with the group name to determine the article number."
886   (let ((methods nnmail-split-methods)
887         (obuf (current-buffer))
888         (beg (point-min))
889         end group-art method grp)
890     (if (and (sequencep methods)
891              (= (length methods) 1))
892         ;; If there is only just one group to put everything in, we
893         ;; just return a list with just this one method in.
894         (setq group-art
895               (list (cons (caar methods) (funcall func (caar methods)))))
896       ;; We do actual comparison.
897       (save-excursion
898         ;; Find headers.
899         (goto-char beg)
900         (setq end (if (search-forward "\n\n" nil t) (point) (point-max)))
901         (set-buffer nntp-server-buffer)
902         (erase-buffer)
903         ;; Copy the headers into the work buffer.
904         (insert-buffer-substring obuf beg end)
905         ;; Fold continuation lines.
906         (goto-char (point-min))
907         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
908           (replace-match " " t t))
909         ;; Nuke pathologically long headers.  Since Gnus applies
910         ;; pathologically complex regexps to the buffer, lines
911         ;; that are looong will take longer than the Universe's
912         ;; existence to process.
913         (goto-char (point-min))
914         (while (not (eobp))
915           (unless (< (move-to-column nnmail-split-header-length-limit)
916                      nnmail-split-header-length-limit)
917             (delete-region (point) (progn (end-of-line) (point))))
918           (forward-line 1))
919         ;; Allow washing.
920         (goto-char (point-min))
921         (run-hooks 'nnmail-split-hook)
922         (when (setq nnmail-split-tracing trace)
923           (setq nnmail-split-trace nil))
924         (if (and (symbolp nnmail-split-methods)
925                  (fboundp nnmail-split-methods))
926             (let ((split
927                    (condition-case nil
928                        ;; `nnmail-split-methods' is a function, so we
929                        ;; just call this function here and use the
930                        ;; result.
931                        (or (funcall nnmail-split-methods)
932                            '("bogus"))
933                      (error
934                       (nnheader-message 5
935                        "Error in `nnmail-split-methods'; using `bogus' mail group")
936                       (sit-for 1)
937                       '("bogus")))))
938               (setq split (gnus-remove-duplicates split))
939               ;; The article may be "cross-posted" to `junk'.  What
940               ;; to do?  Just remove the `junk' spec.  Don't really
941               ;; see anything else to do...
942               (let (elem)
943                 (while (setq elem (car (memq 'junk split)))
944                   (setq split (delq elem split))))
945               (when split
946                 (setq group-art
947                       (mapcar
948                        (lambda (group) (cons group (funcall func group)))
949                        split))))
950           ;; Go through the split methods to find a match.
951           (while (and methods
952                       (or nnmail-crosspost
953                           (not group-art)))
954             (goto-char (point-max))
955             (setq method (pop methods)
956                   grp (car method))
957             (if (or methods
958                     (not (equal "" (nth 1 method))))
959                 (when (and
960                        (ignore-errors
961                          (if (stringp (nth 1 method))
962                              (let ((expand (string-match "\\\\[0-9&]" grp))
963                                    (pos (re-search-backward (cadr method)
964                                                             nil t)))
965                                (and expand
966                                     (setq grp (nnmail-expand-newtext grp)))
967                                pos)
968                            ;; Function to say whether this is a match.
969                            (funcall (nth 1 method) grp)))
970                        ;; Don't enter the article into the same
971                        ;; group twice.
972                        (not (assoc grp group-art)))
973                   (push (cons grp (funcall func grp))
974                         group-art))
975               ;; This is the final group, which is used as a
976               ;; catch-all.
977               (unless group-art
978                 (setq group-art
979                       (list (cons (car method)
980                                   (funcall func (car method)))))))))
981         ;; Produce a trace if non-empty.
982         (when (and trace nnmail-split-trace)
983           (let ((trace (nreverse nnmail-split-trace))
984                 (restore (current-buffer)))
985             (nnheader-set-temp-buffer "*Split Trace*")
986             (gnus-add-buffer)
987             (while trace
988               (insert (car trace) "\n")
989               (setq trace (cdr trace)))
990             (goto-char (point-min))
991             (gnus-configure-windows 'split-trace)
992             (set-buffer restore)))
993         ;; See whether the split methods returned `junk'.
994         (if (equal group-art '(junk))
995             nil
996           ;; The article may be "cross-posted" to `junk'.  What
997           ;; to do?  Just remove the `junk' spec.  Don't really
998           ;; see anything else to do...
999           (let (elem)
1000             (while (setq elem (car (memq 'junk group-art)))
1001               (setq group-art (delq elem group-art)))
1002             (nreverse group-art)))))))
1003
1004 (defun nnmail-insert-lines ()
1005   "Insert how many lines there are in the body of the mail.
1006 Return the number of characters in the body."
1007   (let (lines chars)
1008     (save-excursion
1009       (goto-char (point-min))
1010       (when (search-forward "\n\n" nil t)
1011         (setq chars (- (point-max) (point)))
1012         (setq lines (count-lines (point) (point-max)))
1013         (forward-char -1)
1014         (save-excursion
1015           (when (re-search-backward "^Lines: " nil t)
1016             (delete-region (point) (progn (forward-line 1) (point)))))
1017         (beginning-of-line)
1018         (insert (format "Lines: %d\n" (max lines 0)))
1019         chars))))
1020
1021 (defun nnmail-insert-xref (group-alist)
1022   "Insert an Xref line based on the (group . article) alist."
1023   (save-excursion
1024     (goto-char (point-min))
1025     (when (search-forward "\n\n" nil t)
1026       (forward-char -1)
1027       (when (re-search-backward "^Xref: " nil t)
1028         (delete-region (match-beginning 0)
1029                        (progn (forward-line 1) (point))))
1030       (insert (format "Xref: %s" (system-name)))
1031       (while group-alist
1032         (insert (format " %s:%d"
1033                         (encode-coding-string
1034                          (caar group-alist)
1035                          nnmail-pathname-coding-system)
1036                         (cdar group-alist)))
1037         (setq group-alist (cdr group-alist)))
1038       (insert "\n"))))
1039
1040 ;;; Message washing functions
1041
1042 (defun nnmail-remove-leading-whitespace ()
1043   "Remove excessive whitespace from all headers."
1044   (goto-char (point-min))
1045   (while (re-search-forward "^\\([^ :]+: \\) +" nil t)
1046     (replace-match "\\1" t)))
1047
1048 (defun nnmail-remove-list-identifiers ()
1049   "Remove list identifiers from Subject headers."
1050   (let ((regexp (if (stringp nnmail-list-identifiers) nnmail-list-identifiers
1051                   (mapconcat 'identity nnmail-list-identifiers " *\\|"))))
1052     (when regexp
1053       (goto-char (point-min))
1054       (when (re-search-forward
1055              (concat "^Subject: +\\(Re: +\\)?\\(" regexp " *\\)")
1056              nil t)
1057         (delete-region (match-beginning 2) (match-end 0))))))
1058
1059 (defun nnmail-remove-tabs ()
1060   "Translate TAB characters into SPACE characters."
1061   (subst-char-in-region (point-min) (point-max) ?\t ?  t))
1062
1063 (defun nnmail-fix-eudora-headers ()
1064   "Eudora has a broken References line, but an OK In-Reply-To."
1065   (goto-char (point-min))
1066   (when (re-search-forward "^X-Mailer:.*Eudora" nil t)
1067     (goto-char (point-min))
1068     (when (re-search-forward "^References:" nil t)
1069       (beginning-of-line)
1070       (insert "X-Gnus-Broken-Eudora-"))))
1071
1072 (custom-add-option 'nnmail-prepare-incoming-header-hook
1073                    'nnmail-fix-eudora-headers)
1074
1075 ;;; Utility functions
1076
1077 (defun nnmail-split-fancy ()
1078   "Fancy splitting method.
1079 See the documentation for the variable `nnmail-split-fancy' for documentation."
1080   (let ((syntab (syntax-table)))
1081     (unwind-protect
1082         (progn
1083           (set-syntax-table nnmail-split-fancy-syntax-table)
1084           (nnmail-split-it nnmail-split-fancy))
1085       (set-syntax-table syntab))))
1086
1087 (defvar nnmail-split-cache nil)
1088 ;; Alist of split expressions their equivalent regexps.
1089
1090 (defun nnmail-split-it (split)
1091   ;; Return a list of groups matching SPLIT.
1092   (let (cached-pair)
1093     (cond
1094      ;; nil split
1095      ((null split)
1096       nil)
1097
1098      ;; A group name.  Do the \& and \N subs into the string.
1099      ((stringp split)
1100       (when nnmail-split-tracing
1101         (push (format "\"%s\"" split) nnmail-split-trace))
1102       (list (nnmail-expand-newtext split)))
1103
1104      ;; Junk the message.
1105      ((eq split 'junk)
1106       (when nnmail-split-tracing
1107         (push "junk" nnmail-split-trace))
1108       (list 'junk))
1109
1110      ;; Builtin & operation.
1111      ((eq (car split) '&)
1112       (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
1113
1114      ;; Builtin | operation.
1115      ((eq (car split) '|)
1116       (let (done)
1117         (while (and (not done) (cdr split))
1118           (setq split (cdr split)
1119                 done (nnmail-split-it (car split))))
1120         done))
1121
1122      ;; Builtin : operation.
1123      ((eq (car split) ':)
1124       (nnmail-split-it (save-excursion (eval (cdr split)))))
1125
1126      ;; Builtin ! operation.
1127      ((eq (car split) '!)
1128       (funcall (cadr split) (nnmail-split-it (caddr split))))
1129
1130      ;; Check the cache for the regexp for this split.
1131      ((setq cached-pair (assq split nnmail-split-cache))
1132       (let (split-result
1133             (end-point (point-max))
1134             (value (nth 1 split)))
1135         (if (symbolp value)
1136             (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1137         (while (and (goto-char end-point)
1138                     (re-search-backward (cdr cached-pair) nil t))
1139           (when nnmail-split-tracing
1140             (push (cdr cached-pair) nnmail-split-trace))
1141           (let ((split-rest (cddr split))
1142                 (end (match-end 0))
1143                 ;; The searched regexp is \(\(FIELD\).*\)\(VALUE\).  So,
1144                 ;; start-of-value is the the point just before the
1145                 ;; beginning of the value, whereas after-header-name is
1146                 ;; the point just after the field name.
1147                 (start-of-value (match-end 1))
1148                 (after-header-name (match-end 2)))
1149             ;; Start the next search just before the beginning of the
1150             ;; VALUE match.
1151             (setq end-point (1- start-of-value))
1152             ;; Handle - RESTRICTs
1153             (while (eq (car split-rest) '-)
1154               ;; RESTRICT must start after-header-name and
1155               ;; end after start-of-value, so that, for
1156               ;; (any "foo" - "x-foo" "foo.list")
1157               ;; we do not exclude foo.list just because
1158               ;; the header is: ``To: x-foo, foo''
1159               (goto-char end)
1160               (if (and (re-search-backward (cadr split-rest)
1161                                            after-header-name t)
1162                        (> (match-end 0) start-of-value))
1163                   (setq split-rest nil)
1164                 (setq split-rest (cddr split-rest))))
1165             (when split-rest
1166               (goto-char end)
1167               (let ((value (nth 1 split)))
1168                 (if (symbolp value)
1169                     (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1170                 ;; Someone might want to do a \N sub on this match, so get the
1171                 ;; correct match positions.
1172                 (re-search-backward (concat "\\<" value "\\>") start-of-value))
1173               (dolist (sp (nnmail-split-it (car split-rest)))
1174                 (unless (memq sp split-result)
1175                   (push sp split-result))))))
1176         split-result))
1177
1178      ;; Not in cache, compute a regexp for the field/value pair.
1179      (t
1180       (let* ((field (nth 0 split))
1181              (value (nth 1 split))
1182              partial regexp)
1183         (if (symbolp value)
1184             (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1185         (if (and (>= (length value) 2)
1186                  (string= ".*" (substring value 0 2)))
1187             (setq value (substring value 2)
1188                   partial ""))
1189         (setq regexp (concat "^\\(\\("
1190                              (if (symbolp field)
1191                                  (cdr (assq field nnmail-split-abbrev-alist))
1192                                field)
1193                              "\\):.*\\)"
1194                              (or partial "\\<")
1195                              "\\("
1196                              value
1197                              "\\)\\>"))
1198         (push (cons split regexp) nnmail-split-cache)
1199         ;; Now that it's in the cache, just call nnmail-split-it again
1200         ;; on the same split, which will find it immediately in the cache.
1201         (nnmail-split-it split))))))
1202
1203 (defun nnmail-expand-newtext (newtext)
1204   (let ((len (length newtext))
1205         (pos 0)
1206         c expanded beg N did-expand)
1207     (while (< pos len)
1208       (setq beg pos)
1209       (while (and (< pos len)
1210                   (not (= (aref newtext pos) ?\\)))
1211         (setq pos (1+ pos)))
1212       (unless (= beg pos)
1213         (push (substring newtext beg pos) expanded))
1214       (when (< pos len)
1215         ;; We hit a \; expand it.
1216         (setq did-expand t
1217               pos (1+ pos)
1218               c (aref newtext pos))
1219         (if (not (or (= c ?\&)
1220                      (and (>= c ?1)
1221                           (<= c ?9))))
1222             ;; \ followed by some character we don't expand.
1223             (push (char-to-string c) expanded)
1224           ;; \& or \N
1225           (if (= c ?\&)
1226               (setq N 0)
1227             (setq N (- c ?0)))
1228           (when (match-beginning N)
1229             (push (buffer-substring (match-beginning N) (match-end N))
1230                   expanded))))
1231       (setq pos (1+ pos)))
1232     (if did-expand
1233         (apply 'concat (nreverse expanded))
1234       newtext)))
1235
1236 ;; Activate a backend only if it isn't already activated.
1237 ;; If FORCE, re-read the active file even if the backend is
1238 ;; already activated.
1239 (defun nnmail-activate (backend &optional force)
1240   (nnheader-init-server-buffer)
1241   (let (file timestamp file-time)
1242     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1243             force
1244             (and (setq file (ignore-errors
1245                               (symbol-value (intern (format "%s-active-file"
1246                                                             backend)))))
1247                  (setq file-time (nth 5 (file-attributes file)))
1248                  (or (not
1249                       (setq timestamp
1250                             (condition-case ()
1251                                 (symbol-value (intern
1252                                                (format "%s-active-timestamp"
1253                                                        backend)))
1254                               (error 'none))))
1255                      (not (consp timestamp))
1256                      (equal timestamp '(0 0))
1257                      (> (nth 0 file-time) (nth 0 timestamp))
1258                      (and (= (nth 0 file-time) (nth 0 timestamp))
1259                           (> (nth 1 file-time) (nth 1 timestamp))))))
1260         (save-excursion
1261           (or (eq timestamp 'none)
1262               (set (intern (format "%s-active-timestamp" backend))
1263                    file-time))
1264           (funcall (intern (format "%s-request-list" backend)))))
1265     t))
1266
1267 (defun nnmail-message-id ()
1268   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1269
1270 ;;;
1271 ;;; nnmail duplicate handling
1272 ;;;
1273
1274 (defvar nnmail-cache-buffer nil)
1275
1276 (defun nnmail-cache-open ()
1277   (if (or (not nnmail-treat-duplicates)
1278           (and nnmail-cache-buffer
1279                (buffer-name nnmail-cache-buffer)))
1280       ()                                ; The buffer is open.
1281     (save-excursion
1282       (set-buffer
1283        (setq nnmail-cache-buffer
1284              (get-buffer-create " *nnmail message-id cache*")))
1285       (when (file-exists-p nnmail-message-id-cache-file)
1286         (nnheader-insert-file-contents nnmail-message-id-cache-file))
1287       (set-buffer-modified-p nil)
1288       (current-buffer))))
1289
1290 (defun nnmail-cache-close ()
1291   (when (and nnmail-cache-buffer
1292              nnmail-treat-duplicates
1293              (buffer-name nnmail-cache-buffer)
1294              (buffer-modified-p nnmail-cache-buffer))
1295     (save-excursion
1296       (set-buffer nnmail-cache-buffer)
1297       ;; Weed out the excess number of Message-IDs.
1298       (goto-char (point-max))
1299       (when (search-backward "\n" nil t nnmail-message-id-cache-length)
1300         (progn
1301           (beginning-of-line)
1302           (delete-region (point-min) (point))))
1303       ;; Save the buffer.
1304       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1305           (make-directory (file-name-directory nnmail-message-id-cache-file)
1306                           t))
1307       (nnmail-write-region (point-min) (point-max)
1308                            nnmail-message-id-cache-file nil 'silent)
1309       (set-buffer-modified-p nil)
1310       (setq nnmail-cache-buffer nil)
1311       (kill-buffer (current-buffer)))))
1312
1313 (defun nnmail-cache-insert (id)
1314   (when nnmail-treat-duplicates
1315     (unless (gnus-buffer-live-p nnmail-cache-buffer)
1316       (nnmail-cache-open))
1317     (save-excursion
1318       (set-buffer nnmail-cache-buffer)
1319       (goto-char (point-max))
1320       (insert id "\n"))))
1321
1322 (defun nnmail-cache-id-exists-p (id)
1323   (when nnmail-treat-duplicates
1324     (save-excursion
1325       (set-buffer nnmail-cache-buffer)
1326       (goto-char (point-max))
1327       (search-backward id nil t))))
1328
1329 (defun nnmail-fetch-field (header)
1330   (save-excursion
1331     (save-restriction
1332       (message-narrow-to-head)
1333       (message-fetch-field header))))
1334
1335 (defun nnmail-check-duplication (message-id func artnum-func)
1336   (run-hooks 'nnmail-prepare-incoming-message-hook)
1337   ;; If this is a duplicate message, then we do not save it.
1338   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1339          (case-fold-search t)
1340          (action (when duplication
1341                    (cond
1342                     ((memq nnmail-treat-duplicates '(warn delete))
1343                      nnmail-treat-duplicates)
1344                     ((nnheader-functionp nnmail-treat-duplicates)
1345                      (funcall nnmail-treat-duplicates message-id))
1346                     (t
1347                      nnmail-treat-duplicates))))
1348          group-art)
1349     ;; We insert a line that says what the mail source is.
1350     (let ((case-fold-search t))
1351       (goto-char (point-min))
1352       (re-search-forward "^message-id[ \t]*:" nil t)
1353       (beginning-of-line)
1354       (insert (format "X-Gnus-Mail-Source: %s\n" mail-source-string)))
1355
1356     ;; Let the backend save the article (or not).
1357     (cond
1358      ((not duplication)
1359       (funcall func (setq group-art
1360                           (nreverse (nnmail-article-group artnum-func))))
1361       (nnmail-cache-insert message-id))
1362      ((eq action 'delete)
1363       (setq group-art nil))
1364      ((eq action 'warn)
1365       ;; We insert a warning.
1366       (let ((case-fold-search t))
1367         (goto-char (point-min))
1368         (re-search-forward "^message-id[ \t]*:" nil t)
1369         (beginning-of-line)
1370         (insert
1371          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1372         (funcall func (setq group-art
1373                             (nreverse (nnmail-article-group artnum-func))))))
1374      (t
1375       (funcall func (setq group-art
1376                           (nreverse (nnmail-article-group artnum-func))))))
1377     ;; Add the group-art list to the history list.
1378     (if group-art
1379         (push group-art nnmail-split-history)
1380       (delete-region (point-min) (point-max)))))
1381
1382 ;;; Get new mail.
1383
1384 (defvar nnmail-fetched-sources nil)
1385
1386 (defun nnmail-get-value (&rest args)
1387   (let ((sym (intern (apply 'format args))))
1388     (when (boundp sym)
1389       (symbol-value sym))))
1390
1391 (defun nnmail-get-new-mail (method exit-func temp
1392                                    &optional group spool-func)
1393   "Read new incoming mail."
1394   (let* ((sources (or mail-sources
1395                       (if (listp nnmail-spool-file) nnmail-spool-file
1396                         (list nnmail-spool-file))))
1397          (group-in group)
1398          (i 0)
1399          (new 0)
1400          (total 0)
1401          incoming incomings source)
1402     (when (and (nnmail-get-value "%s-get-new-mail" method)
1403                nnmail-spool-file)
1404       ;; We first activate all the groups.
1405       (nnmail-activate method)
1406       ;; Allow the user to hook.
1407       (run-hooks 'nnmail-pre-get-new-mail-hook)
1408       ;; Open the message-id cache.
1409       (nnmail-cache-open)
1410       ;; The we go through all the existing mail source specification
1411       ;; and fetch the mail from each.
1412       (while (setq source (pop sources))
1413         ;; Be compatible with old values.
1414         (cond
1415          ((stringp source)
1416           (setq source
1417                 (cond
1418                  ((string-match "^po:" source)
1419                   (list 'pop :user (substring source (match-end 0))))
1420                  ((file-directory-p source)
1421                   (list 'directory :path source))
1422                  (t
1423                   (list 'file :path source)))))
1424          ((eq source 'procmail)
1425           (message "Invalid value for nnmail-spool-file: `procmail'")
1426           nil))
1427         ;; Hack to only fetch the contents of a single group's spool file.
1428         (when (and (eq (car source) 'directory)
1429                    group)
1430           (mail-source-bind (directory source)
1431             (setq source (append source
1432                                  (list
1433                                   :predicate
1434                                   `(lambda (file)
1435                                      (string-match
1436                                       ,(concat
1437                                         (regexp-quote (concat group suffix))
1438                                         "$")
1439                                       file)))))))
1440         (when nnmail-fetched-sources
1441           (if (member source nnmail-fetched-sources)
1442               (setq source nil)
1443             (push source nnmail-fetched-sources)))
1444         (when source
1445           (nnheader-message 4 "%s: Reading incoming mail from %s..."
1446                             method (car source))
1447           (when (setq new
1448                       (mail-source-fetch
1449                        source
1450                        `(lambda (file orig-file)
1451                           (nnmail-split-incoming
1452                            file ',(intern (format "%s-save-mail" method))
1453                            ',spool-func
1454                            (nnmail-get-split-group orig-file source)
1455                            ',(intern (format "%s-active-number" method))))))
1456             (incf total new)
1457             (incf i))))
1458       ;; If we did indeed read any incoming spools, we save all info.
1459       (if (zerop total)
1460           (nnheader-message 4 "%s: Reading incoming mail (no new mail)...done"
1461                             method (car source))
1462         (nnmail-save-active
1463          (nnmail-get-value "%s-group-alist" method)
1464          (nnmail-get-value "%s-active-file" method))
1465         (when exit-func
1466           (funcall exit-func))
1467         (run-hooks 'nnmail-read-incoming-hook)
1468         (nnheader-message 4 "%s: Reading incoming mail (%d new)...done" method
1469                           total))
1470       ;; Close the message-id cache.
1471       (nnmail-cache-close)
1472       ;; Allow the user to hook.
1473       (run-hooks 'nnmail-post-get-new-mail-hook))))
1474
1475 (defun nnmail-expired-article-p (group time force &optional inhibit)
1476   "Say whether an article that is TIME old in GROUP should be expired."
1477   (if force
1478       t
1479     (let ((days (or (and nnmail-expiry-wait-function
1480                          (funcall nnmail-expiry-wait-function group))
1481                     nnmail-expiry-wait)))
1482       (cond ((or (eq days 'never)
1483                  (and (not force)
1484                       inhibit))
1485              ;; This isn't an expirable group.
1486              nil)
1487             ((eq days 'immediate)
1488              ;; We expire all articles on sight.
1489              t)
1490             ((equal time '(0 0))
1491              ;; This is an ange-ftp group, and we don't have any dates.
1492              nil)
1493             ((numberp days)
1494              (setq days (days-to-time days))
1495              ;; Compare the time with the current time.
1496              (ignore-errors (time-less-p days (time-since time))))))))
1497
1498 (defun nnmail-check-syntax ()
1499   "Check (and modify) the syntax of the message in the current buffer."
1500   (save-restriction
1501     (message-narrow-to-head)
1502     (let ((case-fold-search t))
1503       (unless (re-search-forward "^Message-ID[ \t]*:" nil t)
1504         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1505
1506 (defun nnmail-write-region (start end filename &optional append visit lockname)
1507   "Do a `write-region', and then set the file modes."
1508   (let ((pathname-coding-system nnmail-pathname-coding-system))
1509     
1510     (write-region-as-coding-system
1511      nnmail-file-coding-system start end filename append visit lockname)
1512     (set-file-modes filename nnmail-default-file-modes)))
1513
1514 ;;;
1515 ;;; Status functions
1516 ;;;
1517
1518 (defun nnmail-replace-status (name value)
1519   "Make status NAME and VALUE part of the current status line."
1520   (save-restriction
1521     (message-narrow-to-head)
1522     (let ((status (nnmail-decode-status)))
1523       (setq status (delq (member name status) status))
1524       (when value
1525         (push (cons name value) status))
1526       (message-remove-header "status")
1527       (goto-char (point-max))
1528       (insert "Status: " (nnmail-encode-status status) "\n"))))
1529
1530 (defun nnmail-decode-status ()
1531   "Return a status-value alist from STATUS."
1532   (goto-char (point-min))
1533   (when (re-search-forward "^Status: " nil t)
1534     (let (name value status)
1535       (save-restriction
1536         ;; Narrow to the status.
1537         (narrow-to-region
1538          (point)
1539          (if (re-search-forward "^[^ \t]" nil t)
1540              (1- (point))
1541            (point-max)))
1542         ;; Go through all elements and add them to the list.
1543         (goto-char (point-min))
1544         (while (re-search-forward "[^ \t=]+" nil t)
1545           (setq name (match-string 0))
1546           (if (not (eq (char-after) ?=))
1547               ;; Implied "yes".
1548               (setq value "yes")
1549             (forward-char 1)
1550             (if (not (eq (char-after) ?\"))
1551                 (if (not (looking-at "[^ \t]"))
1552                     ;; Implied "no".
1553                     (setq value "no")
1554                   ;; Unquoted value.
1555                   (setq value (match-string 0))
1556                   (goto-char (match-end 0)))
1557               ;; Quoted value.
1558               (setq value (read (current-buffer)))))
1559           (push (cons name value) status)))
1560       status)))
1561
1562 (defun nnmail-encode-status (status)
1563   "Return a status string from STATUS."
1564   (mapconcat
1565    (lambda (elem)
1566      (concat
1567       (car elem) "="
1568       (if (string-match "[ \t]" (cdr elem))
1569           (prin1-to-string (cdr elem))
1570         (cdr elem))))
1571    status " "))
1572
1573 (defun nnmail-split-history ()
1574   "Generate an overview of where the last mail split put articles."
1575   (interactive)
1576   (unless nnmail-split-history
1577     (error "No current split history"))
1578   (with-output-to-temp-buffer "*nnmail split history*"
1579     (let ((history nnmail-split-history)
1580           elem)
1581       (while (setq elem (pop history))
1582         (princ (mapconcat (lambda (ga)
1583                             (concat (car ga) ":" (int-to-string (cdr ga))))
1584                           elem
1585                           ", "))
1586         (princ "\n")))))
1587
1588 (defun nnmail-purge-split-history (group)
1589   "Remove all instances of GROUP from `nnmail-split-history'."
1590   (let ((history nnmail-split-history))
1591     (while history
1592       (setcar history (gnus-delete-if (lambda (e) (string= (car e) group))
1593                                       (car history)))
1594       (pop history))
1595     (setq nnmail-split-history (delq nil nnmail-split-history))))
1596
1597 (defun nnmail-new-mail-p (group)
1598   "Say whether GROUP has new mail."
1599   (let ((his nnmail-split-history)
1600         found)
1601     (while his
1602       (when (assoc group (pop his))
1603         (setq found t
1604               his nil)))
1605     found))
1606
1607 (defun nnmail-new-mail-numbers (group)
1608   "Say how many articles has been incorporated to GROUP."
1609   (let ((his (apply 'append nnmail-split-history))
1610         numbers)
1611     (while his
1612       (when (string= group (caar his))
1613         (push (cdar his) numbers))
1614       (setq his (cdr his)))
1615     numbers))
1616
1617 (defun nnmail-within-headers-p ()
1618   "Check to see if point is within the headers of a unix mail message.
1619 Doesn't change point."
1620   (let ((pos (point)))
1621     (save-excursion
1622       (and (nnmail-search-unix-mail-delim-backward)
1623            (not (search-forward "\n\n" pos t))))))
1624
1625 (run-hooks 'nnmail-load-hook)
1626
1627 (provide 'nnmail)
1628
1629 ;;; nnmail.el ends here