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