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