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