2001-08-01 Gerd Moellmann <gerd@gnu.org>
[gnus] / 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 (require 'mm-util)
37
38 (eval-and-compile
39   (autoload 'gnus-error "gnus-util")
40   (autoload 'gnus-buffer-live-p "gnus-util")
41   (autoload 'gnus-add-buffer "gnus"))
42
43 (defgroup nnmail nil
44   "Reading mail with Gnus."
45   :group 'gnus)
46
47 (defgroup nnmail-retrieve nil
48   "Retrieving new mail."
49   :group 'nnmail)
50
51 (defgroup nnmail-prepare nil
52   "Preparing (or mangling) new mail after retrival."
53   :group 'nnmail)
54
55 (defgroup nnmail-duplicate nil
56   "Handling of duplicate mail messages."
57   :group 'nnmail)
58
59 (defgroup nnmail-split nil
60   "Organizing the incomming mail in folders."
61   :group 'nnmail)
62
63 (defgroup nnmail-files nil
64   "Mail files."
65   :group 'gnus-files
66   :group 'nnmail)
67
68 (defgroup nnmail-expire nil
69   "Expiring old mail."
70   :group 'nnmail)
71
72 (defgroup nnmail-procmail nil
73   "Interfacing with procmail and other mail agents."
74   :group 'nnmail)
75
76 (defgroup nnmail-various nil
77   "Various mail options."
78   :group 'nnmail)
79
80 (defcustom nnmail-split-methods
81   '(("mail.misc" ""))
82   "*Incoming mail will be split according to this variable.
83
84 If you'd like, for instance, one mail group for mail from the
85 \"4ad-l\" mailing list, one group for junk mail and one for everything
86 else, you could do something like this:
87
88  (setq nnmail-split-methods
89        '((\"mail.4ad\" \"From:.*4ad\")
90          (\"mail.junk\" \"From:.*Lars\\\\|Subject:.*buy\")
91          (\"mail.misc\" \"\")))
92
93 As you can see, this variable is a list of lists, where the first
94 element in each \"rule\" is the name of the group (which, by the way,
95 does not have to be called anything beginning with \"mail\",
96 \"yonka.zow\" is a fine, fine name), and the second is a regexp that
97 nnmail will try to match on the header to find a fit.
98
99 The second element can also be a function.  In that case, it will be
100 called narrowed to the headers with the first element of the rule as
101 the argument.  It should return a non-nil value if it thinks that the
102 mail belongs in that group.
103
104 The last element should always have \"\" as the regexp.
105
106 This variable can also have a function as its value."
107   :group 'nnmail-split
108   :type '(choice (repeat :tag "Alist" (group (string :tag "Name") regexp))
109                  (function-item nnmail-split-fancy)
110                  (function :tag "Other")))
111
112 ;; Suggested by Erik Selberg <speed@cs.washington.edu>.
113 (defcustom nnmail-crosspost t
114   "If non-nil, do crossposting if several split methods match the mail.
115 If nil, the first match found will be used."
116   :group 'nnmail-split
117   :type 'boolean)
118
119 (defcustom nnmail-split-fancy-with-parent-ignore-groups nil
120   "Regexp that matches group names to be ignored when applying
121 `nnmail-split-fancy-with-parent'.  This can also be a list of regexps."
122   :group 'nnmail-split
123   :type '(choice (const :tag "none" nil)
124                  (regexp :value ".*")
125                  (repeat :value (".*") regexp)))
126
127 ;; Added by gord@enci.ucalgary.ca (Gordon Matzigkeit).
128 (defcustom nnmail-keep-last-article nil
129   "If non-nil, nnmail will never delete/move a group's last article.
130 It can be marked expirable, so it will be deleted when it is no longer last.
131
132 You may need to set this variable if other programs are putting
133 new mail into folder numbers that Gnus has marked as expired."
134   :group 'nnmail-procmail
135   :group 'nnmail-various
136   :type 'boolean)
137
138 (defcustom nnmail-use-long-file-names nil
139   "If non-nil the mail backends will use long file and directory names.
140 If nil, groups like \"mail.misc\" will end up in directories like
141 \"mail/misc/\"."
142   :group 'nnmail-files
143   :type 'boolean)
144
145 (defcustom nnmail-default-file-modes 384
146   "Set the mode bits of all new mail files to this integer."
147   :group 'nnmail-files
148   :type 'integer)
149
150 (defcustom nnmail-expiry-wait 7
151   "*Expirable articles that are older than this will be expired.
152 This variable can either be a number (which will be interpreted as a
153 number of days) -- this doesn't have to be an integer.  This variable
154 can also be `immediate' and `never'."
155   :group 'nnmail-expire
156   :type '(choice (const immediate)
157                  (number :tag "days")
158                  (const never)))
159
160 (defcustom nnmail-expiry-wait-function nil
161   "Variable that holds function to specify how old articles should be before they are expired.
162   The function will be called with the name of the group that the
163 expiry is to be performed in, and it should return an integer that
164 says how many days an article can be stored before it is considered
165 \"old\".  It can also return the values `never' and `immediate'.
166
167 Eg.:
168
169 \(setq nnmail-expiry-wait-function
170       (lambda (newsgroup)
171         (cond ((string-match \"private\" newsgroup) 31)
172               ((string-match \"junk\" newsgroup) 1)
173               ((string-match \"important\" newsgroup) 'never)
174               (t 7))))"
175   :group 'nnmail-expire
176   :type '(choice (const :tag "nnmail-expiry-wait" nil)
177                  (function :format "%v" nnmail-)))
178
179 (defcustom nnmail-expiry-target 'delete
180   "*Variable that says where expired messages should end up.
181 The default value is `delete' (which says to delete the messages),
182 but it can also be a string or a function.  If it is a string, expired
183 messages end up in that group.  If it is a function, the function is
184 called in a buffer narrowed to the message in question.  The function
185 receives one argument, the name of the group the message comes from.
186 The return value should be `delete' or a group name (a string)."
187   :version "21.1"
188   :group 'nnmail-expire
189   :type '(choice (const delete)
190                  (function :format "%v" nnmail-)
191                  string))
192
193 (defcustom nnmail-cache-accepted-message-ids nil
194   "If non-nil, put Message-IDs of Gcc'd articles into the duplicate cache.
195 If non-nil, also update the cache when copy or move articles."
196   :group 'nnmail
197   :type 'boolean)
198
199 (defcustom nnmail-spool-file '((file))
200   "*Where the mail backends will look for incoming mail.
201 This variable is a list of mail source specifiers.
202 This variable is obsolete; `mail-sources' should be used instead."
203   :group 'nnmail-files
204   :type 'sexp)
205
206 (defcustom nnmail-resplit-incoming nil
207   "*If non-nil, re-split incoming procmail sorted mail."
208   :group 'nnmail-procmail
209   :type 'boolean)
210
211 (defcustom nnmail-scan-directory-mail-source-once nil
212   "*If non-nil, scan all incoming procmail sorted mails once.
213 It scans low-level sorted spools even when not required."
214   :version "21.1"
215   :group 'nnmail-procmail
216   :type 'boolean)
217
218 (defcustom nnmail-delete-file-function 'delete-file
219   "Function called to delete files in some mail backends."
220   :group 'nnmail-files
221   :type 'function)
222
223 (defcustom nnmail-crosspost-link-function
224   (if (string-match "windows-nt\\|emx" (symbol-name system-type))
225       'copy-file
226     'add-name-to-file)
227   "*Function called to create a copy of a file.
228 This is `add-name-to-file' by default, which means that crossposts
229 will use hard links.  If your file system doesn't allow hard
230 links, you could set this variable to `copy-file' instead."
231   :group 'nnmail-files
232   :type '(radio (function-item add-name-to-file)
233                 (function-item copy-file)
234                 (function :tag "Other")))
235
236 (defcustom nnmail-read-incoming-hook
237   (if (eq system-type 'windows-nt)
238       '(nnheader-ms-strip-cr)
239     nil)
240   "*Hook that will be run after the incoming mail has been transferred.
241 The incoming mail is moved from the specified spool file (which normally is
242 something like \"/usr/spool/mail/$user\") to the user's home
243 directory.  This hook is called after the incoming mail box has been
244 emptied, and can be used to call any mail box programs you have
245 running (\"xwatch\", etc.)
246
247 Eg.
248
249 \(add-hook 'nnmail-read-incoming-hook
250           (lambda ()
251             (call-process \"/local/bin/mailsend\" nil nil nil
252                           \"read\" nnmail-spool-file)))
253
254 If you have xwatch running, this will alert it that mail has been
255 read.
256
257 If you use `display-time', you could use something like this:
258
259 \(add-hook 'nnmail-read-incoming-hook
260           (lambda ()
261             ;; Update the displayed time, since that will clear out
262             ;; the flag that says you have mail.
263             (when (eq (process-status \"display-time\") 'run)
264               (display-time-filter display-time-process \"\"))))"
265   :group 'nnmail-prepare
266   :type 'hook)
267
268 (defcustom nnmail-prepare-incoming-hook nil
269   "Hook called before treating incoming mail.
270 The hook is run in a buffer with all the new, incoming mail."
271   :group 'nnmail-prepare
272   :type 'hook)
273
274 (defcustom nnmail-prepare-incoming-header-hook nil
275   "Hook called narrowed to the headers of each message.
276 This can be used to remove excessive spaces (and stuff like
277 that) from the headers before splitting and saving the messages."
278   :group 'nnmail-prepare
279   :type 'hook)
280
281 (defcustom nnmail-prepare-incoming-message-hook nil
282   "Hook called narrowed to each message."
283   :group 'nnmail-prepare
284   :type 'hook)
285
286 (defcustom nnmail-list-identifiers nil
287   "Regexp that matches list identifiers to be removed.
288 This can also be a list of regexps."
289   :group 'nnmail-prepare
290   :type '(choice (const :tag "none" nil)
291                  (regexp :value ".*")
292                  (repeat :value (".*") regexp)))
293
294 (defcustom nnmail-pre-get-new-mail-hook nil
295   "Hook called just before starting to handle new incoming mail."
296   :group 'nnmail-retrieve
297   :type 'hook)
298
299 (defcustom nnmail-post-get-new-mail-hook nil
300   "Hook called just after finishing handling new incoming mail."
301   :group 'nnmail-retrieve
302   :type 'hook)
303
304 (defcustom nnmail-split-hook nil
305   "Hook called before deciding where to split an article.
306 The functions in this hook are free to modify the buffer
307 contents in any way they choose -- the buffer contents are
308 discarded after running the split process."
309   :group 'nnmail-split
310   :type 'hook)
311
312 (defcustom nnmail-large-newsgroup 50
313   "*The number of the articles which indicates a large newsgroup.
314 If the number of the articles is greater than the value, verbose
315 messages will be shown to indicate the current status."
316   :group 'nnmail-various
317   :type 'integer)
318
319 (defcustom nnmail-split-fancy "mail.misc"
320   "Incoming mail can be split according to this fancy variable.
321 To enable this, set `nnmail-split-methods' to `nnmail-split-fancy'.
322
323 The format of this variable is SPLIT, where SPLIT can be one of
324 the following:
325
326 GROUP: Mail will be stored in GROUP (a string).
327
328 \(FIELD VALUE [- RESTRICT [- RESTRICT [...]]] SPLIT): If the message
329   field FIELD (a regexp) contains VALUE (a regexp), store the messages
330   as specified by SPLIT.  If RESTRICT (a regexp) matches some string
331   after FIELD and before the end of the matched VALUE, return NIL,
332   otherwise process SPLIT.  Multiple RESTRICTs add up, further
333   restricting the possibility of processing SPLIT.
334
335 \(| SPLIT...): Process each SPLIT expression until one of them matches.
336   A SPLIT expression is said to match if it will cause the mail
337   message to be stored in one or more groups.
338
339 \(& SPLIT...): Process each SPLIT expression.
340
341 \(: FUNCTION optional args): Call FUNCTION with the optional args, in
342   the buffer containing the message headers.  The return value FUNCTION
343   should be a split, which is then recursively processed.
344
345 \(! FUNCTION SPLIT): Call FUNCTION with the result of SPLIT.  The
346   return value FUNCTION should be a split, which is then recursively
347   processed.
348
349 FIELD must match a complete field name.  VALUE must match a complete
350 word according to the `nnmail-split-fancy-syntax-table' syntax table.
351 You can use \".*\" in the regexps to match partial field names or words.
352
353 FIELD and VALUE can also be lisp symbols, in that case they are expanded
354 as specified in `nnmail-split-abbrev-alist'.
355
356 GROUP can contain \\& and \\N which will substitute from matching
357 \\(\\) patterns in the previous VALUE.
358
359 Example:
360
361 \(setq nnmail-split-methods 'nnmail-split-fancy
362       nnmail-split-fancy
363       ;; Messages from the mailer daemon are not crossposted to any of
364       ;; the ordinary groups.  Warnings are put in a separate group
365       ;; from real errors.
366       '(| (\"from\" mail (| (\"subject\" \"warn.*\" \"mail.warning\")
367                           \"mail.misc\"))
368           ;; Non-error messages are crossposted to all relevant
369           ;; groups, but we don't crosspost between the group for the
370           ;; (ding) list and the group for other (ding) related mail.
371           (& (| (any \"ding@ifi\\\\.uio\\\\.no\" \"ding.list\")
372                 (\"subject\" \"ding\" \"ding.misc\"))
373              ;; Other mailing lists...
374              (any \"procmail@informatik\\\\.rwth-aachen\\\\.de\" \"procmail.list\")
375              (any \"SmartList@informatik\\\\.rwth-aachen\\\\.de\" \"SmartList.list\")
376              ;; Both lists below have the same suffix, so prevent
377              ;; cross-posting to mkpkg.list of messages posted only to
378              ;; the bugs- list, but allow cross-posting when the
379              ;; message was really cross-posted.
380              (any \"bugs-mypackage@somewhere\" \"mypkg.bugs\")
381              (any \"mypackage@somewhere\" - \"bugs-mypackage\" \"mypkg.list\")
382              ;;
383              ;; People...
384              (any \"larsi@ifi\\\\.uio\\\\.no\" \"people.Lars Magne Ingebrigtsen\"))
385           ;; Unmatched mail goes to the catch all group.
386           \"misc.misc\"))"
387   :group 'nnmail-split
388   ;; Sigh!
389   :type 'sexp)
390
391 (defcustom nnmail-split-abbrev-alist
392   '((any . "from\\|to\\|cc\\|sender\\|apparently-to\\|resent-from\\|resent-to\\|resent-cc")
393     (mail . "mailer-daemon\\|postmaster\\|uucp")
394     (to . "to\\|cc\\|apparently-to\\|resent-to\\|resent-cc")
395     (from . "from\\|sender\\|resent-from")
396     (nato . "to\\|cc\\|resent-to\\|resent-cc")
397     (naany . "from\\|to\\|cc\\|sender\\|resent-from\\|resent-to\\|resent-cc"))
398   "*Alist of abbreviations allowed in `nnmail-split-fancy'."
399   :group 'nnmail-split
400   :type '(repeat (cons :format "%v" symbol regexp)))
401
402 (defcustom nnmail-message-id-cache-length 1000
403   "*The approximate number of Message-IDs nnmail will keep in its cache.
404 If this variable is nil, no checking on duplicate messages will be
405 performed."
406   :group 'nnmail-duplicate
407   :type '(choice (const :tag "disable" nil)
408                  (integer :format "%v")))
409
410 (defcustom nnmail-message-id-cache-file "~/.nnmail-cache"
411   "*The file name of the nnmail Message-ID cache."
412   :group 'nnmail-duplicate
413   :group 'nnmail-files
414   :type 'file)
415
416 (defcustom nnmail-treat-duplicates 'warn
417   "*If non-nil, nnmail keep a cache of Message-IDs to discover mail duplicates.
418 Three values are valid: nil, which means that nnmail is not to keep a
419 Message-ID cache; `warn', which means that nnmail should insert extra
420 headers to warn the user about the duplication (this is the default);
421 and `delete', which means that nnmail will delete duplicated mails.
422
423 This variable can also be a function.  It will be called from a buffer
424 narrowed to the article in question with the Message-ID as a
425 parameter.  It should return nil, `warn' or `delete'."
426   :group 'nnmail-duplicate
427   :type '(choice (const :tag "off" nil)
428                  (const warn)
429                  (const delete)))
430
431 (defcustom nnmail-extra-headers nil
432   "*Extra headers to parse."
433   :version "21.1"
434   :group 'nnmail
435   :type '(repeat symbol))
436
437 (defcustom nnmail-split-header-length-limit 512
438   "Header lines longer than this limit are excluded from the split function."
439   :version "21.1"
440   :group 'nnmail
441   :type 'integer)
442
443 ;;; Internal variables.
444
445 (defvar nnmail-article-buffer " *nnmail incoming*"
446   "The buffer used for splitting incoming mails.")
447
448 (defvar nnmail-split-history nil
449   "List of group/article elements that say where the previous split put messages.")
450
451 (defvar nnmail-split-fancy-syntax-table nil
452   "Syntax table used by `nnmail-split-fancy'.")
453 (unless (syntax-table-p nnmail-split-fancy-syntax-table)
454   (setq nnmail-split-fancy-syntax-table
455         (copy-syntax-table (standard-syntax-table)))
456   ;; support the %-hack
457   (modify-syntax-entry ?\% "." nnmail-split-fancy-syntax-table))
458
459 (defvar nnmail-prepare-save-mail-hook nil
460   "Hook called before saving mail.")
461
462 (defvar nnmail-split-tracing nil)
463 (defvar nnmail-split-trace nil)
464
465 \f
466
467 (defconst nnmail-version "nnmail 1.0"
468   "nnmail version.")
469
470 \f
471
472 (defun nnmail-request-post (&optional server)
473   (mail-send-and-exit nil))
474
475 (defvar nnmail-file-coding-system 'raw-text
476   "Coding system used in nnmail.")
477
478 (defvar nnmail-incoming-coding-system
479   mm-text-coding-system
480   "Coding system used in reading inbox")
481
482 (defvar nnmail-pathname-coding-system 'iso-8859-1
483   "*Coding system for pathname.")
484
485 (defun nnmail-find-file (file)
486   "Insert FILE in server buffer safely."
487   (set-buffer nntp-server-buffer)
488   (delete-region (point-min) (point-max))
489   (let ((format-alist nil)
490         (after-insert-file-functions nil))
491     (condition-case ()
492         (let ((coding-system-for-read nnmail-file-coding-system)
493               (auto-mode-alist (mm-auto-mode-alist))
494               (file-name-coding-system nnmail-pathname-coding-system))
495           (insert-file-contents file)
496           t)
497       (file-error nil))))
498
499 (defun nnmail-group-pathname (group dir &optional file)
500   "Make pathname for GROUP."
501   (concat
502    (let ((dir (file-name-as-directory (expand-file-name dir))))
503      (setq group (nnheader-replace-duplicate-chars-in-string
504                   (nnheader-replace-chars-in-string group ?/ ?_)
505                   ?. ?_))
506      (setq group (nnheader-translate-file-chars group))
507      ;; If this directory exists, we use it directly.
508      (file-name-as-directory
509       (if (or nnmail-use-long-file-names
510               (file-directory-p (concat dir group)))
511           (expand-file-name group dir)
512         ;; If not, we translate dots into slashes.
513         (expand-file-name
514          (mm-encode-coding-string
515           (nnheader-replace-chars-in-string group ?. ?/)
516           nnmail-pathname-coding-system)
517          dir))))
518    (or file "")))
519
520 (defun nnmail-get-active ()
521   "Returns an assoc of group names and active ranges.
522 nn*-request-list should have been called before calling this function."
523   ;; Go through all groups from the active list.
524   (save-excursion
525     (set-buffer nntp-server-buffer)
526     (nnmail-parse-active)))
527
528 (defun nnmail-parse-active ()
529   "Parse the active file in the current buffer and return an alist."
530   (goto-char (point-min))
531   (unless (re-search-forward "[\\\"]" nil t)
532     (goto-char (point-max))
533     (while (re-search-backward "[][';?()#]" nil t)
534       (insert ?\\)))
535   (goto-char (point-min))
536   (let ((buffer (current-buffer))
537         group-assoc group max min)
538     (while (not (eobp))
539       (condition-case err
540           (progn
541             (narrow-to-region (point) (gnus-point-at-eol))
542             (setq group (read buffer))
543             (unless (stringp group)
544               (setq group (symbol-name group)))
545             (if (and (numberp (setq max (read buffer)))
546                      (numberp (setq min (read buffer))))
547                 (push (list group (cons min max))
548                       group-assoc)))
549         (error nil))
550       (widen)
551       (forward-line 1))
552     group-assoc))
553
554 (defvar nnmail-active-file-coding-system 'raw-text
555   "*Coding system for active file.")
556
557 (defun nnmail-save-active (group-assoc file-name)
558   "Save GROUP-ASSOC in ACTIVE-FILE."
559   (let ((coding-system-for-write 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 ((coding-system-for-read nnmail-incoming-coding-system))
914         (mm-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                       (mm-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 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       (gnus-add-buffer)
1381       (when (file-exists-p nnmail-message-id-cache-file)
1382         (nnheader-insert-file-contents nnmail-message-id-cache-file))
1383       (set-buffer-modified-p nil)
1384       (current-buffer))))
1385
1386 (defun nnmail-cache-close ()
1387   (when (and nnmail-cache-buffer
1388              nnmail-treat-duplicates
1389              (buffer-name nnmail-cache-buffer)
1390              (buffer-modified-p nnmail-cache-buffer))
1391     (save-excursion
1392       (set-buffer nnmail-cache-buffer)
1393       ;; Weed out the excess number of Message-IDs.
1394       (goto-char (point-max))
1395       (when (search-backward "\n" nil t nnmail-message-id-cache-length)
1396         (progn
1397           (beginning-of-line)
1398           (delete-region (point-min) (point))))
1399       ;; Save the buffer.
1400       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1401           (make-directory (file-name-directory nnmail-message-id-cache-file)
1402                           t))
1403       (nnmail-write-region (point-min) (point-max)
1404                            nnmail-message-id-cache-file nil 'silent)
1405       (set-buffer-modified-p nil)
1406       (setq nnmail-cache-buffer nil)
1407       (kill-buffer (current-buffer)))))
1408
1409 ;; Compiler directives.
1410 (defvar group)
1411 (defvar group-art-list)
1412 (defvar group-art)
1413 (defun nnmail-cache-insert (id)
1414   (when nnmail-treat-duplicates
1415     ;; Store some information about the group this message is written
1416     ;; to.  This function might have been called from various places.
1417     ;; Sometimes, a function up in the calling sequence has an
1418     ;; argument GROUP which is bound to a string, the group name.  At
1419     ;; other times, there is a function up in the calling sequence
1420     ;; which has an argument GROUP-ART which is a list of pairs, and
1421     ;; the car of a pair is a group name.  Should we check that the
1422     ;; length of the list is equal to 1? -- kai
1423     (let ((g nil))
1424       (cond ((and (boundp 'group) group)
1425              (setq g group))
1426             ((and (boundp 'group-art-list) group-art-list
1427                   (listp group-art-list))
1428              (setq g (caar group-art-list)))
1429             ((and (boundp 'group-art) group-art (listp group-art))
1430              (setq g (caar group-art)))
1431             (t (setq g "")))
1432       (unless (gnus-buffer-live-p nnmail-cache-buffer)
1433         (nnmail-cache-open))
1434       (save-excursion
1435         (set-buffer nnmail-cache-buffer)
1436         (goto-char (point-max))
1437         (if (and g (not (string= "" g))
1438                  (gnus-methods-equal-p gnus-command-method
1439                                        (nnmail-cache-primary-mail-backend)))
1440             (insert id "\t" g "\n")
1441           (insert id "\n"))))))
1442
1443 (defun nnmail-cache-primary-mail-backend ()
1444   (let ((be-list (cons gnus-select-method gnus-secondary-select-methods))
1445         (be nil)
1446         (res nil))
1447     (while (and (null res) be-list)
1448       (setq be (car be-list))
1449       (setq be-list (cdr be-list))
1450       (when (and (gnus-method-option-p be 'respool)
1451                  (eval (intern (format "%s-get-new-mail" (car be)))))
1452         (setq res be)))
1453     res))
1454
1455 ;; Fetch the group name corresponding to the message id stored in the
1456 ;; cache.
1457 (defun nnmail-cache-fetch-group (id)
1458   (when (and nnmail-treat-duplicates nnmail-cache-buffer)
1459     (save-excursion
1460       (set-buffer nnmail-cache-buffer)
1461       (goto-char (point-max))
1462       (when (search-backward id nil t)
1463         (beginning-of-line)
1464         (skip-chars-forward "^\n\r\t")
1465         (unless (eolp)
1466           (forward-char 1)
1467           (buffer-substring (point)
1468                             (progn (end-of-line) (point))))))))
1469
1470 ;; Function for nnmail-split-fancy: look up all references in the
1471 ;; cache and if a match is found, return that group.
1472 (defun nnmail-split-fancy-with-parent ()
1473   "Split this message into the same group as its parent.
1474 This function can be used as an entry in `nnmail-split-fancy', for
1475 example like this: (: nnmail-split-fancy)
1476 For a message to be split, it looks for the parent message in the
1477 References or In-Reply-To header and then looks in the message id
1478 cache file (given by the variable `nnmail-message-id-cache-file') to
1479 see which group that message was put in.  This group is returned.
1480
1481 See the Info node `(gnus)Fancy Mail Splitting' for more details."
1482   (let* ((refstr (or (message-fetch-field "references")
1483                      (message-fetch-field "in-reply-to")))
1484          (references nil)
1485          (res nil)
1486          (regexp (if (consp nnmail-split-fancy-with-parent-ignore-groups)
1487                      (mapconcat 'nnmail-split-fancy-with-parent-ignore-groups " *\\|")
1488                    nnmail-split-fancy-with-parent-ignore-groups)))
1489     (when refstr
1490       (setq references (nreverse (gnus-split-references refstr)))
1491       (unless (gnus-buffer-live-p nnmail-cache-buffer)
1492         (nnmail-cache-open))
1493       (mapcar (lambda (x)
1494                 (setq res (or (nnmail-cache-fetch-group x) res))
1495                 (when (or (string= "drafts" res)
1496                           (and regexp (string-match regexp res)))
1497                   (setq res nil)))
1498               references)
1499       res)))
1500
1501 (defun nnmail-cache-id-exists-p (id)
1502   (when nnmail-treat-duplicates
1503     (save-excursion
1504       (set-buffer nnmail-cache-buffer)
1505       (goto-char (point-max))
1506       (search-backward id nil t))))
1507
1508 (defun nnmail-fetch-field (header)
1509   (save-excursion
1510     (save-restriction
1511       (message-narrow-to-head)
1512       (message-fetch-field header))))
1513
1514 (defun nnmail-check-duplication (message-id func artnum-func)
1515   (run-hooks 'nnmail-prepare-incoming-message-hook)
1516   ;; If this is a duplicate message, then we do not save it.
1517   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1518          (case-fold-search t)
1519          (action (when duplication
1520                    (cond
1521                     ((memq nnmail-treat-duplicates '(warn delete))
1522                      nnmail-treat-duplicates)
1523                     ((nnheader-functionp nnmail-treat-duplicates)
1524                      (funcall nnmail-treat-duplicates message-id))
1525                     (t
1526                      nnmail-treat-duplicates))))
1527          group-art)
1528     ;; We insert a line that says what the mail source is.
1529     (let ((case-fold-search t))
1530       (goto-char (point-min))
1531       (re-search-forward "^message-id[ \t]*:" nil t)
1532       (beginning-of-line)
1533       (insert (format "X-Gnus-Mail-Source: %s\n" mail-source-string)))
1534
1535     ;; Let the backend save the article (or not).
1536     (cond
1537      ((not duplication)
1538       (funcall func (setq group-art
1539                           (nreverse (nnmail-article-group artnum-func))))
1540       (nnmail-cache-insert message-id))
1541      ((eq action 'delete)
1542       (setq group-art nil))
1543      ((eq action 'warn)
1544       ;; We insert a warning.
1545       (let ((case-fold-search t))
1546         (goto-char (point-min))
1547         (re-search-forward "^message-id[ \t]*:" nil t)
1548         (beginning-of-line)
1549         (insert
1550          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1551         (funcall func (setq group-art
1552                             (nreverse (nnmail-article-group artnum-func))))))
1553      (t
1554       (funcall func (setq group-art
1555                           (nreverse (nnmail-article-group artnum-func))))))
1556     ;; Add the group-art list to the history list.
1557     (if group-art
1558         (push group-art nnmail-split-history)
1559       (delete-region (point-min) (point-max)))))
1560
1561 ;;; Get new mail.
1562
1563 (defvar nnmail-fetched-sources nil)
1564
1565 (defun nnmail-get-value (&rest args)
1566   (let ((sym (intern (apply 'format args))))
1567     (when (boundp sym)
1568       (symbol-value sym))))
1569
1570 (defun nnmail-get-new-mail (method exit-func temp
1571                                    &optional group spool-func)
1572   "Read new incoming mail."
1573   (let* ((sources (or mail-sources
1574                       (if (listp nnmail-spool-file) nnmail-spool-file
1575                         (list nnmail-spool-file))))
1576          fetching-sources
1577          (group-in group)
1578          (i 0)
1579          (new 0)
1580          (total 0)
1581          incoming incomings source)
1582     (when (and (nnmail-get-value "%s-get-new-mail" method)
1583                sources)
1584       (while (setq source (pop sources))
1585         ;; Be compatible with old values.
1586         (cond
1587          ((stringp source)
1588           (setq source
1589                 (cond
1590                  ((string-match "^po:" source)
1591                   (list 'pop :user (substring source (match-end 0))))
1592                  ((file-directory-p source)
1593                   (list 'directory :path source))
1594                  (t
1595                   (list 'file :path source)))))
1596          ((eq source 'procmail)
1597           (message "Invalid value for nnmail-spool-file: `procmail'")
1598           nil))
1599         ;; Hack to only fetch the contents of a single group's spool file.
1600         (when (and (eq (car source) 'directory)
1601                    (null nnmail-scan-directory-mail-source-once)
1602                    group)
1603           (mail-source-bind (directory source)
1604             (setq source (append source
1605                                  (list
1606                                   :predicate
1607                                   (gnus-byte-compile
1608                                    `(lambda (file)
1609                                       (string-equal
1610                                        ,(concat group suffix)
1611                                        (file-name-nondirectory file)))))))))
1612         (when nnmail-fetched-sources
1613           (if (member source nnmail-fetched-sources)
1614               (setq source nil)
1615             (push source nnmail-fetched-sources)
1616             (push source fetching-sources)))))
1617     (when fetching-sources
1618       ;; We first activate all the groups.
1619       (nnmail-activate method)
1620       ;; Allow the user to hook.
1621       (run-hooks 'nnmail-pre-get-new-mail-hook)
1622       ;; Open the message-id cache.
1623       (nnmail-cache-open)
1624       ;; The we go through all the existing mail source specification
1625       ;; and fetch the mail from each.
1626       (while (setq source (pop fetching-sources))
1627         (nnheader-message 4 "%s: Reading incoming mail from %s..."
1628                           method (car source))
1629         (when (setq new
1630                     (mail-source-fetch
1631                      source
1632                      (gnus-byte-compile
1633                       `(lambda (file orig-file)
1634                          (nnmail-split-incoming
1635                           file ',(intern (format "%s-save-mail" method))
1636                           ',spool-func
1637                           (if (equal file orig-file)
1638                               nil
1639                             (nnmail-get-split-group orig-file ',source))
1640                           ',(intern (format "%s-active-number" method)))))))
1641           (incf total new)
1642           (incf i)))
1643       ;; If we did indeed read any incoming spools, we save all info.
1644       (if (zerop total)
1645           (nnheader-message 4 "%s: Reading incoming mail (no new mail)...done"
1646                             method (car source))
1647         (nnmail-save-active
1648          (nnmail-get-value "%s-group-alist" method)
1649          (nnmail-get-value "%s-active-file" method))
1650         (when exit-func
1651           (funcall exit-func))
1652         (run-hooks 'nnmail-read-incoming-hook)
1653         (nnheader-message 4 "%s: Reading incoming mail (%d new)...done" method
1654                           total))
1655       ;; Close the message-id cache.
1656       (nnmail-cache-close)
1657       ;; Allow the user to hook.
1658       (run-hooks 'nnmail-post-get-new-mail-hook))))
1659
1660 (defun nnmail-expired-article-p (group time force &optional inhibit)
1661   "Say whether an article that is TIME old in GROUP should be expired."
1662   (if force
1663       t
1664     (let ((days (or (and nnmail-expiry-wait-function
1665                          (funcall nnmail-expiry-wait-function group))
1666                     nnmail-expiry-wait)))
1667       (cond ((or (eq days 'never)
1668                  (and (not force)
1669                       inhibit))
1670              ;; This isn't an expirable group.
1671              nil)
1672             ((eq days 'immediate)
1673              ;; We expire all articles on sight.
1674              t)
1675             ((equal time '(0 0))
1676             ;; This is an ange-ftp group, and we don't have any dates.
1677              nil)
1678             ((numberp days)
1679              (setq days (days-to-time days))
1680              ;; Compare the time with the current time.
1681              (ignore-errors (time-less-p days (time-since time))))))))
1682
1683 (defun nnmail-expiry-target-group (target group)
1684   (let (nnmail-cache-accepted-message-ids)
1685     ;; Don't enter Message-IDs into cache.
1686     ;; Let users hack it in TARGET function.
1687     (when (nnheader-functionp target)
1688       (setq target (funcall target group)))
1689     (unless (eq target 'delete)
1690       (gnus-request-accept-article target nil nil t))))
1691
1692 (defun nnmail-check-syntax ()
1693   "Check (and modify) the syntax of the message in the current buffer."
1694   (save-restriction
1695     (message-narrow-to-head)
1696     (let ((case-fold-search t))
1697       (unless (re-search-forward "^Message-ID[ \t]*:" nil t)
1698         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1699
1700 (defun nnmail-write-region (start end filename &optional append visit lockname)
1701   "Do a `write-region', and then set the file modes."
1702   (let ((coding-system-for-write nnmail-file-coding-system)
1703         (file-name-coding-system nnmail-pathname-coding-system))
1704     (write-region 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-within-headers-p ()
1803   "Check to see if point is within the headers of a unix mail message.
1804 Doesn't change point."
1805   (let ((pos (point)))
1806     (save-excursion
1807       (and (nnmail-search-unix-mail-delim-backward)
1808            (not (search-forward "\n\n" pos t))))))
1809
1810 (run-hooks 'nnmail-load-hook)
1811
1812 (provide 'nnmail)
1813
1814 ;;; nnmail.el ends here