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