* nnmail.el (nnmail-do-request-post): Util function to be used by
[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-do-request-post (accept-func &optional server)
1135   "Utility function to directly post a message to an nnmail-derived group.
1136 Calls ACCEPT-FUNC (which should be `nnchoke-request-accept-article')
1137 to actually put the message in the right group."
1138   (let ((success t))
1139     (dolist (mbx (message-unquote-tokens
1140                   (message-tokenize-header
1141                    (message-fetch-field "Newsgroups") ", ")) success)
1142       (let ((to-newsgroup (gnus-group-prefixed-name mbx gnus-command-method)))
1143         (or (gnus-active to-newsgroup)
1144             (gnus-activate-group to-newsgroup)
1145             (if (gnus-y-or-n-p (format "No such group: %s.  Create it? "
1146                                        to-newsgroup))
1147                 (or (and (gnus-request-create-group
1148                           to-newsgroup gnus-command-method)
1149                          (gnus-activate-group to-newsgroup nil nil
1150                                               gnus-command-method))
1151                     (error "Couldn't create group %s" to-newsgroup)))
1152             (error "No such group: %s" to-newsgroup))
1153         (unless (funcall accept-func mbx (nth 1 gnus-command-method))
1154           (setq success nil))))))
1155
1156 (defun nnmail-split-fancy ()
1157   "Fancy splitting method.
1158 See the documentation for the variable `nnmail-split-fancy' for documentation."
1159   (let ((syntab (syntax-table)))
1160     (unwind-protect
1161         (progn
1162           (set-syntax-table nnmail-split-fancy-syntax-table)
1163           (nnmail-split-it nnmail-split-fancy))
1164       (set-syntax-table syntab))))
1165
1166 (defvar nnmail-split-cache nil)
1167 ;; Alist of split expressions their equivalent regexps.
1168
1169 (defun nnmail-split-it (split)
1170   ;; Return a list of groups matching SPLIT.
1171   (let (cached-pair)
1172     (cond
1173      ;; nil split
1174      ((null split)
1175       nil)
1176
1177      ;; A group name.  Do the \& and \N subs into the string.
1178      ((stringp split)
1179       (when nnmail-split-tracing
1180         (push (format "\"%s\"" split) nnmail-split-trace))
1181       (list (nnmail-expand-newtext split)))
1182
1183      ;; Junk the message.
1184      ((eq split 'junk)
1185       (when nnmail-split-tracing
1186         (push "junk" nnmail-split-trace))
1187       (list 'junk))
1188
1189      ;; Builtin & operation.
1190      ((eq (car split) '&)
1191       (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
1192
1193      ;; Builtin | operation.
1194      ((eq (car split) '|)
1195       (let (done)
1196         (while (and (not done) (cdr split))
1197           (setq split (cdr split)
1198                 done (nnmail-split-it (car split))))
1199         done))
1200
1201      ;; Builtin : operation.
1202      ((eq (car split) ':)
1203       (nnmail-split-it (save-excursion (eval (cdr split)))))
1204
1205      ;; Builtin ! operation.
1206      ((eq (car split) '!)
1207       (funcall (cadr split) (nnmail-split-it (caddr split))))
1208
1209      ;; Check the cache for the regexp for this split.
1210      ((setq cached-pair (assq split nnmail-split-cache))
1211       (let (split-result
1212             (end-point (point-max))
1213             (value (nth 1 split)))
1214         (if (symbolp value)
1215             (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1216         (while (and (goto-char end-point)
1217                     (re-search-backward (cdr cached-pair) nil t))
1218           (when nnmail-split-tracing
1219             (push (cdr cached-pair) nnmail-split-trace))
1220           (let ((split-rest (cddr split))
1221                 (end (match-end 0))
1222                 ;; The searched regexp is \(\(FIELD\).*\)\(VALUE\).  So,
1223                 ;; start-of-value is the the point just before the
1224                 ;; beginning of the value, whereas after-header-name is
1225                 ;; the point just after the field name.
1226                 (start-of-value (match-end 1))
1227                 (after-header-name (match-end 2)))
1228             ;; Start the next search just before the beginning of the
1229             ;; VALUE match.
1230             (setq end-point (1- start-of-value))
1231             ;; Handle - RESTRICTs
1232             (while (eq (car split-rest) '-)
1233               ;; RESTRICT must start after-header-name and
1234               ;; end after start-of-value, so that, for
1235               ;; (any "foo" - "x-foo" "foo.list")
1236               ;; we do not exclude foo.list just because
1237               ;; the header is: ``To: x-foo, foo''
1238               (goto-char end)
1239               (if (and (re-search-backward (cadr split-rest)
1240                                            after-header-name t)
1241                        (> (match-end 0) start-of-value))
1242                   (setq split-rest nil)
1243                 (setq split-rest (cddr split-rest))))
1244             (when split-rest
1245               (goto-char end)
1246               (let ((value (nth 1 split)))
1247                 (if (symbolp value)
1248                     (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1249                 ;; Someone might want to do a \N sub on this match, so get the
1250                 ;; correct match positions.
1251                 (re-search-backward value start-of-value))
1252               (dolist (sp (nnmail-split-it (car split-rest)))
1253                 (unless (memq sp split-result)
1254                   (push sp split-result))))))
1255         split-result))
1256
1257      ;; Not in cache, compute a regexp for the field/value pair.
1258      (t
1259       (let* ((field (nth 0 split))
1260              (value (nth 1 split))
1261              partial-front regexp
1262              partial-rear  regexp)
1263         (if (symbolp value)
1264             (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1265         (if (and (>= (length value) 2)
1266                  (string= ".*" (substring value 0 2)))
1267             (setq value (substring value 2)
1268                   partial-front ""))
1269         ;; Same trick for the rear of the regexp
1270         (if (and (>= (length value) 2)
1271                  (string= ".*" (substring value -2)))
1272             (setq value (substring value 0 -2)
1273                   partial-rear ""))
1274         (setq regexp (concat "^\\(\\("
1275                              (if (symbolp field)
1276                                  (cdr (assq field nnmail-split-abbrev-alist))
1277                                field)
1278                              "\\):.*\\)"
1279                              (or partial-front "\\<")
1280                              "\\("
1281                              value
1282                              "\\)"
1283                              (or partial-rear "\\>")))
1284         (push (cons split regexp) nnmail-split-cache)
1285         ;; Now that it's in the cache, just call nnmail-split-it again
1286         ;; on the same split, which will find it immediately in the cache.
1287         (nnmail-split-it split))))))
1288
1289 (defun nnmail-expand-newtext (newtext)
1290   (let ((len (length newtext))
1291         (pos 0)
1292         c expanded beg N did-expand)
1293     (while (< pos len)
1294       (setq beg pos)
1295       (while (and (< pos len)
1296                   (not (= (aref newtext pos) ?\\)))
1297         (setq pos (1+ pos)))
1298       (unless (= beg pos)
1299         (push (substring newtext beg pos) expanded))
1300       (when (< pos len)
1301         ;; We hit a \; expand it.
1302         (setq did-expand t
1303               pos (1+ pos)
1304               c (aref newtext pos))
1305         (if (not (or (= c ?\&)
1306                      (and (>= c ?1)
1307                           (<= c ?9))))
1308             ;; \ followed by some character we don't expand.
1309             (push (char-to-string c) expanded)
1310           ;; \& or \N
1311           (if (= c ?\&)
1312               (setq N 0)
1313             (setq N (- c ?0)))
1314           (when (match-beginning N)
1315             (push (buffer-substring (match-beginning N) (match-end N))
1316                   expanded))))
1317       (setq pos (1+ pos)))
1318     (if did-expand
1319         (apply 'concat (nreverse expanded))
1320       newtext)))
1321
1322 ;; Activate a backend only if it isn't already activated.
1323 ;; If FORCE, re-read the active file even if the backend is
1324 ;; already activated.
1325 (defun nnmail-activate (backend &optional force)
1326   (nnheader-init-server-buffer)
1327   (let (file timestamp file-time)
1328     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1329             force
1330             (and (setq file (ignore-errors
1331                               (symbol-value (intern (format "%s-active-file"
1332                                                             backend)))))
1333                  (setq file-time (nth 5 (file-attributes file)))
1334                  (or (not
1335                       (setq timestamp
1336                             (condition-case ()
1337                                 (symbol-value (intern
1338                                                (format "%s-active-timestamp"
1339                                                        backend)))
1340                               (error 'none))))
1341                      (not (consp timestamp))
1342                      (equal timestamp '(0 0))
1343                      (> (nth 0 file-time) (nth 0 timestamp))
1344                      (and (= (nth 0 file-time) (nth 0 timestamp))
1345                           (> (nth 1 file-time) (nth 1 timestamp))))))
1346         (save-excursion
1347           (or (eq timestamp 'none)
1348               (set (intern (format "%s-active-timestamp" backend))
1349                    file-time))
1350           (funcall (intern (format "%s-request-list" backend)))))
1351     t))
1352
1353 (defun nnmail-message-id ()
1354   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1355
1356 ;;;
1357 ;;; nnmail duplicate handling
1358 ;;;
1359
1360 (defvar nnmail-cache-buffer nil)
1361
1362 (defun nnmail-cache-open ()
1363   (if (or (not nnmail-treat-duplicates)
1364           (and nnmail-cache-buffer
1365                (buffer-name nnmail-cache-buffer)))
1366       ()                                ; The buffer is open.
1367     (save-excursion
1368       (set-buffer
1369        (setq nnmail-cache-buffer
1370              (get-buffer-create " *nnmail message-id cache*")))
1371       (when (file-exists-p nnmail-message-id-cache-file)
1372         (nnheader-insert-file-contents nnmail-message-id-cache-file))
1373       (set-buffer-modified-p nil)
1374       (current-buffer))))
1375
1376 (defun nnmail-cache-close ()
1377   (when (and nnmail-cache-buffer
1378              nnmail-treat-duplicates
1379              (buffer-name nnmail-cache-buffer)
1380              (buffer-modified-p nnmail-cache-buffer))
1381     (save-excursion
1382       (set-buffer nnmail-cache-buffer)
1383       ;; Weed out the excess number of Message-IDs.
1384       (goto-char (point-max))
1385       (when (search-backward "\n" nil t nnmail-message-id-cache-length)
1386         (progn
1387           (beginning-of-line)
1388           (delete-region (point-min) (point))))
1389       ;; Save the buffer.
1390       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1391           (make-directory (file-name-directory nnmail-message-id-cache-file)
1392                           t))
1393       (nnmail-write-region (point-min) (point-max)
1394                            nnmail-message-id-cache-file nil 'silent)
1395       (set-buffer-modified-p nil)
1396       (setq nnmail-cache-buffer nil)
1397       (kill-buffer (current-buffer)))))
1398
1399 ;; Compiler directives.
1400 (defvar group)
1401 (defvar group-art-list)
1402 (defvar group-art)
1403 (defun nnmail-cache-insert (id)
1404   (when nnmail-treat-duplicates
1405     ;; Store some information about the group this message is written
1406     ;; to.  This function might have been called from various places.
1407     ;; Sometimes, a function up in the calling sequence has an
1408     ;; argument GROUP which is bound to a string, the group name.  At
1409     ;; other times, there is a function up in the calling sequence
1410     ;; which has an argument GROUP-ART which is a list of pairs, and
1411     ;; the car of a pair is a group name.  Should we check that the
1412     ;; length of the list is equal to 1? -- kai
1413     (let ((g nil))
1414       (cond ((and (boundp 'group) group)
1415              (setq g group))
1416             ((and (boundp 'group-art-list) group-art-list
1417                   (listp group-art-list))
1418              (setq g (caar group-art-list)))
1419             ((and (boundp 'group-art) group-art (listp group-art))
1420              (setq g (caar group-art)))
1421             (t (setq g "")))
1422       (unless (gnus-buffer-live-p nnmail-cache-buffer)
1423         (nnmail-cache-open))
1424       (save-excursion
1425         (set-buffer nnmail-cache-buffer)
1426         (goto-char (point-max))
1427         (if (and g (not (string= "" g))
1428                  (gnus-methods-equal-p gnus-command-method
1429                                        (nnmail-cache-primary-mail-backend)))
1430             (insert id "\t" g "\n")
1431           (insert id "\n"))))))
1432
1433 (defun nnmail-cache-primary-mail-backend ()
1434   (let ((be-list (cons gnus-select-method gnus-secondary-select-methods))
1435         (be nil)
1436         (res nil))
1437     (while (and (null res) be-list)
1438       (setq be (car be-list))
1439       (setq be-list (cdr be-list))
1440       (when (and (gnus-method-option-p be 'respool)
1441                  (eval (intern (format "%s-get-new-mail" (car be)))))
1442         (setq res be)))
1443     res))
1444
1445 ;; Fetch the group name corresponding to the message id stored in the
1446 ;; cache.
1447 (defun nnmail-cache-fetch-group (id)
1448   (when (and nnmail-treat-duplicates nnmail-cache-buffer)
1449     (save-excursion
1450       (set-buffer nnmail-cache-buffer)
1451       (goto-char (point-max))
1452       (when (search-backward id nil t)
1453         (beginning-of-line)
1454         (skip-chars-forward "^\n\r\t")
1455         (unless (eolp)
1456           (forward-char 1)
1457           (buffer-substring (point)
1458                             (progn (end-of-line) (point))))))))
1459
1460 ;; Function for nnmail-split-fancy: look up all references in the
1461 ;; cache and if a match is found, return that group.
1462 (defun nnmail-split-fancy-with-parent ()
1463   "Split this message into the same group as its parent.
1464 This function can be used as an entry in `nnmail-split-fancy', for
1465 example like this: (: nnmail-split-fancy)
1466 For a message to be split, it looks for the parent message in the
1467 References or In-Reply-To header and then looks in the message id
1468 cache file (given by the variable `nnmail-message-id-cache-file') to
1469 see which group that message was put in.  This group is returned.
1470
1471 See the Info node `(gnus)Fancy Mail Splitting' for more details."
1472   (let* ((refstr (or (message-fetch-field "references")
1473                      (message-fetch-field "in-reply-to")))
1474          (references nil)
1475          (res nil))
1476     (when refstr
1477       (setq references (nreverse (gnus-split-references refstr)))
1478       (unless (gnus-buffer-live-p nnmail-cache-buffer)
1479         (nnmail-cache-open))
1480       (mapcar (lambda (x)
1481                 (setq res (or (nnmail-cache-fetch-group x) res))
1482                 (when (string= "drafts" res)
1483                   (setq res nil)))
1484               references)
1485       res)))
1486
1487 (defun nnmail-cache-id-exists-p (id)
1488   (when nnmail-treat-duplicates
1489     (save-excursion
1490       (set-buffer nnmail-cache-buffer)
1491       (goto-char (point-max))
1492       (search-backward id nil t))))
1493
1494 (defun nnmail-fetch-field (header)
1495   (save-excursion
1496     (save-restriction
1497       (message-narrow-to-head)
1498       (message-fetch-field header))))
1499
1500 (defun nnmail-check-duplication (message-id func artnum-func)
1501   (run-hooks 'nnmail-prepare-incoming-message-hook)
1502   ;; If this is a duplicate message, then we do not save it.
1503   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1504          (case-fold-search t)
1505          (action (when duplication
1506                    (cond
1507                     ((memq nnmail-treat-duplicates '(warn delete))
1508                      nnmail-treat-duplicates)
1509                     ((nnheader-functionp nnmail-treat-duplicates)
1510                      (funcall nnmail-treat-duplicates message-id))
1511                     (t
1512                      nnmail-treat-duplicates))))
1513          group-art)
1514     ;; We insert a line that says what the mail source is.
1515     (let ((case-fold-search t))
1516       (goto-char (point-min))
1517       (re-search-forward "^message-id[ \t]*:" nil t)
1518       (beginning-of-line)
1519       (insert (format "X-Gnus-Mail-Source: %s\n" mail-source-string)))
1520
1521     ;; Let the backend save the article (or not).
1522     (cond
1523      ((not duplication)
1524       (funcall func (setq group-art
1525                           (nreverse (nnmail-article-group artnum-func))))
1526       (nnmail-cache-insert message-id))
1527      ((eq action 'delete)
1528       (setq group-art nil))
1529      ((eq action 'warn)
1530       ;; We insert a warning.
1531       (let ((case-fold-search t))
1532         (goto-char (point-min))
1533         (re-search-forward "^message-id[ \t]*:" nil t)
1534         (beginning-of-line)
1535         (insert
1536          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1537         (funcall func (setq group-art
1538                             (nreverse (nnmail-article-group artnum-func))))))
1539      (t
1540       (funcall func (setq group-art
1541                           (nreverse (nnmail-article-group artnum-func))))))
1542     ;; Add the group-art list to the history list.
1543     (if group-art
1544         (push group-art nnmail-split-history)
1545       (delete-region (point-min) (point-max)))))
1546
1547 ;;; Get new mail.
1548
1549 (defvar nnmail-fetched-sources nil)
1550
1551 (defun nnmail-get-value (&rest args)
1552   (let ((sym (intern (apply 'format args))))
1553     (when (boundp sym)
1554       (symbol-value sym))))
1555
1556 (defun nnmail-get-new-mail (method exit-func temp
1557                                    &optional group spool-func)
1558   "Read new incoming mail."
1559   (let* ((sources (or mail-sources
1560                       (if (listp nnmail-spool-file) nnmail-spool-file
1561                         (list nnmail-spool-file))))
1562          fetching-sources
1563          (group-in group)
1564          (i 0)
1565          (new 0)
1566          (total 0)
1567          incoming incomings source)
1568     (when (and (nnmail-get-value "%s-get-new-mail" method)
1569                sources)
1570       (while (setq source (pop sources))
1571         ;; Be compatible with old values.
1572         (cond
1573          ((stringp source)
1574           (setq source
1575                 (cond
1576                  ((string-match "^po:" source)
1577                   (list 'pop :user (substring source (match-end 0))))
1578                  ((file-directory-p source)
1579                   (list 'directory :path source))
1580                  (t
1581                   (list 'file :path source)))))
1582          ((eq source 'procmail)
1583           (message "Invalid value for nnmail-spool-file: `procmail'")
1584           nil))
1585         ;; Hack to only fetch the contents of a single group's spool file.
1586         (when (and (eq (car source) 'directory)
1587                    (null nnmail-scan-directory-mail-source-once)
1588                    group)
1589           (mail-source-bind (directory source)
1590             (setq source (append source
1591                                  (list
1592                                   :predicate
1593                                   `(lambda (file)
1594                                      (string-equal
1595                                       ,(concat group suffix)
1596                                       (file-name-nondirectory file))))))))
1597         (when nnmail-fetched-sources
1598           (if (member source nnmail-fetched-sources)
1599               (setq source nil)
1600             (push source nnmail-fetched-sources)
1601             (push source fetching-sources)))))
1602     (when fetching-sources
1603       ;; We first activate all the groups.
1604       (nnmail-activate method)
1605       ;; Allow the user to hook.
1606       (run-hooks 'nnmail-pre-get-new-mail-hook)
1607       ;; Open the message-id cache.
1608       (nnmail-cache-open)
1609       ;; The we go through all the existing mail source specification
1610       ;; and fetch the mail from each.
1611       (while (setq source (pop fetching-sources))
1612         (nnheader-message 4 "%s: Reading incoming mail from %s..."
1613                           method (car source))
1614         (when (setq new
1615                     (mail-source-fetch
1616                      source
1617                      `(lambda (file orig-file)
1618                         (nnmail-split-incoming
1619                          file ',(intern (format "%s-save-mail" method))
1620                          ',spool-func
1621                          (if (equal file orig-file)
1622                              nil
1623                            (nnmail-get-split-group orig-file ',source))
1624                          ',(intern (format "%s-active-number" method))))))
1625           (incf total new)
1626           (incf i)))
1627       ;; If we did indeed read any incoming spools, we save all info.
1628       (if (zerop total)
1629           (nnheader-message 4 "%s: Reading incoming mail (no new mail)...done"
1630                             method (car source))
1631         (nnmail-save-active
1632          (nnmail-get-value "%s-group-alist" method)
1633          (nnmail-get-value "%s-active-file" method))
1634         (when exit-func
1635           (funcall exit-func))
1636         (run-hooks 'nnmail-read-incoming-hook)
1637         (nnheader-message 4 "%s: Reading incoming mail (%d new)...done" method
1638                           total))
1639       ;; Close the message-id cache.
1640       (nnmail-cache-close)
1641       ;; Allow the user to hook.
1642       (run-hooks 'nnmail-post-get-new-mail-hook))))
1643
1644 (defun nnmail-expired-article-p (group time force &optional inhibit)
1645   "Say whether an article that is TIME old in GROUP should be expired."
1646   (if force
1647       t
1648     (let ((days (or (and nnmail-expiry-wait-function
1649                          (funcall nnmail-expiry-wait-function group))
1650                     nnmail-expiry-wait)))
1651       (cond ((or (eq days 'never)
1652                  (and (not force)
1653                       inhibit))
1654              ;; This isn't an expirable group.
1655              nil)
1656             ((eq days 'immediate)
1657              ;; We expire all articles on sight.
1658              t)
1659             ((equal time '(0 0))
1660              ;; This is an ange-ftp group, and we don't have any dates.
1661              nil)
1662             ((numberp days)
1663              (setq days (days-to-time days))
1664              ;; Compare the time with the current time.
1665              (ignore-errors (time-less-p days (time-since time))))))))
1666
1667 (defun nnmail-expiry-target-group (target group)
1668   (let (nnmail-cache-accepted-message-ids)
1669     ;; Don't enter Message-IDs into cache.
1670     ;; Let users hack it in TARGET function.
1671     (when (nnheader-functionp target)
1672       (setq target (funcall target group)))
1673     (unless (eq target 'delete)
1674       (gnus-request-accept-article target nil nil t))))
1675
1676 (defun nnmail-check-syntax ()
1677   "Check (and modify) the syntax of the message in the current buffer."
1678   (save-restriction
1679     (message-narrow-to-head)
1680     (let ((case-fold-search t))
1681       (unless (re-search-forward "^Message-ID[ \t]*:" nil t)
1682         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1683
1684 (defun nnmail-write-region (start end filename &optional append visit lockname)
1685   "Do a `write-region', and then set the file modes."
1686   (let ((coding-system-for-write nnmail-file-coding-system)
1687         (file-name-coding-system nnmail-pathname-coding-system))
1688     (write-region start end filename append visit lockname)
1689     (set-file-modes filename nnmail-default-file-modes)))
1690
1691 ;;;
1692 ;;; Status functions
1693 ;;;
1694
1695 (defun nnmail-replace-status (name value)
1696   "Make status NAME and VALUE part of the current status line."
1697   (save-restriction
1698     (message-narrow-to-head)
1699     (let ((status (nnmail-decode-status)))
1700       (setq status (delq (member name status) status))
1701       (when value
1702         (push (cons name value) status))
1703       (message-remove-header "status")
1704       (goto-char (point-max))
1705       (insert "Status: " (nnmail-encode-status status) "\n"))))
1706
1707 (defun nnmail-decode-status ()
1708   "Return a status-value alist from STATUS."
1709   (goto-char (point-min))
1710   (when (re-search-forward "^Status: " nil t)
1711     (let (name value status)
1712       (save-restriction
1713         ;; Narrow to the status.
1714         (narrow-to-region
1715          (point)
1716          (if (re-search-forward "^[^ \t]" nil t)
1717              (1- (point))
1718            (point-max)))
1719         ;; Go through all elements and add them to the list.
1720         (goto-char (point-min))
1721         (while (re-search-forward "[^ \t=]+" nil t)
1722           (setq name (match-string 0))
1723           (if (not (eq (char-after) ?=))
1724               ;; Implied "yes".
1725               (setq value "yes")
1726             (forward-char 1)
1727             (if (not (eq (char-after) ?\"))
1728                 (if (not (looking-at "[^ \t]"))
1729                     ;; Implied "no".
1730                     (setq value "no")
1731                   ;; Unquoted value.
1732                   (setq value (match-string 0))
1733                   (goto-char (match-end 0)))
1734               ;; Quoted value.
1735               (setq value (read (current-buffer)))))
1736           (push (cons name value) status)))
1737       status)))
1738
1739 (defun nnmail-encode-status (status)
1740   "Return a status string from STATUS."
1741   (mapconcat
1742    (lambda (elem)
1743      (concat
1744       (car elem) "="
1745       (if (string-match "[ \t]" (cdr elem))
1746           (prin1-to-string (cdr elem))
1747         (cdr elem))))
1748    status " "))
1749
1750 (defun nnmail-split-history ()
1751   "Generate an overview of where the last mail split put articles."
1752   (interactive)
1753   (unless nnmail-split-history
1754     (error "No current split history"))
1755   (with-output-to-temp-buffer "*nnmail split history*"
1756     (with-current-buffer standard-output
1757       (fundamental-mode))               ; for Emacs 20.4+
1758     (let ((history nnmail-split-history)
1759           elem)
1760       (while (setq elem (pop history))
1761         (princ (mapconcat (lambda (ga)
1762                             (concat (car ga) ":" (int-to-string (cdr ga))))
1763                           elem
1764                           ", "))
1765         (princ "\n")))))
1766
1767 (defun nnmail-purge-split-history (group)
1768   "Remove all instances of GROUP from `nnmail-split-history'."
1769   (let ((history nnmail-split-history))
1770     (while history
1771       (setcar history (gnus-delete-if (lambda (e) (string= (car e) group))
1772                                       (car history)))
1773       (pop history))
1774     (setq nnmail-split-history (delq nil nnmail-split-history))))
1775
1776 (defun nnmail-new-mail-p (group)
1777   "Say whether GROUP has new mail."
1778   (let ((his nnmail-split-history)
1779         found)
1780     (while his
1781       (when (assoc group (pop his))
1782         (setq found t
1783               his nil)))
1784     found))
1785
1786 (defun nnmail-within-headers-p ()
1787   "Check to see if point is within the headers of a unix mail message.
1788 Doesn't change point."
1789   (let ((pos (point)))
1790     (save-excursion
1791       (and (nnmail-search-unix-mail-delim-backward)
1792            (not (search-forward "\n\n" pos t))))))
1793
1794 (run-hooks 'nnmail-load-hook)
1795
1796 (provide 'nnmail)
1797
1798 ;;; nnmail.el ends here