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