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