* gnus-srvr.el (gnus-server-kill-server): Offer to kill all the
[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   ;; Go through all groups from the active list.
486   (save-excursion
487     (set-buffer nntp-server-buffer)
488     (nnmail-parse-active)))
489
490 (defun nnmail-parse-active ()
491   "Parse the active file in the current buffer and return an alist."
492   (goto-char (point-min))
493   (unless (re-search-forward "[\\\"]" nil t)
494     (goto-char (point-max))
495     (while (re-search-backward "[][';?()#]" nil t)
496       (insert ?\\)))
497   (goto-char (point-min))
498   (let ((buffer (current-buffer))
499         group-assoc group max min)
500     (while (not (eobp))
501       (condition-case err
502           (progn
503             (narrow-to-region (point) (gnus-point-at-eol))
504             (setq group (read buffer))
505             (unless (stringp group)
506               (setq group (symbol-name group)))
507             (if (and (numberp (setq max (read nntp-server-buffer)))
508                      (numberp (setq min (read nntp-server-buffer))))
509                 (push (list group (cons min max))
510                       group-assoc)))
511         (error nil))
512       (widen)
513       (forward-line 1))
514     group-assoc))
515
516 (defvar nnmail-active-file-coding-system 'raw-text
517   "*Coding system for active file.")
518
519 (defun nnmail-save-active (group-assoc file-name)
520   "Save GROUP-ASSOC in ACTIVE-FILE."
521   (let ((coding-system-for-write nnmail-active-file-coding-system))
522     (when file-name
523       (with-temp-file file-name
524         (nnmail-generate-active group-assoc)))))
525
526 (defun nnmail-generate-active (alist)
527   "Generate an active file from group-alist ALIST."
528   (erase-buffer)
529   (let (group)
530     (while (setq group (pop alist))
531       (insert (format "%S %d %d y\n" (intern (car group)) (cdadr group)
532                       (caadr group))))
533     (goto-char (point-max))
534     (while (search-backward "\\." nil t)
535       (delete-char 1))))
536
537 (defun nnmail-get-split-group (file source)
538   "Find out whether this FILE is to be split into GROUP only.
539 If SOURCE is a directory spec, try to return the group name component."
540   (if (eq (car source) 'directory)
541       (let ((file (file-name-nondirectory file)))
542         (mail-source-bind (directory source)
543           (if (string-match (concat (regexp-quote suffix) "$") file)
544               (substring file 0 (match-beginning 0))
545             nil)))
546     nil))
547
548 (defun nnmail-process-babyl-mail-format (func artnum-func)
549   (let ((case-fold-search t)
550         (count 0)
551         start message-id content-length do-search end)
552     (while (not (eobp))
553       (goto-char (point-min))
554       (re-search-forward
555        "\f\n0, *unseen,+\n\\(\\*\\*\\* EOOH \\*\\*\\*\n\\)?" nil t)
556       (goto-char (match-end 0))
557       (delete-region (match-beginning 0) (match-end 0))
558       (narrow-to-region
559        (setq start (point))
560        (progn
561          ;; Skip all the headers in case there are more "From "s...
562          (or (search-forward "\n\n" nil t)
563              (search-forward-regexp "^[^:]*\\( .*\\|\\)$" nil t)
564              (search-forward "\1f\f"))
565          (point)))
566       ;; Unquote the ">From " line, if any.
567       (goto-char (point-min))
568       (when (looking-at ">From ")
569         (replace-match "X-From-Line: ") )
570       (run-hooks 'nnmail-prepare-incoming-header-hook)
571       (goto-char (point-max))
572       ;; Find the Message-ID header.
573       (save-excursion
574         (if (re-search-backward
575              "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]*>\\)" nil t)
576             (setq message-id (buffer-substring (match-beginning 1)
577                                                (match-end 1)))
578           ;; There is no Message-ID here, so we create one.
579           (save-excursion
580             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
581               (beginning-of-line)
582               (insert "Original-")))
583           (forward-line -1)
584           (insert "Message-ID: " (setq message-id (nnmail-message-id))
585                   "\n")))
586       ;; Look for a Content-Length header.
587       (if (not (save-excursion
588                  (and (re-search-backward
589                        "^Content-Length:[ \t]*\\([0-9]+\\)" start t)
590                       (setq content-length (string-to-int
591                                             (buffer-substring
592                                              (match-beginning 1)
593                                              (match-end 1))))
594                       ;; We destroy the header, since none of
595                       ;; the backends ever use it, and we do not
596                       ;; want to confuse other mailers by having
597                       ;; a (possibly) faulty header.
598                       (progn (insert "X-") t))))
599           (setq do-search t)
600         (widen)
601         (if (or (= (+ (point) content-length) (point-max))
602                 (save-excursion
603                   (goto-char (+ (point) content-length))
604                   (looking-at "\1f")))
605             (progn
606               (goto-char (+ (point) content-length))
607               (setq do-search nil))
608           (setq do-search t)))
609       (widen)
610       ;; Go to the beginning of the next article - or to the end
611       ;; of the buffer.
612       (when do-search
613         (if (re-search-forward "^\1f" nil t)
614             (goto-char (match-beginning 0))
615           (goto-char (1- (point-max)))))
616       (delete-char 1)                   ; delete ^_
617       (save-excursion
618         (save-restriction
619           (narrow-to-region start (point))
620           (goto-char (point-min))
621           (nnmail-check-duplication message-id func artnum-func)
622           (incf count)
623           (setq end (point-max))))
624       (goto-char end))
625     count))
626
627 (defsubst nnmail-search-unix-mail-delim ()
628   "Put point at the beginning of the next Unix mbox message."
629   ;; Algorithm used to find the the next article in the
630   ;; brain-dead Unix mbox format:
631   ;;
632   ;; 1) Search for "^From ".
633   ;; 2) If we find it, then see whether the previous
634   ;;    line is blank and the next line looks like a header.
635   ;; Then it's possible that this is a mail delim, and we use it.
636   (let ((case-fold-search nil)
637         found)
638     (while (not found)
639       (if (not (re-search-forward "^From " nil t))
640           (setq found 'no)
641         (save-excursion
642           (beginning-of-line)
643           (when (and (or (bobp)
644                          (save-excursion
645                            (forward-line -1)
646                            (eq (char-after) ?\n)))
647                      (save-excursion
648                        (forward-line 1)
649                        (while (looking-at ">From \\|From ")
650                          (forward-line 1))
651                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
652             (setq found 'yes)))))
653     (beginning-of-line)
654     (eq found 'yes)))
655
656 (defun nnmail-search-unix-mail-delim-backward ()
657   "Put point at the beginning of the current Unix mbox message."
658   ;; Algorithm used to find the the next article in the
659   ;; brain-dead Unix mbox format:
660   ;;
661   ;; 1) Search for "^From ".
662   ;; 2) If we find it, then see whether the previous
663   ;;    line is blank and the next line looks like a header.
664   ;; Then it's possible that this is a mail delim, and we use it.
665   (let ((case-fold-search nil)
666         found)
667     (while (not found)
668       (if (not (re-search-backward "^From " nil t))
669           (setq found 'no)
670         (save-excursion
671           (beginning-of-line)
672           (when (and (or (bobp)
673                          (save-excursion
674                            (forward-line -1)
675                            (eq (char-after) ?\n)))
676                      (save-excursion
677                        (forward-line 1)
678                        (while (looking-at ">From \\|From ")
679                          (forward-line 1))
680                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
681             (setq found 'yes)))))
682     (beginning-of-line)
683     (eq found 'yes)))
684
685 (defun nnmail-process-unix-mail-format (func artnum-func)
686   (let ((case-fold-search t)
687         (count 0)
688         start message-id content-length end skip head-end)
689     (goto-char (point-min))
690     (if (not (and (re-search-forward "^From " nil t)
691                   (goto-char (match-beginning 0))))
692         ;; Possibly wrong format?
693         (error "Error, unknown mail format! (Possibly corrupted.)")
694       ;; Carry on until the bitter end.
695       (while (not (eobp))
696         (setq start (point)
697               end nil)
698         ;; Find the end of the head.
699         (narrow-to-region
700          start
701          (if (search-forward "\n\n" nil t)
702              (1- (point))
703            ;; This will never happen, but just to be on the safe side --
704            ;; if there is no head-body delimiter, we search a bit manually.
705            (while (and (looking-at "From \\|[^ \t]+:")
706                        (not (eobp)))
707              (forward-line 1))
708            (point)))
709         ;; Find the Message-ID header.
710         (goto-char (point-min))
711         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
712             (setq message-id (match-string 1))
713           (save-excursion
714             (when (re-search-forward "^Message-ID[ \t]*:" nil t)
715               (beginning-of-line)
716               (insert "Original-")))
717           ;; There is no Message-ID here, so we create one.
718           (forward-line 1)
719           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
720         ;; Look for a Content-Length header.
721         (goto-char (point-min))
722         (if (not (re-search-forward
723                   "^Content-Length:[ \t]*\\([0-9]+\\)" nil t))
724             (setq content-length nil)
725           (setq content-length (string-to-int (match-string 1)))
726           ;; We destroy the header, since none of the backends ever
727           ;; use it, and we do not want to confuse other mailers by
728           ;; having a (possibly) faulty header.
729           (beginning-of-line)
730           (insert "X-"))
731         (run-hooks 'nnmail-prepare-incoming-header-hook)
732         ;; Find the end of this article.
733         (goto-char (point-max))
734         (widen)
735         (setq head-end (point))
736         ;; We try the Content-Length value.  The idea: skip over the header
737         ;; separator, then check what happens content-length bytes into the
738         ;; message body.  This should be either the end ot the buffer, the
739         ;; message separator or a blank line followed by the separator.
740         ;; The blank line should probably be deleted.  If neither of the
741         ;; three is met, the content-length header is probably invalid.
742         (when content-length
743           (forward-line 1)
744           (setq skip (+ (point) content-length))
745           (goto-char skip)
746           (cond ((or (= skip (point-max))
747                      (= (1+ skip) (point-max)))
748                  (setq end (point-max)))
749                 ((looking-at "From ")
750                  (setq end skip))
751                 ((looking-at "[ \t]*\n\\(From \\)")
752                  (setq end (match-beginning 1)))
753                 (t (setq end nil))))
754         (if end
755             (goto-char end)
756           ;; No Content-Length, so we find the beginning of the next
757           ;; article or the end of the buffer.
758           (goto-char head-end)
759           (or (nnmail-search-unix-mail-delim)
760               (goto-char (point-max))))
761         ;; Allow the backend to save the article.
762         (save-excursion
763           (save-restriction
764             (narrow-to-region start (point))
765             (goto-char (point-min))
766             (incf count)
767             (nnmail-check-duplication message-id func artnum-func)
768             (setq end (point-max))))
769         (goto-char end)))
770     count))
771
772 (defun nnmail-process-mmdf-mail-format (func artnum-func)
773   (let ((delim "^\^A\^A\^A\^A$")
774         (case-fold-search t)
775         (count 0)
776         start message-id end)
777     (goto-char (point-min))
778     (if (not (and (re-search-forward delim nil t)
779                   (forward-line 1)))
780         ;; Possibly wrong format?
781         (error "Error, unknown mail format! (Possibly corrupted.)")
782       ;; Carry on until the bitter end.
783       (while (not (eobp))
784         (setq start (point))
785         ;; Find the end of the head.
786         (narrow-to-region
787          start
788          (if (search-forward "\n\n" nil t)
789              (1- (point))
790            ;; This will never happen, but just to be on the safe side --
791            ;; if there is no head-body delimiter, we search a bit manually.
792            (while (and (looking-at "From \\|[^ \t]+:")
793                        (not (eobp)))
794              (forward-line 1))
795            (point)))
796         ;; Find the Message-ID header.
797         (goto-char (point-min))
798         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
799             (setq message-id (match-string 1))
800           ;; There is no Message-ID here, so we create one.
801           (save-excursion
802             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
803               (beginning-of-line)
804               (insert "Original-")))
805           (forward-line 1)
806           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
807         (run-hooks 'nnmail-prepare-incoming-header-hook)
808         ;; Find the end of this article.
809         (goto-char (point-max))
810         (widen)
811         (if (re-search-forward delim nil t)
812             (beginning-of-line)
813           (goto-char (point-max)))
814         ;; Allow the backend to save the article.
815         (save-excursion
816           (save-restriction
817             (narrow-to-region start (point))
818             (goto-char (point-min))
819             (incf count)
820             (nnmail-check-duplication message-id func artnum-func)
821             (setq end (point-max))))
822         (goto-char end)
823         (forward-line 2)))
824     count))
825
826 (defun nnmail-process-maildir-mail-format (func artnum-func)
827   ;; In a maildir, every file contains exactly one mail.
828   (let ((case-fold-search t)
829         message-id)
830     (goto-char (point-min))
831     ;; Find the end of the head.
832     (narrow-to-region
833      (point-min)
834      (if (search-forward "\n\n" nil t)
835          (1- (point))
836        ;; This will never happen, but just to be on the safe side --
837        ;; if there is no head-body delimiter, we search a bit manually.
838        (while (and (looking-at "From \\|[^ \t]+:")
839                    (not (eobp)))
840          (forward-line 1))
841        (point)))
842     ;; Find the Message-ID header.
843     (goto-char (point-min))
844     (if (re-search-forward "^Message-ID:[ \t]*\\(<[^>]+>\\)" nil t)
845         (setq message-id (match-string 1))
846       ;; There is no Message-ID here, so we create one.
847       (save-excursion
848         (when (re-search-backward "^Message-ID[ \t]*:" nil t)
849           (beginning-of-line)
850           (insert "Original-")))
851       (forward-line 1)
852       (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
853     (run-hooks 'nnmail-prepare-incoming-header-hook)
854     ;; Allow the backend to save the article.
855     (widen)
856     (save-excursion
857       (goto-char (point-min))
858       (nnmail-check-duplication message-id func artnum-func))
859     1))
860
861 (defun nnmail-split-incoming (incoming func &optional exit-func
862                                        group artnum-func)
863   "Go through the entire INCOMING file and pick out each individual mail.
864 FUNC will be called with the buffer narrowed to each mail."
865   (let (;; If this is a group-specific split, we bind the split
866         ;; methods to just this group.
867         (nnmail-split-methods (if (and group
868                                        (not nnmail-resplit-incoming))
869                                   (list (list group ""))
870                                 nnmail-split-methods)))
871     (save-excursion
872       ;; Insert the incoming file.
873       (set-buffer (get-buffer-create " *nnmail incoming*"))
874       (erase-buffer)
875       (let ((coding-system-for-read nnmail-incoming-coding-system))
876         (mm-insert-file-contents incoming))
877       (prog1
878           (if (zerop (buffer-size))
879               0
880             (goto-char (point-min))
881             (save-excursion (run-hooks 'nnmail-prepare-incoming-hook))
882             ;; Handle both babyl, MMDF and unix mail formats, since
883             ;; movemail will use the former when fetching from a
884             ;; mailbox, the latter when fetching from a file.
885             (cond ((or (looking-at "\^L")
886                        (looking-at "BABYL OPTIONS:"))
887                    (nnmail-process-babyl-mail-format func artnum-func))
888                   ((looking-at "\^A\^A\^A\^A")
889                    (nnmail-process-mmdf-mail-format func artnum-func))
890                   ((looking-at "Return-Path:")
891                    (nnmail-process-maildir-mail-format func artnum-func))
892                   (t
893                    (nnmail-process-unix-mail-format func artnum-func))))
894         (when exit-func
895           (funcall exit-func))
896         (kill-buffer (current-buffer))))))
897
898 (defun nnmail-article-group (func &optional trace)
899   "Look at the headers and return an alist of groups that match.
900 FUNC will be called with the group name to determine the article number."
901   (let ((methods nnmail-split-methods)
902         (obuf (current-buffer))
903         (beg (point-min))
904         end group-art method grp)
905     (if (and (sequencep methods)
906              (= (length methods) 1))
907         ;; If there is only just one group to put everything in, we
908         ;; just return a list with just this one method in.
909         (setq group-art
910               (list (cons (caar methods) (funcall func (caar methods)))))
911       ;; We do actual comparison.
912       (save-excursion
913         ;; Find headers.
914         (goto-char beg)
915         (setq end (if (search-forward "\n\n" nil t) (point) (point-max)))
916         (set-buffer nntp-server-buffer)
917         (erase-buffer)
918         ;; Copy the headers into the work buffer.
919         (insert-buffer-substring obuf beg end)
920         ;; Fold continuation lines.
921         (goto-char (point-min))
922         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
923           (replace-match " " t t))
924         ;; Nuke pathologically long headers.  Since Gnus applies
925         ;; pathologically complex regexps to the buffer, lines
926         ;; that are looong will take longer than the Universe's
927         ;; existence to process.
928         (goto-char (point-min))
929         (while (not (eobp))
930           (unless (< (move-to-column nnmail-split-header-length-limit)
931                      nnmail-split-header-length-limit)
932             (delete-region (point) (progn (end-of-line) (point))))
933           (forward-line 1))
934         ;; Allow washing.
935         (goto-char (point-min))
936         (run-hooks 'nnmail-split-hook)
937         (when (setq nnmail-split-tracing trace)
938           (setq nnmail-split-trace nil))
939         (if (and (symbolp nnmail-split-methods)
940                  (fboundp nnmail-split-methods))
941             (let ((split
942                    (condition-case nil
943                        ;; `nnmail-split-methods' is a function, so we
944                        ;; just call this function here and use the
945                        ;; result.
946                        (or (funcall nnmail-split-methods)
947                            '("bogus"))
948                      (error
949                       (nnheader-message 5
950                                         "Error in `nnmail-split-methods'; using `bogus' mail group")
951                       (sit-for 1)
952                       '("bogus")))))
953               (setq split (gnus-remove-duplicates split))
954               ;; The article may be "cross-posted" to `junk'.  What
955               ;; to do?  Just remove the `junk' spec.  Don't really
956               ;; see anything else to do...
957               (let (elem)
958                 (while (setq elem (car (memq 'junk split)))
959                   (setq split (delq elem split))))
960               (when split
961                 (setq group-art
962                       (mapcar
963                        (lambda (group) (cons group (funcall func group)))
964                        split))))
965           ;; Go through the split methods to find a match.
966           (while (and methods
967                       (or nnmail-crosspost
968                           (not group-art)))
969             (goto-char (point-max))
970             (setq method (pop methods)
971                   grp (car method))
972             (if (or methods
973                     (not (equal "" (nth 1 method))))
974                 (when (and
975                        (ignore-errors
976                          (if (stringp (nth 1 method))
977                              (let ((expand (string-match "\\\\[0-9&]" grp))
978                                    (pos (re-search-backward (cadr method)
979                                                             nil t)))
980                                (and expand
981                                     (setq grp (nnmail-expand-newtext grp)))
982                                pos)
983                            ;; Function to say whether this is a match.
984                            (funcall (nth 1 method) grp)))
985                        ;; Don't enter the article into the same
986                        ;; group twice.
987                        (not (assoc grp group-art)))
988                   (push (cons grp (funcall func grp))
989                         group-art))
990               ;; This is the final group, which is used as a
991               ;; catch-all.
992               (unless group-art
993                 (setq group-art
994                       (list (cons (car method)
995                                   (funcall func (car method)))))))))
996         ;; Produce a trace if non-empty.
997         (when (and trace nnmail-split-trace)
998           (let ((trace (nreverse nnmail-split-trace))
999                 (restore (current-buffer)))
1000             (nnheader-set-temp-buffer "*Split Trace*")
1001             (gnus-add-buffer)
1002             (while trace
1003               (insert (car trace) "\n")
1004               (setq trace (cdr trace)))
1005             (goto-char (point-min))
1006             (gnus-configure-windows 'split-trace)
1007             (set-buffer restore)))
1008         ;; See whether the split methods returned `junk'.
1009         (if (equal group-art '(junk))
1010             nil
1011           ;; The article may be "cross-posted" to `junk'.  What
1012           ;; to do?  Just remove the `junk' spec.  Don't really
1013           ;; see anything else to do...
1014           (let (elem)
1015             (while (setq elem (car (memq 'junk group-art)))
1016               (setq group-art (delq elem group-art)))
1017             (nreverse group-art)))))))
1018
1019 (defun nnmail-insert-lines ()
1020   "Insert how many lines there are in the body of the mail.
1021 Return the number of characters in the body."
1022   (let (lines chars)
1023     (save-excursion
1024       (goto-char (point-min))
1025       (unless (search-forward "\n\n" nil t) 
1026         (goto-char (point-max))
1027         (insert "\n"))
1028       (setq chars (- (point-max) (point)))
1029       (setq lines (count-lines (point) (point-max)))
1030       (forward-char -1)
1031       (save-excursion
1032         (when (re-search-backward "^Lines: " nil t)
1033           (delete-region (point) (progn (forward-line 1) (point)))))
1034       (beginning-of-line)
1035       (insert (format "Lines: %d\n" (max lines 0)))
1036       chars)))
1037
1038 (defun nnmail-insert-xref (group-alist)
1039   "Insert an Xref line based on the (group . article) alist."
1040   (save-excursion
1041     (goto-char (point-min))
1042     (unless (search-forward "\n\n" nil t)
1043       (goto-char (point-max))
1044       (insert "\n"))
1045     (forward-char -1)
1046     (when (re-search-backward "^Xref: " nil t)
1047       (delete-region (match-beginning 0)
1048                      (progn (forward-line 1) (point))))
1049     (insert (format "Xref: %s" (system-name)))
1050     (while group-alist
1051       (insert (format " %s:%d"
1052                       (mm-encode-coding-string
1053                        (caar group-alist)
1054                        nnmail-pathname-coding-system)
1055                       (cdar group-alist)))
1056       (setq group-alist (cdr group-alist)))
1057     (insert "\n")))
1058
1059 ;;; Message washing functions
1060
1061 (defun nnmail-remove-leading-whitespace ()
1062   "Remove excessive whitespace from all headers."
1063   (goto-char (point-min))
1064   (while (re-search-forward "^\\([^ :]+: \\) +" nil t)
1065     (replace-match "\\1" t)))
1066
1067 (defun nnmail-remove-list-identifiers ()
1068   "Remove list identifiers from Subject headers."
1069   (let ((regexp (if (stringp nnmail-list-identifiers) nnmail-list-identifiers
1070                   (mapconcat 'identity nnmail-list-identifiers " *\\|"))))
1071     (when regexp
1072       (goto-char (point-min))
1073       (when (re-search-forward
1074              (concat "^Subject: +\\(Re: +\\)?\\(" regexp " *\\)")
1075              nil t)
1076         (delete-region (match-beginning 2) (match-end 0))))))
1077
1078 (defun nnmail-remove-tabs ()
1079   "Translate TAB characters into SPACE characters."
1080   (subst-char-in-region (point-min) (point-max) ?\t ?  t))
1081
1082 (defun nnmail-fix-eudora-headers ()
1083   "Eudora has a broken References line, but an OK In-Reply-To."
1084   (goto-char (point-min))
1085   (when (re-search-forward "^X-Mailer:.*Eudora" nil t)
1086     (goto-char (point-min))
1087     (when (re-search-forward "^References:" nil t)
1088       (beginning-of-line)
1089       (insert "X-Gnus-Broken-Eudora-"))))
1090
1091 (custom-add-option 'nnmail-prepare-incoming-header-hook
1092                    'nnmail-fix-eudora-headers)
1093
1094 ;;; Utility functions
1095
1096 (defun nnmail-split-fancy ()
1097   "Fancy splitting method.
1098 See the documentation for the variable `nnmail-split-fancy' for documentation."
1099   (let ((syntab (syntax-table)))
1100     (unwind-protect
1101         (progn
1102           (set-syntax-table nnmail-split-fancy-syntax-table)
1103           (nnmail-split-it nnmail-split-fancy))
1104       (set-syntax-table syntab))))
1105
1106 (defvar nnmail-split-cache nil)
1107 ;; Alist of split expressions their equivalent regexps.
1108
1109 (defun nnmail-split-it (split)
1110   ;; Return a list of groups matching SPLIT.
1111   (let (cached-pair)
1112     (cond
1113      ;; nil split
1114      ((null split)
1115       nil)
1116
1117      ;; A group name.  Do the \& and \N subs into the string.
1118      ((stringp split)
1119       (when nnmail-split-tracing
1120         (push (format "\"%s\"" split) nnmail-split-trace))
1121       (list (nnmail-expand-newtext split)))
1122
1123      ;; Junk the message.
1124      ((eq split 'junk)
1125       (when nnmail-split-tracing
1126         (push "junk" nnmail-split-trace))
1127       (list 'junk))
1128
1129      ;; Builtin & operation.
1130      ((eq (car split) '&)
1131       (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
1132
1133      ;; Builtin | operation.
1134      ((eq (car split) '|)
1135       (let (done)
1136         (while (and (not done) (cdr split))
1137           (setq split (cdr split)
1138                 done (nnmail-split-it (car split))))
1139         done))
1140
1141      ;; Builtin : operation.
1142      ((eq (car split) ':)
1143       (nnmail-split-it (save-excursion (eval (cdr split)))))
1144
1145      ;; Builtin ! operation.
1146      ((eq (car split) '!)
1147       (funcall (cadr split) (nnmail-split-it (caddr split))))
1148
1149      ;; Check the cache for the regexp for this split.
1150      ((setq cached-pair (assq split nnmail-split-cache))
1151       (let (split-result
1152             (end-point (point-max))
1153             (value (nth 1 split)))
1154         (if (symbolp value)
1155             (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1156         (while (and (goto-char end-point)
1157                     (re-search-backward (cdr cached-pair) nil t))
1158           (when nnmail-split-tracing
1159             (push (cdr cached-pair) nnmail-split-trace))
1160           (let ((split-rest (cddr split))
1161                 (end (match-end 0))
1162                 ;; The searched regexp is \(\(FIELD\).*\)\(VALUE\).  So,
1163                 ;; start-of-value is the the point just before the
1164                 ;; beginning of the value, whereas after-header-name is
1165                 ;; the point just after the field name.
1166                 (start-of-value (match-end 1))
1167                 (after-header-name (match-end 2)))
1168             ;; Start the next search just before the beginning of the
1169             ;; VALUE match.
1170             (setq end-point (1- start-of-value))
1171             ;; Handle - RESTRICTs
1172             (while (eq (car split-rest) '-)
1173               ;; RESTRICT must start after-header-name and
1174               ;; end after start-of-value, so that, for
1175               ;; (any "foo" - "x-foo" "foo.list")
1176               ;; we do not exclude foo.list just because
1177               ;; the header is: ``To: x-foo, foo''
1178               (goto-char end)
1179               (if (and (re-search-backward (cadr split-rest)
1180                                            after-header-name t)
1181                        (> (match-end 0) start-of-value))
1182                   (setq split-rest nil)
1183                 (setq split-rest (cddr split-rest))))
1184             (when split-rest
1185               (goto-char end)
1186               (let ((value (nth 1 split)))
1187                 (if (symbolp value)
1188                     (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1189                 ;; Someone might want to do a \N sub on this match, so get the
1190                 ;; correct match positions.
1191                 (re-search-backward value start-of-value))
1192               (dolist (sp (nnmail-split-it (car split-rest)))
1193                 (unless (memq sp split-result)
1194                   (push sp split-result))))))
1195         split-result))
1196
1197      ;; Not in cache, compute a regexp for the field/value pair.
1198      (t
1199       (let* ((field (nth 0 split))
1200              (value (nth 1 split))
1201              partial regexp)
1202         (if (symbolp value)
1203             (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1204         (if (and (>= (length value) 2)
1205                  (string= ".*" (substring value 0 2)))
1206             (setq value (substring value 2)
1207                   partial ""))
1208         (setq regexp (concat "^\\(\\("
1209                              (if (symbolp field)
1210                                  (cdr (assq field nnmail-split-abbrev-alist))
1211                                field)
1212                              "\\):.*\\)"
1213                              (or partial "\\<")
1214                              "\\("
1215                              value
1216                              "\\)\\>"))
1217         (push (cons split regexp) nnmail-split-cache)
1218         ;; Now that it's in the cache, just call nnmail-split-it again
1219         ;; on the same split, which will find it immediately in the cache.
1220         (nnmail-split-it split))))))
1221
1222 (defun nnmail-expand-newtext (newtext)
1223   (let ((len (length newtext))
1224         (pos 0)
1225         c expanded beg N did-expand)
1226     (while (< pos len)
1227       (setq beg pos)
1228       (while (and (< pos len)
1229                   (not (= (aref newtext pos) ?\\)))
1230         (setq pos (1+ pos)))
1231       (unless (= beg pos)
1232         (push (substring newtext beg pos) expanded))
1233       (when (< pos len)
1234         ;; We hit a \; expand it.
1235         (setq did-expand t
1236               pos (1+ pos)
1237               c (aref newtext pos))
1238         (if (not (or (= c ?\&)
1239                      (and (>= c ?1)
1240                           (<= c ?9))))
1241             ;; \ followed by some character we don't expand.
1242             (push (char-to-string c) expanded)
1243           ;; \& or \N
1244           (if (= c ?\&)
1245               (setq N 0)
1246             (setq N (- c ?0)))
1247           (when (match-beginning N)
1248             (push (buffer-substring (match-beginning N) (match-end N))
1249                   expanded))))
1250       (setq pos (1+ pos)))
1251     (if did-expand
1252         (apply 'concat (nreverse expanded))
1253       newtext)))
1254
1255 ;; Activate a backend only if it isn't already activated.
1256 ;; If FORCE, re-read the active file even if the backend is
1257 ;; already activated.
1258 (defun nnmail-activate (backend &optional force)
1259   (nnheader-init-server-buffer)
1260   (let (file timestamp file-time)
1261     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1262             force
1263             (and (setq file (ignore-errors
1264                               (symbol-value (intern (format "%s-active-file"
1265                                                             backend)))))
1266                  (setq file-time (nth 5 (file-attributes file)))
1267                  (or (not
1268                       (setq timestamp
1269                             (condition-case ()
1270                                 (symbol-value (intern
1271                                                (format "%s-active-timestamp"
1272                                                        backend)))
1273                               (error 'none))))
1274                      (not (consp timestamp))
1275                      (equal timestamp '(0 0))
1276                      (> (nth 0 file-time) (nth 0 timestamp))
1277                      (and (= (nth 0 file-time) (nth 0 timestamp))
1278                           (> (nth 1 file-time) (nth 1 timestamp))))))
1279         (save-excursion
1280           (or (eq timestamp 'none)
1281               (set (intern (format "%s-active-timestamp" backend))
1282                    file-time))
1283           (funcall (intern (format "%s-request-list" backend)))))
1284     t))
1285
1286 (defun nnmail-message-id ()
1287   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1288
1289 ;;;
1290 ;;; nnmail duplicate handling
1291 ;;;
1292
1293 (defvar nnmail-cache-buffer nil)
1294
1295 (defun nnmail-cache-open ()
1296   (if (or (not nnmail-treat-duplicates)
1297           (and nnmail-cache-buffer
1298                (buffer-name nnmail-cache-buffer)))
1299       ()                                ; The buffer is open.
1300     (save-excursion
1301       (set-buffer
1302        (setq nnmail-cache-buffer
1303              (get-buffer-create " *nnmail message-id cache*")))
1304       (when (file-exists-p nnmail-message-id-cache-file)
1305         (nnheader-insert-file-contents nnmail-message-id-cache-file))
1306       (set-buffer-modified-p nil)
1307       (current-buffer))))
1308
1309 (defun nnmail-cache-close ()
1310   (when (and nnmail-cache-buffer
1311              nnmail-treat-duplicates
1312              (buffer-name nnmail-cache-buffer)
1313              (buffer-modified-p nnmail-cache-buffer))
1314     (save-excursion
1315       (set-buffer nnmail-cache-buffer)
1316       ;; Weed out the excess number of Message-IDs.
1317       (goto-char (point-max))
1318       (when (search-backward "\n" nil t nnmail-message-id-cache-length)
1319         (progn
1320           (beginning-of-line)
1321           (delete-region (point-min) (point))))
1322       ;; Save the buffer.
1323       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1324           (make-directory (file-name-directory nnmail-message-id-cache-file)
1325                           t))
1326       (nnmail-write-region (point-min) (point-max)
1327                            nnmail-message-id-cache-file nil 'silent)
1328       (set-buffer-modified-p nil)
1329       (setq nnmail-cache-buffer nil)
1330       (kill-buffer (current-buffer)))))
1331
1332 (defun nnmail-cache-insert (id)
1333   (when nnmail-treat-duplicates
1334     (unless (gnus-buffer-live-p nnmail-cache-buffer)
1335       (nnmail-cache-open))
1336     (save-excursion
1337       (set-buffer nnmail-cache-buffer)
1338       (goto-char (point-max))
1339       (insert id "\n"))))
1340
1341 (defun nnmail-cache-id-exists-p (id)
1342   (when nnmail-treat-duplicates
1343     (save-excursion
1344       (set-buffer nnmail-cache-buffer)
1345       (goto-char (point-max))
1346       (search-backward id nil t))))
1347
1348 (defun nnmail-fetch-field (header)
1349   (save-excursion
1350     (save-restriction
1351       (message-narrow-to-head)
1352       (message-fetch-field header))))
1353
1354 (defun nnmail-check-duplication (message-id func artnum-func)
1355   (run-hooks 'nnmail-prepare-incoming-message-hook)
1356   ;; If this is a duplicate message, then we do not save it.
1357   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1358          (case-fold-search t)
1359          (action (when duplication
1360                    (cond
1361                     ((memq nnmail-treat-duplicates '(warn delete))
1362                      nnmail-treat-duplicates)
1363                     ((nnheader-functionp nnmail-treat-duplicates)
1364                      (funcall nnmail-treat-duplicates message-id))
1365                     (t
1366                      nnmail-treat-duplicates))))
1367          group-art)
1368     ;; We insert a line that says what the mail source is.
1369     (let ((case-fold-search t))
1370       (goto-char (point-min))
1371       (re-search-forward "^message-id[ \t]*:" nil t)
1372       (beginning-of-line)
1373       (insert (format "X-Gnus-Mail-Source: %s\n" mail-source-string)))
1374
1375     ;; Let the backend save the article (or not).
1376     (cond
1377      ((not duplication)
1378       (funcall func (setq group-art
1379                           (nreverse (nnmail-article-group artnum-func))))
1380       (nnmail-cache-insert message-id))
1381      ((eq action 'delete)
1382       (setq group-art nil))
1383      ((eq action 'warn)
1384       ;; We insert a warning.
1385       (let ((case-fold-search t))
1386         (goto-char (point-min))
1387         (re-search-forward "^message-id[ \t]*:" nil t)
1388         (beginning-of-line)
1389         (insert
1390          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1391         (funcall func (setq group-art
1392                             (nreverse (nnmail-article-group artnum-func))))))
1393      (t
1394       (funcall func (setq group-art
1395                           (nreverse (nnmail-article-group artnum-func))))))
1396     ;; Add the group-art list to the history list.
1397     (if group-art
1398         (push group-art nnmail-split-history)
1399       (delete-region (point-min) (point-max)))))
1400
1401 ;;; Get new mail.
1402
1403 (defvar nnmail-fetched-sources nil)
1404
1405 (defun nnmail-get-value (&rest args)
1406   (let ((sym (intern (apply 'format args))))
1407     (when (boundp sym)
1408       (symbol-value sym))))
1409
1410 (defun nnmail-get-new-mail (method exit-func temp
1411                                    &optional group spool-func)
1412   "Read new incoming mail."
1413   (let* ((sources (or mail-sources
1414                       (if (listp nnmail-spool-file) nnmail-spool-file
1415                         (list nnmail-spool-file))))
1416          fetching-sources
1417          (group-in group)
1418          (i 0)
1419          (new 0)
1420          (total 0)
1421          incoming incomings source)
1422     (when (and (nnmail-get-value "%s-get-new-mail" method)
1423                nnmail-spool-file)
1424       (while (setq source (pop sources))
1425         ;; Be compatible with old values.
1426         (cond
1427          ((stringp source)
1428           (setq source
1429                 (cond
1430                  ((string-match "^po:" source)
1431                   (list 'pop :user (substring source (match-end 0))))
1432                  ((file-directory-p source)
1433                   (list 'directory :path source))
1434                  (t
1435                   (list 'file :path source)))))
1436          ((eq source 'procmail)
1437           (message "Invalid value for nnmail-spool-file: `procmail'")
1438           nil))
1439         ;; Hack to only fetch the contents of a single group's spool file.
1440         (when (and (eq (car source) 'directory)
1441                    group)
1442           (mail-source-bind (directory source)
1443             (setq source (append source
1444                                  (list
1445                                   :predicate
1446                                   `(lambda (file)
1447                                      (string-match
1448                                       ,(concat
1449                                         (regexp-quote (concat group suffix))
1450                                         "$")
1451                                       file)))))))
1452         (when nnmail-fetched-sources
1453           (if (member source nnmail-fetched-sources)
1454               (setq source nil)
1455             (push source nnmail-fetched-sources)
1456             (push source fetching-sources)))))
1457     (when fetching-sources
1458       ;; We first activate all the groups.
1459       (nnmail-activate method)
1460       ;; Allow the user to hook.
1461       (run-hooks 'nnmail-pre-get-new-mail-hook)
1462       ;; Open the message-id cache.
1463       (nnmail-cache-open)
1464       ;; The we go through all the existing mail source specification
1465       ;; and fetch the mail from each.
1466       (while (setq source (pop fetching-sources))
1467         (nnheader-message 4 "%s: Reading incoming mail from %s..."
1468                           method (car source))
1469         (when (setq new
1470                     (mail-source-fetch
1471                      source
1472                      `(lambda (file orig-file)
1473                         (nnmail-split-incoming
1474                          file ',(intern (format "%s-save-mail" method))
1475                          ',spool-func
1476                          (nnmail-get-split-group orig-file source)
1477                          ',(intern (format "%s-active-number" method))))))
1478           (incf total new)
1479           (incf i)))
1480       ;; If we did indeed read any incoming spools, we save all info.
1481       (if (zerop total)
1482           (nnheader-message 4 "%s: Reading incoming mail (no new mail)...done"
1483                             method (car source))
1484         (nnmail-save-active
1485          (nnmail-get-value "%s-group-alist" method)
1486          (nnmail-get-value "%s-active-file" method))
1487         (when exit-func
1488           (funcall exit-func))
1489         (run-hooks 'nnmail-read-incoming-hook)
1490         (nnheader-message 4 "%s: Reading incoming mail (%d new)...done" method
1491                           total))
1492       ;; Close the message-id cache.
1493       (nnmail-cache-close)
1494       ;; Allow the user to hook.
1495       (run-hooks 'nnmail-post-get-new-mail-hook))))
1496
1497 (defun nnmail-expired-article-p (group time force &optional inhibit)
1498   "Say whether an article that is TIME old in GROUP should be expired."
1499   (if force
1500       t
1501     (let ((days (or (and nnmail-expiry-wait-function
1502                          (funcall nnmail-expiry-wait-function group))
1503                     nnmail-expiry-wait)))
1504       (cond ((or (eq days 'never)
1505                  (and (not force)
1506                       inhibit))
1507              ;; This isn't an expirable group.
1508              nil)
1509             ((eq days 'immediate)
1510              ;; We expire all articles on sight.
1511              t)
1512             ((equal time '(0 0))
1513              ;; This is an ange-ftp group, and we don't have any dates.
1514              nil)
1515             ((numberp days)
1516              (setq days (days-to-time days))
1517              ;; Compare the time with the current time.
1518              (ignore-errors (time-less-p days (time-since time))))))))
1519
1520 (defun nnmail-check-syntax ()
1521   "Check (and modify) the syntax of the message in the current buffer."
1522   (save-restriction
1523     (message-narrow-to-head)
1524     (let ((case-fold-search t))
1525       (unless (re-search-forward "^Message-ID[ \t]*:" nil t)
1526         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1527
1528 (defun nnmail-write-region (start end filename &optional append visit lockname)
1529   "Do a `write-region', and then set the file modes."
1530   (let ((coding-system-for-write nnmail-file-coding-system)
1531         (pathname-coding-system nnmail-pathname-coding-system))
1532     (write-region start end filename append visit lockname)
1533     (set-file-modes filename nnmail-default-file-modes)))
1534
1535 ;;;
1536 ;;; Status functions
1537 ;;;
1538
1539 (defun nnmail-replace-status (name value)
1540   "Make status NAME and VALUE part of the current status line."
1541   (save-restriction
1542     (message-narrow-to-head)
1543     (let ((status (nnmail-decode-status)))
1544       (setq status (delq (member name status) status))
1545       (when value
1546         (push (cons name value) status))
1547       (message-remove-header "status")
1548       (goto-char (point-max))
1549       (insert "Status: " (nnmail-encode-status status) "\n"))))
1550
1551 (defun nnmail-decode-status ()
1552   "Return a status-value alist from STATUS."
1553   (goto-char (point-min))
1554   (when (re-search-forward "^Status: " nil t)
1555     (let (name value status)
1556       (save-restriction
1557         ;; Narrow to the status.
1558         (narrow-to-region
1559          (point)
1560          (if (re-search-forward "^[^ \t]" nil t)
1561              (1- (point))
1562            (point-max)))
1563         ;; Go through all elements and add them to the list.
1564         (goto-char (point-min))
1565         (while (re-search-forward "[^ \t=]+" nil t)
1566           (setq name (match-string 0))
1567           (if (not (eq (char-after) ?=))
1568               ;; Implied "yes".
1569               (setq value "yes")
1570             (forward-char 1)
1571             (if (not (eq (char-after) ?\"))
1572                 (if (not (looking-at "[^ \t]"))
1573                     ;; Implied "no".
1574                     (setq value "no")
1575                   ;; Unquoted value.
1576                   (setq value (match-string 0))
1577                   (goto-char (match-end 0)))
1578               ;; Quoted value.
1579               (setq value (read (current-buffer)))))
1580           (push (cons name value) status)))
1581       status)))
1582
1583 (defun nnmail-encode-status (status)
1584   "Return a status string from STATUS."
1585   (mapconcat
1586    (lambda (elem)
1587      (concat
1588       (car elem) "="
1589       (if (string-match "[ \t]" (cdr elem))
1590           (prin1-to-string (cdr elem))
1591         (cdr elem))))
1592    status " "))
1593
1594 (defun nnmail-split-history ()
1595   "Generate an overview of where the last mail split put articles."
1596   (interactive)
1597   (unless nnmail-split-history
1598     (error "No current split history"))
1599   (with-output-to-temp-buffer "*nnmail split history*"
1600     (with-current-buffer standard-output
1601       (fundamental-mode))               ; for Emacs 20.4+
1602     (let ((history nnmail-split-history)
1603           elem)
1604       (while (setq elem (pop history))
1605         (princ (mapconcat (lambda (ga)
1606                             (concat (car ga) ":" (int-to-string (cdr ga))))
1607                           elem
1608                           ", "))
1609         (princ "\n")))))
1610
1611 (defun nnmail-purge-split-history (group)
1612   "Remove all instances of GROUP from `nnmail-split-history'."
1613   (let ((history nnmail-split-history))
1614     (while history
1615       (setcar history (gnus-delete-if (lambda (e) (string= (car e) group))
1616                                       (car history)))
1617       (pop history))
1618     (setq nnmail-split-history (delq nil nnmail-split-history))))
1619
1620 (defun nnmail-new-mail-p (group)
1621   "Say whether GROUP has new mail."
1622   (let ((his nnmail-split-history)
1623         found)
1624     (while his
1625       (when (assoc group (pop his))
1626         (setq found t
1627               his nil)))
1628     found))
1629
1630 (defun nnmail-within-headers-p ()
1631   "Check to see if point is within the headers of a unix mail message.
1632 Doesn't change point."
1633   (let ((pos (point)))
1634     (save-excursion
1635       (and (nnmail-search-unix-mail-delim-backward)
1636            (not (search-forward "\n\n" pos t))))))
1637
1638 (run-hooks 'nnmail-load-hook)
1639
1640 (provide 'nnmail)
1641
1642 ;;; nnmail.el ends here