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