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