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