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