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