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