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