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