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