rmail.el 93.4 KB
Newer Older
Eric S. Raymond's avatar
Eric S. Raymond committed
1 2
;;; rmail.el --- main code of "RMAIL" mail reader for Emacs.

Karl Heuer's avatar
Karl Heuer committed
3
;; Copyright (C) 1985,86,87,88,93,94,95 Free Software Foundation, Inc.
Eric S. Raymond's avatar
Eric S. Raymond committed
4

Eric S. Raymond's avatar
Eric S. Raymond committed
5
;; Maintainer: FSF
Eric S. Raymond's avatar
Eric S. Raymond committed
6
;; Keywords: mail
Eric S. Raymond's avatar
Eric S. Raymond committed
7

Roland McGrath's avatar
Roland McGrath committed
8 9 10 11
;; This file is part of GNU Emacs.

;; GNU Emacs is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
Eric S. Raymond's avatar
Eric S. Raymond committed
12
;; the Free Software Foundation; either version 2, or (at your option)
Roland McGrath's avatar
Roland McGrath committed
13 14 15 16 17 18 19 20 21 22 23
;; any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to
;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.

Eric S. Raymond's avatar
Eric S. Raymond committed
24
;;; Code:
Roland McGrath's avatar
Roland McGrath committed
25 26 27 28 29 30

;; Souped up by shane@mit-ajax based on ideas of rlk@athena.mit.edu
;;   New features include attribute and keyword support, message
;;   selection by dispatch table, summary by attributes and keywords,
;;   expunging by dispatch table, sticky options for file commands.

31 32 33 34 35 36 37
;; Extended by Bob Weiner of Motorola
;;   New features include: rmail and rmail-summary buffers remain
;;   synchronized and key bindings basically operate the same way in both
;;   buffers, summary by topic or by regular expression, rmail-reply-prefix
;;   variable, and a bury rmail buffer (wipe) command.
;;

Roland McGrath's avatar
Roland McGrath committed
38
(require 'mail-utils)
39 40 41 42

;; For Emacs V18 compatibility
(and (not (fboundp 'buffer-disable-undo))
     (fboundp 'buffer-flush-undo)
43
     (defalias 'buffer-disable-undo 'buffer-flush-undo))
44 45

; These variables now declared in paths.el.
Roland McGrath's avatar
Roland McGrath committed
46 47 48 49 50 51 52
;(defvar rmail-spool-directory "/usr/spool/mail/"
;  "This is the name of the directory used by the system mailer for\n\
;delivering new mail.  It's name should end with a slash.")
;(defvar rmail-file-name
;  (expand-file-name "~/RMAIL")
;  "")

53 54 55
(defvar rmail-movemail-program nil
  "If non-nil, name of program for fetching new mail.")

Roland McGrath's avatar
Roland McGrath committed
56 57 58
;;;###autoload
(defvar rmail-dont-reply-to-names nil "\
*A regexp specifying names to prune of reply to messages.
Richard M. Stallman's avatar
Richard M. Stallman committed
59
A value of nil means exclude your own name only.")
Roland McGrath's avatar
Roland McGrath committed
60 61 62 63 64 65 66

;;;###autoload
(defvar rmail-default-dont-reply-to-names "info-" "\
A regular expression specifying part of the value of the default value of
the variable `rmail-dont-reply-to-names', for when the user does not set
`rmail-dont-reply-to-names' explicitly.  (The other part of the default
value is the user's name.)
Richard M. Stallman's avatar
Richard M. Stallman committed
67
It is useful to set this variable in the site customization file.")
Roland McGrath's avatar
Roland McGrath committed
68 69

;;;###autoload
70
(defvar rmail-ignored-headers "^via:\\|^mail-from:\\|^origin:\\|^status:\\|^received:\\|^x400-originator:\\|^x400-recipients:\\|^x400-received:\\|^x400-mts-identifier:\\|^x400-content-type:\\|^\\(resent-\\|\\)message-id:\\|^summary-line:"
71
  "*Regexp to match Header fields that Rmail should normally hide.")
Roland McGrath's avatar
Roland McGrath committed
72

73 74 75 76 77 78
;;;###autoload
(defvar rmail-displayed-headers nil
  "*Regexp to match Header fields that Rmail should display.
If nil, display all header fields except those matched by
`rmail-ignored-headers'.")

79 80 81 82
;;;###autoload
(defvar rmail-retry-ignored-headers nil "\
*Headers that should be stripped when retrying a failed message.")

83 84
;;;###autoload
(defvar rmail-highlighted-headers "^From:\\|^Subject:" "\
85
*Regexp to match Header fields that Rmail should normally highlight.
86 87
A value of nil means don't highlight.
See also `rmail-highlight-face'.")
88

89 90 91 92
;;;###autoload
(defvar rmail-highlight-face nil "\
*Face used by Rmail for highlighting headers.")

Roland McGrath's avatar
Roland McGrath committed
93 94 95 96 97
;;;###autoload
(defvar rmail-delete-after-output nil "\
*Non-nil means automatically delete a message that is copied to a file.")

;;;###autoload
98
(defvar rmail-primary-inbox-list nil "\
99 100 101
*List of files which are inboxes for user's primary mail file `~/RMAIL'.
`nil' means the default, which is (\"/usr/spool/mail/$USER\")
\(the name varies depending on the operating system,
Roland McGrath's avatar
Roland McGrath committed
102 103
and the value of the environment variable MAIL overrides it).")

104 105 106 107
;;;###autoload
(defvar rmail-mail-new-frame nil
  "*Non-nil means Rmail makes a new frame for composing outgoing mail.")

108 109 110 111 112 113 114
;;;###autoload
(defvar rmail-secondary-file-directory "~/"
  "*Directory for additional secondary Rmail files.")
;;;###autoload
(defvar rmail-secondary-file-regexp "\\.xmail$"
  "*Regexp for which files are secondary Rmail files.")

115 116 117
;; These may be altered by site-init.el to match the format of mmdf files
;;  delimiting used on a given host (delim1 and delim2 from the config
;;  files).
Roland McGrath's avatar
Roland McGrath committed
118 119 120 121 122 123 124

(defvar mmdf-delim1 "^\001\001\001\001\n"
  "Regexp marking the start of an mmdf message")
(defvar mmdf-delim2 "^\001\001\001\001\n"
  "Regexp marking the end of an mmdf message")

(defvar rmail-message-filter nil
Karl Heuer's avatar
Karl Heuer committed
125 126
  "If non nil, a filter function for new messages in RMAIL.
Called with region narrowed to the message, including headers.")
Roland McGrath's avatar
Roland McGrath committed
127

128 129 130
(defvar rmail-reply-prefix "Re: "
  "String to prepend to Subject line when replying to a message.")

Karl Heuer's avatar
Karl Heuer committed
131 132 133 134 135
;; Some mailers use "Re(2):" or "Re^2:" or "Re: Re:".
;; This pattern should catch all the common variants.
(defvar rmail-reply-regexp "\\`\\(Re\\(([0-9]+)\\|\\^[0-9]+\\)?: *\\)*"
  "Regexp to delete from Subject line before inserting rmail-reply-prefix.")

136 137 138
(defvar rmail-display-summary nil
  "If non nil, the summary buffer is always displayed.")

Roland McGrath's avatar
Roland McGrath committed
139 140 141 142 143 144 145 146 147 148 149 150
(defvar rmail-mode-map nil)

(defvar rmail-inbox-list nil)
(defvar rmail-keywords nil)

;; Message counters and markers.  Deleted flags.

(defvar rmail-current-message nil)
(defvar rmail-total-messages nil)
(defvar rmail-message-vector nil)
(defvar rmail-deleted-vector nil)

151 152
(defvar rmail-overlay-list nil)

153 154 155 156 157 158 159 160 161
(defvar rmail-font-lock-keywords
  '(("^\\(From\\|Sender\\):" . font-lock-function-name-face)
    ("^Reply-To:.*$" . font-lock-function-name-face)
    ("^Subject:" . font-lock-comment-face)
    ("^\\(To\\|Apparently-To\\|Cc\\):" . font-lock-keyword-face)
    ("^[ \t]*\\sw*[>|}].*$" . font-lock-reference-face)		; Citation.
    ("^\\(X-[A-Za-z0-9-]+\\|In-reply-to\\|Date\\):.*$" . font-lock-string-face))
  "Additional expressions to highlight in Rmail mode.")

Roland McGrath's avatar
Roland McGrath committed
162 163 164 165 166 167 168 169 170
;; These are used by autoloaded rmail-summary.

(defvar rmail-summary-buffer nil)
(defvar rmail-summary-vector nil)

;; `Sticky' default variables.

;; Last individual label specified to a or k.
(defvar rmail-last-label nil)
171
;; Last set of values specified to C-M-n, C-M-p, C-M-s or C-M-l.
Roland McGrath's avatar
Roland McGrath committed
172
(defvar rmail-last-multi-labels nil)
173
(defvar rmail-last-regexp nil)
174
(defvar rmail-default-file "~/xmail"
175
  "*Default file name for \\[rmail-output].")
176
(defvar rmail-default-rmail-file "~/XMAIL"
177
  "*Default file name for \\[rmail-output-to-rmail-file].")
Jim Blandy's avatar
Jim Blandy committed
178

Jim Blandy's avatar
Jim Blandy committed
179 180 181 182
;;; Regexp matching the delimiter of messages in UNIX mail format
;;; (UNIX From lines), minus the initial ^.  Note that if you change
;;; this expression, you must change the code in rmail-nuke-pinhead-header
;;; that knows the exact ordering of the \\( \\) subexpressions.
Jim Blandy's avatar
Jim Blandy committed
183
(defvar rmail-unix-mail-delimiter
Jim Blandy's avatar
Jim Blandy committed
184
  (let ((time-zone-regexp
185
	 (concat "\\([A-Z]?[A-Z][A-Z][A-Z]\\( DST\\)?"
Jim Blandy's avatar
Jim Blandy committed
186 187 188 189 190 191 192 193 194 195
		 "\\|[-+]?[0-9][0-9][0-9][0-9]"
		 "\\|"
		 "\\) *")))
    (concat
     "From "

     ;; Username, perhaps with a quoted section that can contain spaces.
     "\\("
     "[^ \n]*"
     "\\(\\|\".*\"[^ \n]*\\)"
196
     "\\|<[^<>\n]+>"
Jim Blandy's avatar
Jim Blandy committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
     "\\)  ?"

     ;; The time the message was sent.
     "\\([^ \n]*\\) *"			; day of the week
     "\\([^ ]*\\) *"			; month
     "\\([0-9]*\\) *"			; day of month
     "\\([0-9:]*\\) *"			; time of day

     ;; Perhaps a time zone, specified by an abbreviation, or by a
     ;; numeric offset.
     time-zone-regexp

     ;; The year.
     " [0-9][0-9]\\([0-9]*\\) *"

     ;; On some systems the time zone can appear after the year, too.
     time-zone-regexp

Karl Heuer's avatar
Karl Heuer committed
215 216
     ;; Old uucp cruft.
     "\\(remote from .*\\)?"
Jim Blandy's avatar
Jim Blandy committed
217 218 219 220

     "\n"))
  nil)

221 222 223
;; Perform BODY in the summary buffer
;; in such a way that its cursor is properly updated in its own window.
(defmacro rmail-select-summary (&rest body)
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
  (` (let ((total rmail-total-messages))
       (if (rmail-summary-displayed)
	   (let ((window (selected-window)))
	     (save-excursion
	       (unwind-protect
		   (progn
		     (pop-to-buffer rmail-summary-buffer)
		     ;; rmail-total-messages is a buffer-local var
		     ;; in the rmail buffer.
		     ;; This way we make it available for the body
		     ;; even tho the rmail buffer is not current.
		     (let ((rmail-total-messages total))
		       (,@ body)))
		 (select-window window))))
	 (save-excursion
	   (set-buffer rmail-summary-buffer)
	   (let ((rmail-total-messages total))
	     (,@ body))))
       (rmail-maybe-display-summary))))
Roland McGrath's avatar
Roland McGrath committed
243 244 245 246 247 248

;;;; *** Rmail Mode ***

;;;###autoload
(defun rmail (&optional file-name-arg)
  "Read and edit incoming mail.
249
Moves messages into file named by `rmail-file-name' (a babyl format file)
Roland McGrath's avatar
Roland McGrath committed
250 251 252
 and edits that file in RMAIL Mode.
Type \\[describe-mode] once editing that file, for a list of RMAIL commands.

253 254 255
May be called with file name as argument; then performs rmail editing on
that file, but does not copy any new mail into the file.
Interactively, if you supply a prefix argument, then you
256 257 258
have a chance to specify a file name with the minibuffer.

If `rmail-display-summary' is non-nil, make a summary for this RMAIL file."
Roland McGrath's avatar
Roland McGrath committed
259 260 261 262 263 264 265 266 267 268 269
  (interactive (if current-prefix-arg
		   (list (read-file-name "Run rmail on RMAIL file: "
					 nil nil t))))
  (let* ((file-name (expand-file-name (or file-name-arg rmail-file-name)))
	 (existed (get-file-buffer file-name)))
    ;; Like find-file, but in the case where a buffer existed
    ;; and the file was reverted, recompute the message-data.
    (if (and existed (not (verify-visited-file-modtime existed)))
	(progn
	  ;; Don't be confused by apparent local-variables spec
	  ;; in the last message in the RMAIL file.
270
	  (let ((enable-local-variables nil))
Roland McGrath's avatar
Roland McGrath committed
271
	    (find-file file-name))
272 273
	  (if (and (verify-visited-file-modtime existed)
		   (eq major-mode 'rmail-mode))
Roland McGrath's avatar
Roland McGrath committed
274 275
	      (progn (rmail-forget-messages)
		     (rmail-set-message-counters))))
276
      (let ((enable-local-variables nil))
Roland McGrath's avatar
Roland McGrath committed
277
	(find-file file-name)))
278 279
    (if (eq major-mode 'rmail-edit-mode)
	(error "Exit Rmail Edit mode before getting new mail."))
Roland McGrath's avatar
Roland McGrath committed
280 281 282 283 284 285 286 287 288 289 290 291
    (if (and existed (> (buffer-size) 0))
	;; Buffer not new and not empty; ensure in proper mode, but that's all.
	(or (eq major-mode 'rmail-mode)
	    (rmail-mode-2))
      (rmail-mode-2)
      ;; Convert all or part to Babyl file if possible.
      (rmail-convert-file)
      (goto-char (point-max))
      (if (null rmail-inbox-list)
	  (progn
	    (rmail-set-message-counters)
	    (rmail-show-message))))
292 293 294
    (or (and (null file-name-arg)
	     (rmail-get-new-mail))
	(rmail-show-message (rmail-first-unseen-message)))
295 296
    (if rmail-display-summary (rmail-summary))
    (rmail-construct-io-menu)))
Roland McGrath's avatar
Roland McGrath committed
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327

;; Given the value of MAILPATH, return a list of inbox file names.
;; This is turned off because it is not clear that the user wants
;; all these inboxes to feed into the primary rmail file.
; (defun rmail-convert-mailpath (string)
;   (let (idx list)
;     (while (setq idx (string-match "[%:]" string))
;       (let ((this (substring string 0 idx)))
; 	(setq string (substring string (1+ idx)))
; 	(setq list (cons (if (string-match "%" this)
; 			     (substring this 0 (string-match "%" this))
; 			   this)
; 			 list))))
;     list))

; I have checked that adding "-*- rmail -*-" to the BABYL OPTIONS line
; will not cause emacs 18.55 problems.

(defun rmail-convert-file ()
  (let (convert)
    (widen)
    (goto-char (point-min))
    ;; If file doesn't start like a Babyl file,
    ;; convert it to one, by adding a header and converting each message.
    (cond ((looking-at "BABYL OPTIONS:"))
	  ((looking-at "Version: 5\n")
	   ;; Losing babyl file made by old version of Rmail.
	   ;; Just fix the babyl file header; don't make a new one,
	   ;; so we don't lose the Labels: file attribute, etc.
	   (let ((buffer-read-only nil))
	     (insert "BABYL OPTIONS: -*- rmail -*-\n")))
328 329 330
	  ((equal (point-min) (point-max))
	   ;; Empty RMAIL file.  Just insert the header.
	   (rmail-insert-rmail-file-header))
Roland McGrath's avatar
Roland McGrath committed
331
	  (t
332
	   ;; Non-empty file in non-RMAIL format.  Add header and convert.
Roland McGrath's avatar
Roland McGrath committed
333 334 335 336 337 338
	   (setq convert t)
	   (rmail-insert-rmail-file-header)))
    ;; If file was not a Babyl file or if there are
    ;; Unix format messages added at the end,
    ;; convert file as necessary.
    (if (or convert
339 340 341 342 343
	    (save-excursion
	      (goto-char (point-max))
	      (search-backward "\^_")
	      (forward-char 1)
	      (looking-at "\n*From ")))
Roland McGrath's avatar
Roland McGrath committed
344 345
	(let ((buffer-read-only nil))
	  (message "Converting to Babyl format...")
346 347 348 349 350
	  ;; If file needs conversion, convert it all,
	  ;; except for the BABYL header.
	  ;; (rmail-convert-to-babyl-format would delete the header.)
	  (goto-char (point-min))
	  (search-forward "\n\^_" nil t)
351
	  (narrow-to-region (point) (point-max))
Roland McGrath's avatar
Roland McGrath committed
352 353 354
	  (rmail-convert-to-babyl-format)
	  (message "Converting to Babyl format...done")))))

355 356
;;; I have checked that adding "-*- rmail -*-" to the BABYL OPTIONS line
;;; will not cause emacs 18.55 problems.
Roland McGrath's avatar
Roland McGrath committed
357 358 359 360 361 362 363 364 365 366 367 368 369 370

(defun rmail-insert-rmail-file-header ()
  (let ((buffer-read-only nil))
    (insert "BABYL OPTIONS: -*- rmail -*-
Version: 5
Labels:
Note:   This is the header of an rmail file.
Note:   If you are seeing it in rmail,
Note:    it means the file has no messages in it.\n\^_")))

(if rmail-mode-map
    nil
  (setq rmail-mode-map (make-keymap))
  (suppress-keymap rmail-mode-map)
371 372 373 374 375 376 377 378 379 380 381 382 383
  (define-key rmail-mode-map "a"      'rmail-add-label)
  (define-key rmail-mode-map "b"      'rmail-bury)
  (define-key rmail-mode-map "c"      'rmail-continue)
  (define-key rmail-mode-map "d"      'rmail-delete-forward)
  (define-key rmail-mode-map "\C-d"   'rmail-delete-backward)
  (define-key rmail-mode-map "e"      'rmail-edit-current-message)
  (define-key rmail-mode-map "f"      'rmail-forward)
  (define-key rmail-mode-map "g"      'rmail-get-new-mail)
  (define-key rmail-mode-map "h"      'rmail-summary)
  (define-key rmail-mode-map "i"      'rmail-input)
  (define-key rmail-mode-map "j"      'rmail-show-message)
  (define-key rmail-mode-map "k"      'rmail-kill-label)
  (define-key rmail-mode-map "l"      'rmail-summary-by-labels)
Roland McGrath's avatar
Roland McGrath committed
384 385 386 387
  (define-key rmail-mode-map "\e\C-h" 'rmail-summary)
  (define-key rmail-mode-map "\e\C-l" 'rmail-summary-by-labels)
  (define-key rmail-mode-map "\e\C-r" 'rmail-summary-by-recipients)
  (define-key rmail-mode-map "\e\C-s" 'rmail-summary-by-regexp)
388 389 390 391 392 393 394 395 396 397 398 399 400
  (define-key rmail-mode-map "\e\C-t" 'rmail-summary-by-topic)
  (define-key rmail-mode-map "m"      'rmail-mail)
  (define-key rmail-mode-map "\em"    'rmail-retry-failure)
  (define-key rmail-mode-map "n"      'rmail-next-undeleted-message)
  (define-key rmail-mode-map "\en"    'rmail-next-message)
  (define-key rmail-mode-map "\e\C-n" 'rmail-next-labeled-message)
  (define-key rmail-mode-map "o"      'rmail-output-to-rmail-file)
  (define-key rmail-mode-map "\C-o"   'rmail-output)
  (define-key rmail-mode-map "p"      'rmail-previous-undeleted-message)
  (define-key rmail-mode-map "\ep"    'rmail-previous-message)
  (define-key rmail-mode-map "\e\C-p" 'rmail-previous-labeled-message)
  (define-key rmail-mode-map "q"      'rmail-quit)
  (define-key rmail-mode-map "r"      'rmail-reply)
401
;; I find I can't live without the default M-r command -- rms.
402 403 404 405 406 407 408 409 410 411 412 413 414
;;  (define-key rmail-mode-map "\er"  'rmail-search-backwards)
  (define-key rmail-mode-map "s"      'rmail-expunge-and-save)
  (define-key rmail-mode-map "\es"    'rmail-search)
  (define-key rmail-mode-map "t"      'rmail-toggle-header)
  (define-key rmail-mode-map "u"      'rmail-undelete-previous-message)
  (define-key rmail-mode-map "w"      'rmail-edit-current-message)
  (define-key rmail-mode-map "x"      'rmail-expunge)
  (define-key rmail-mode-map "."      'rmail-beginning-of-message)
  (define-key rmail-mode-map "<"      'rmail-first-message)
  (define-key rmail-mode-map ">"      'rmail-last-message)
  (define-key rmail-mode-map " "      'scroll-up)
  (define-key rmail-mode-map "\177"   'scroll-down)
  (define-key rmail-mode-map "?"      'describe-mode)
415 416 417 418 419 420
  (define-key rmail-mode-map "\C-c\C-s\C-d" 'rmail-sort-by-date)
  (define-key rmail-mode-map "\C-c\C-s\C-s" 'rmail-sort-by-subject)
  (define-key rmail-mode-map "\C-c\C-s\C-a" 'rmail-sort-by-author)
  (define-key rmail-mode-map "\C-c\C-s\C-r" 'rmail-sort-by-recipient)
  (define-key rmail-mode-map "\C-c\C-s\C-c" 'rmail-sort-by-correspondent)
  (define-key rmail-mode-map "\C-c\C-s\C-l" 'rmail-sort-by-lines)
421
  (define-key rmail-mode-map "\C-c\C-s\C-k" 'rmail-sort-by-keywords)
422 423
  (define-key rmail-mode-map "\C-c\C-n" 'rmail-next-same-subject)
  (define-key rmail-mode-map "\C-c\C-p" 'rmail-previous-same-subject)
424
  )
425 426 427 428 429 430

(define-key rmail-mode-map [menu-bar] (make-sparse-keymap))

(define-key rmail-mode-map [menu-bar classify]
  (cons "Classify" (make-sparse-keymap "Classify")))

431
(define-key rmail-mode-map [menu-bar classify input-menu]
432
  nil)
433 434

(define-key rmail-mode-map [menu-bar classify output-menu]
435
  nil)
436

437
(define-key rmail-mode-map [menu-bar classify output-inbox]
438
  '("Output (inbox)..." . rmail-output))
439 440

(define-key rmail-mode-map [menu-bar classify output]
441
  '("Output (Rmail)..." . rmail-output-to-rmail-file))
442 443

(define-key rmail-mode-map [menu-bar classify kill-label]
444
  '("Kill Label..." . rmail-kill-label))
445 446

(define-key rmail-mode-map [menu-bar classify add-label]
447
  '("Add Label..." . rmail-add-label))
448 449 450 451 452

(define-key rmail-mode-map [menu-bar summary]
  (cons "Summary" (make-sparse-keymap "Summary")))

(define-key rmail-mode-map [menu-bar summary labels]
453
  '("By Labels..." . rmail-summary-by-labels))
454 455

(define-key rmail-mode-map [menu-bar summary recipients]
456
  '("By Recipients..." . rmail-summary-by-recipients))
457 458

(define-key rmail-mode-map [menu-bar summary topic]
459
  '("By Topic..." . rmail-summary-by-topic))
460 461

(define-key rmail-mode-map [menu-bar summary regexp]
462
  '("By Regexp..." . rmail-summary-by-regexp))
463 464 465 466 467 468

(define-key rmail-mode-map [menu-bar summary all]
  '("All" . rmail-summary))

(define-key rmail-mode-map [menu-bar mail]
  (cons "Mail" (make-sparse-keymap "Mail")))
469

470
(define-key rmail-mode-map [menu-bar mail rmail-get-new-mail]
471 472 473
  '("Get New Mail" . rmail-get-new-mail))

(define-key rmail-mode-map [menu-bar mail lambda]
474
  '("----"))
475

476 477 478
(define-key rmail-mode-map [menu-bar mail continue]
  '("Continue" . rmail-continue))

479
(define-key rmail-mode-map [menu-bar mail resend]
480
  '("Re-send..." . rmail-resend))
481

482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
(define-key rmail-mode-map [menu-bar mail forward]
  '("Forward" . rmail-forward))

(define-key rmail-mode-map [menu-bar mail retry]
  '("Retry" . rmail-retry-failure))

(define-key rmail-mode-map [menu-bar mail reply]
  '("Reply" . rmail-reply))

(define-key rmail-mode-map [menu-bar mail mail]
  '("Mail" . rmail-mail))

(define-key rmail-mode-map [menu-bar delete]
  (cons "Delete" (make-sparse-keymap "Delete")))

(define-key rmail-mode-map [menu-bar delete expunge/save]
  '("Expunge/Save" . rmail-expunge-and-save))
Roland McGrath's avatar
Roland McGrath committed
499

500 501 502 503 504 505 506 507 508 509 510 511 512
(define-key rmail-mode-map [menu-bar delete expunge]
  '("Expunge" . rmail-expunge))

(define-key rmail-mode-map [menu-bar delete undelete]
  '("Undelete" . rmail-undelete-previous-message))

(define-key rmail-mode-map [menu-bar delete delete]
  '("Delete" . rmail-delete-forward))

(define-key rmail-mode-map [menu-bar move]
  (cons "Move" (make-sparse-keymap "Move")))

(define-key rmail-mode-map [menu-bar move search-back]
513
  '("Search Back..." . rmail-search-backwards))
514 515

(define-key rmail-mode-map [menu-bar move search]
516
  '("Search..." . rmail-search))
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535

(define-key rmail-mode-map [menu-bar move previous]
  '("Previous Nondeleted" . rmail-previous-undeleted-message))

(define-key rmail-mode-map [menu-bar move next]
  '("Next Nondeleted" . rmail-next-undeleted-message))

(define-key rmail-mode-map [menu-bar move last]
  '("Last" . rmail-last-message))

(define-key rmail-mode-map [menu-bar move first]
  '("First" . rmail-first-message))

(define-key rmail-mode-map [menu-bar move previous]
  '("Previous" . rmail-previous-message))

(define-key rmail-mode-map [menu-bar move next]
  '("Next" . rmail-next-message))

Roland McGrath's avatar
Roland McGrath committed
536 537 538
;; Rmail mode is suitable only for specially formatted data.
(put 'rmail-mode 'mode-class 'special)

539 540 541
(defun rmail-mode-kill-summary ()
  (if rmail-summary-buffer (kill-buffer rmail-summary-buffer)))

542
;;;###autoload
Roland McGrath's avatar
Roland McGrath committed
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
(defun rmail-mode ()
  "Rmail Mode is used by \\<rmail-mode-map>\\[rmail] for editing Rmail files.
All normal editing commands are turned off.
Instead, these commands are available:

\\[rmail-beginning-of-message]	Move point to front of this message (same as \\[beginning-of-buffer]).
\\[scroll-up]	Scroll to next screen of this message.
\\[scroll-down]	Scroll to previous screen of this message.
\\[rmail-next-undeleted-message]	Move to Next non-deleted message.
\\[rmail-previous-undeleted-message]	Move to Previous non-deleted message.
\\[rmail-next-message]	Move to Next message whether deleted or not.
\\[rmail-previous-message]	Move to Previous message whether deleted or not.
\\[rmail-first-message]	Move to the first message in Rmail file.
\\[rmail-last-message]	Move to the last message in Rmail file.
\\[rmail-show-message]	Jump to message specified by numeric position in file.
\\[rmail-search]	Search for string and show message it is found in.
\\[rmail-delete-forward]	Delete this message, move to next nondeleted.
\\[rmail-delete-backward]	Delete this message, move to previous nondeleted.
\\[rmail-undelete-previous-message]	Undelete message.  Tries current message, then earlier messages
	till a deleted message is found.
563
\\[rmail-edit-current-message]	Edit the current message.  \\[rmail-cease-edit] to return to Rmail.
Roland McGrath's avatar
Roland McGrath committed
564 565 566 567
\\[rmail-expunge]	Expunge deleted messages.
\\[rmail-expunge-and-save]	Expunge and save the file.
\\[rmail-quit]       Quit Rmail: expunge, save, then switch to another buffer.
\\[save-buffer] Save without expunging.
568
\\[rmail-get-new-mail]	Move new mail from system spool directory into this file.
Roland McGrath's avatar
Roland McGrath committed
569 570
\\[rmail-mail]	Mail a message (same as \\[mail-other-window]).
\\[rmail-continue]	Continue composing outgoing message started before.
571 572
\\[rmail-reply]	Reply to this message.  Like \\[rmail-mail] but initializes some fields.
\\[rmail-retry-failure]	Send this message again.  Used on a mailer failure message.
Roland McGrath's avatar
Roland McGrath committed
573 574 575 576 577 578 579 580 581
\\[rmail-forward]	Forward this message to another user.
\\[rmail-output-to-rmail-file]       Output this message to an Rmail file (append it).
\\[rmail-output]	Output this message to a Unix-format mail file (append it).
\\[rmail-input]	Input Rmail file.  Run Rmail on that file.
\\[rmail-add-label]	Add label to message.  It will be displayed in the mode line.
\\[rmail-kill-label]	Kill label.  Remove a label from current message.
\\[rmail-next-labeled-message]   Move to Next message with specified label
          (label defaults to last one specified).
          Standard labels: filed, unseen, answered, forwarded, deleted.
582
          Any other label is present only if you add it with \\[rmail-add-label].
Roland McGrath's avatar
Roland McGrath committed
583 584
\\[rmail-previous-labeled-message]   Move to Previous message with specified label
\\[rmail-summary]	Show headers buffer, with a one line summary of each message.
585 586 587 588 589
\\[rmail-summary-by-labels]	Summarize only messages with particular label(s).
\\[rmail-summary-by-recipients]   Summarize only messages with particular recipient(s).
\\[rmail-summary-by-regexp]   Summarize only messages with particular regexp(s).
\\[rmail-summary-by-topic]   Summarize only messages with subject line regexp(s).
\\[rmail-toggle-header]	Toggle display of complete header."
Roland McGrath's avatar
Roland McGrath committed
590 591 592
  (interactive)
  (rmail-mode-2)
  (rmail-set-message-counters)
593
  (rmail-show-message rmail-total-messages))
Roland McGrath's avatar
Roland McGrath committed
594 595 596 597 598 599 600 601 602 603 604

(defun rmail-mode-2 ()
  (kill-all-local-variables)
  (rmail-mode-1)
  (rmail-variables)
  (run-hooks 'rmail-mode-hook))

(defun rmail-mode-1 ()
  (setq major-mode 'rmail-mode)
  (setq mode-name "RMAIL")
  (setq buffer-read-only t)
Richard M. Stallman's avatar
Richard M. Stallman committed
605 606 607 608 609
  ;; No need to auto save RMAIL files in normal circumstances
  ;; because they contain no info except attribute changes
  ;; and deletion of messages.
  ;; The one exception is when messages are copied into an Rmail mode buffer.
  ;; rmail-output-to-rmail-file enables auto save when you do that.
Roland McGrath's avatar
Roland McGrath committed
610 611 612 613 614 615 616 617 618 619 620 621
  (setq buffer-auto-save-file-name nil)
  (if (boundp 'mode-line-modified)
      (setq mode-line-modified "--- ")
    (setq mode-line-format
	  (cons "--- " (cdr (default-value 'mode-line-format)))))
  (use-local-map rmail-mode-map)
  (set-syntax-table text-mode-syntax-table)
  (setq local-abbrev-table text-mode-abbrev-table))

(defun rmail-variables ()
  (make-local-variable 'revert-buffer-function)
  (setq revert-buffer-function 'rmail-revert)
622 623
  (make-local-variable 'font-lock-defaults)
  (setq font-lock-defaults '(rmail-font-lock-keywords t))
Roland McGrath's avatar
Roland McGrath committed
624
  (make-local-variable 'rmail-last-label)
625
  (make-local-variable 'rmail-last-regexp)
Roland McGrath's avatar
Roland McGrath committed
626 627 628 629 630 631 632
  (make-local-variable 'rmail-deleted-vector)
  (make-local-variable 'rmail-summary-buffer)
  (make-local-variable 'rmail-summary-vector)
  (make-local-variable 'rmail-current-message)
  (make-local-variable 'rmail-total-messages)
  (make-local-variable 'require-final-newline)
  (setq require-final-newline nil)
633 634
  (make-local-variable 'rmail-overlay-list)
  (setq rmail-overlay-list nil)
Roland McGrath's avatar
Roland McGrath committed
635 636
  (make-local-variable 'version-control)
  (setq version-control 'never)
637 638
  (make-local-variable 'kill-buffer-hook)
  (add-hook 'kill-buffer-hook 'rmail-mode-kill-summary)
Roland McGrath's avatar
Roland McGrath committed
639 640 641 642 643
  (make-local-variable 'file-precious-flag)
  (setq file-precious-flag t)
  (make-local-variable 'rmail-message-vector)
  (make-local-variable 'rmail-inbox-list)
  (setq rmail-inbox-list (rmail-parse-file-inboxes))
644 645
  ;; Provide default set of inboxes for primary mail file ~/RMAIL.
  (and (null rmail-inbox-list)
646
       (or (equal buffer-file-name (expand-file-name rmail-file-name))
647 648
	   (equal buffer-file-truename
		  (abbreviate-file-name (file-truename rmail-file-name))))
649 650 651 652
       (setq rmail-inbox-list
	     (or rmail-primary-inbox-list
		 (list (or (getenv "MAIL")
			   (concat rmail-spool-directory
653
				   (user-login-name)))))))
Roland McGrath's avatar
Roland McGrath committed
654 655
  (make-local-variable 'rmail-keywords)
  ;; this gets generated as needed
656
  (setq rmail-keywords nil))
Roland McGrath's avatar
Roland McGrath committed
657 658 659

;; Handle M-x revert-buffer done in an rmail-mode buffer.
(defun rmail-revert (arg noconfirm)
660
  (let ((revert-buffer-function (default-value 'revert-buffer-function)))
Roland McGrath's avatar
Roland McGrath committed
661 662 663 664 665 666 667
    ;; Call our caller again, but this time it does the default thing.
    (if (revert-buffer arg noconfirm)
	;; If the user said "yes", and we changed something,
	;; reparse the messages.
	(progn
	  (rmail-convert-file)
	  (goto-char (point-max))
668
	  (rmail-mode)))))
Roland McGrath's avatar
Roland McGrath committed
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691

;; Return a list of files from this buffer's Mail: option.
;; Does not assume that messages have been parsed.
;; Just returns nil if buffer does not look like Babyl format.
(defun rmail-parse-file-inboxes ()
  (save-excursion
    (save-restriction
      (widen)
      (goto-char 1)
      (cond ((looking-at "BABYL OPTIONS:")
	     (search-forward "\n\^_" nil 'move)
	     (narrow-to-region 1 (point))
	     (goto-char 1)
	     (if (search-forward "\nMail:" nil t)
		 (progn
		   (narrow-to-region (point) (progn (end-of-line) (point)))
		   (goto-char (point-min))
		   (mail-parse-comma-list))))))))

(defun rmail-expunge-and-save ()
  "Expunge and save RMAIL file."
  (interactive)
  (rmail-expunge)
692 693 694
  (save-buffer)
  (if (rmail-summary-exists)
      (rmail-select-summary (set-buffer-modified-p nil))))
Roland McGrath's avatar
Roland McGrath committed
695 696 697 698 699 700 701

(defun rmail-quit ()
  "Quit out of RMAIL."
  (interactive)
  (rmail-expunge-and-save)
  ;; Don't switch to the summary buffer even if it was recently visible.
  (if rmail-summary-buffer
702 703 704
      (progn
	(replace-buffer-in-windows rmail-summary-buffer)
	(bury-buffer rmail-summary-buffer)))
Roland McGrath's avatar
Roland McGrath committed
705
  (let ((obuf (current-buffer)))
706
    (replace-buffer-in-windows obuf)
Roland McGrath's avatar
Roland McGrath committed
707 708
    (bury-buffer obuf)))

709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
(defun rmail-bury ()
  "Bury current Rmail buffer and its summary buffer."
  (interactive)
  ;; This let var was called rmail-buffer, but that interfered
  ;; with the buffer-local var used in summary buffers.
  (let ((buffer-to-bury (current-buffer)))
    (if (rmail-summary-exists)
	(let (window)
	  (while (setq window (get-buffer-window rmail-summary-buffer))
	    (set-window-buffer window (other-buffer rmail-summary-buffer)))
	  (bury-buffer rmail-summary-buffer)))
    (switch-to-buffer (other-buffer (current-buffer)))
    (bury-buffer buffer-to-bury)))

(defun rmail-duplicate-message ()
  "Create a duplicated copy of the current message.
The duplicate copy goes into the Rmail file just after the
original copy."
  (interactive)
  (widen)
  (let ((buffer-read-only nil)
	(number rmail-current-message)
	(string (buffer-substring (rmail-msgbeg rmail-current-message)
				  (rmail-msgend rmail-current-message))))
    (goto-char (rmail-msgend rmail-current-message))
    (insert string)
    (rmail-forget-messages)
    (rmail-show-message number)
    (message "Message duplicated")))

Roland McGrath's avatar
Roland McGrath committed
739 740
;;;###autoload
(defun rmail-input (filename)
741
  "Run Rmail on file FILENAME."
Roland McGrath's avatar
Roland McGrath committed
742 743 744
  (interactive "FRun rmail on RMAIL file: ")
  (rmail filename))

745 746 747 748
;; Return a list of file names for all files in or under START
;; whose names match rmail-secondary-file-regexp.
;; This includes START itself, if that name matches.
;; But normally START is a directory.
749 750
(defun rmail-find-all-files (start)
  (if (file-accessible-directory-p start)
751 752 753
      ;; Don't sort here.
      (let ((files (directory-files start t
				    rmail-secondary-file-regexp t))
754 755
	    (ret nil)
	    file)
756 757 758
	(while files
	  (setq file (car files))
	  (setq files (cdr files))
759 760 761 762 763 764 765 766
	  (setq ret (nconc
		     (rmail-find-all-files file)
		     ret)))
	;; Sort here instead of in directory-files
	;; because this list is usually much shorter.
	(sort ret 'string<))
    (if (string-match rmail-secondary-file-regexp start)
	(list (file-name-nondirectory start)))))
767 768 769 770 771

(defun rmail-list-to-menu (menu-name l action &optional full-name)
  (let ((menu (make-sparse-keymap menu-name)))
    (mapcar
     (function (lambda (item)
772 773 774 775 776 777 778 779 780 781 782
		 (let (command)
		   (if (consp item)
		       (progn
			 (setq command
			       (rmail-list-to-menu (car item) (cdr item) 
						   action 
						   (if full-name
						       (concat full-name "/"
							       (car item))
						     (car item))))
			 (setq name (car item)))
783
		     (progn
784 785 786 787 788 789 790 791 792 793 794
		       (setq name item)
		       (setq command 
			     (list 'lambda () '(interactive)
				   (list action
					 (expand-file-name 
					  (if full-name
					      (concat full-name "/" item)
					    item)
					  rmail-secondary-file-directory))))))
		   (define-key menu (vector (intern name))
		     (cons name command)))))
795
     (reverse l))
796 797
    menu))
 
798 799 800
;; This command is always "disabled" when it appears in a menu.
(put 'rmail-disable-menu 'menu-enable ''nil)

801 802
(defun rmail-construct-io-menu ()
  (let ((files (rmail-find-all-files rmail-secondary-file-directory)))
803
    (if files
804 805 806 807
	(progn
	  (define-key rmail-mode-map [menu-bar classify input-menu]
	    (cons "Input Rmail File" 
		  (rmail-list-to-menu "Input Rmail File" 
808
				      files
809 810 811 812
				      'rmail-input)))
	  (define-key rmail-mode-map [menu-bar classify output-menu]
	    (cons "Output Rmail File" 
		  (rmail-list-to-menu "Output Rmail File" 
813 814 815 816 817 818 819
				      files
				      'rmail-output-to-rmail-file))))

      (define-key rmail-mode-map [menu-bar classify input-menu]
	'("Input Rmail File" . rmail-disable-menu))
      (define-key rmail-mode-map [menu-bar classify output-menu]
	'("Output Rmail File" . rmail-disable-menu)))))
820

Roland McGrath's avatar
Roland McGrath committed
821 822 823 824 825 826 827 828 829 830

;;;; *** Rmail input ***

;; RLK feature not added in this version:
;; argument specifies inbox file or files in various ways.

(defun rmail-get-new-mail (&optional file-name)
  "Move any new mail from this RMAIL file's inbox files.
The inbox files can be specified with the file's Mail: option.  The
variable `rmail-primary-inbox-list' specifies the inboxes for your
831 832
primary RMAIL file if it has no Mail: option.  By default, this is
your /usr/spool/mail/$USER.
Roland McGrath's avatar
Roland McGrath committed
833 834 835 836

You can also specify the file to get new mail from.  In this case, the
file of new mail is not changed or deleted.  Noninteractively, you can
pass the inbox file name as an argument.  Interactively, a prefix
837 838
argument causes us to read a file name and use that file as the inbox.

839 840
This function runs `rmail-get-new-mail-hook' before saving the updated file.
It returns t if it got any new messages."
Roland McGrath's avatar
Roland McGrath committed
841 842 843
  (interactive
   (list (if current-prefix-arg
	     (read-file-name "Get new mail from file: "))))
844 845
  ;; If the disk file has been changed from under us,
  ;; revert to it before we get new mail.
Roland McGrath's avatar
Roland McGrath committed
846
  (or (verify-visited-file-modtime (current-buffer))
847
      (find-file (buffer-file-name)))
Roland McGrath's avatar
Roland McGrath committed
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
  (rmail-maybe-set-message-counters)
  (widen)
  ;; Get rid of all undo records for this buffer.
  (or (eq buffer-undo-list t)
      (setq buffer-undo-list nil))
  (unwind-protect
      (let ((opoint (point))
	    (new-messages 0)
	    (delete-files ())
	    ;; If buffer has not changed yet, and has not been saved yet,
	    ;; don't replace the old backup file now.
	    (make-backup-files (and make-backup-files (buffer-modified-p)))
	    (buffer-read-only nil)
	    ;; Don't make undo records for what we do in getting mail.
	    (buffer-undo-list t))
	(goto-char (point-max))
	(skip-chars-backward " \t\n")	    ; just in case of brain damage
	(delete-region (point) (point-max)) ; caused by require-final-newline
	(save-excursion
	  (save-restriction
	    (narrow-to-region (point) (point))
	    ;; Read in the contents of the inbox files,
	    ;; renaming them as necessary,
	    ;; and adding to the list of files to delete eventually.
	    (if file-name
		(rmail-insert-inbox-text (list file-name) nil)
	      (setq delete-files (rmail-insert-inbox-text rmail-inbox-list t)))
	    ;; Scan the new text and convert each message to babyl format.
	    (goto-char (point-min))
	    (save-excursion
	      (setq new-messages (rmail-convert-to-babyl-format)))
	    (or (zerop new-messages)
		(let (success)
		  (widen)
882
		  (search-backward "\n\^_" nil t)
Roland McGrath's avatar
Roland McGrath committed
883 884 885
		  (narrow-to-region (point) (point-max))
		  (goto-char (1+ (point-min)))
		  (rmail-count-new-messages)
886
		  (run-hooks 'rmail-get-new-mail-hook)
Roland McGrath's avatar
Roland McGrath committed
887 888 889 890
		  (save-buffer)))
	    ;; Delete the old files, now that babyl file is saved.
	    (while delete-files
	      (condition-case ()
Richard M. Stallman's avatar
Richard M. Stallman committed
891 892 893 894 895 896
		  ;; First, try deleting.
		  (condition-case ()
		      (delete-file (car delete-files))
		    (file-error
		     ;; If we can't delete it, truncate it.
		     (write-region (point) (point) (car delete-files))))
Roland McGrath's avatar
Roland McGrath committed
897 898 899 900 901
		(file-error nil))
	      (setq delete-files (cdr delete-files)))))
	(if (= new-messages 0)
	    (progn (goto-char opoint)
		   (if (or file-name rmail-inbox-list)
902 903
		       (message "(No new mail has arrived)"))
		   nil)
904 905 906
	  (if (rmail-summary-exists)
	      (rmail-select-summary
		(rmail-update-summary)))
Roland McGrath's avatar
Roland McGrath committed
907 908
	  (message "%d new message%s read"
		   new-messages (if (= 1 new-messages) "" "s"))
909 910 911
	  ;; Move to the first new message
	  ;; unless we have other unseen messages before it.
	  (rmail-show-message (rmail-first-unseen-message))
912 913 914
	  ;; Update the displayed time, since that will clear out
	  ;; the flag that says you have mail.
	  (if (eq (process-status "display-time") 'run)
915 916
	      (display-time-filter display-time-process ""))
	  t))
Roland McGrath's avatar
Roland McGrath committed
917 918 919 920
    ;; Don't leave the buffer screwed up if we get a disk-full error.
    (rmail-show-message)))

(defun rmail-insert-inbox-text (files renamep)
921
  (let (file tofile delete-files movemail popmail)
Roland McGrath's avatar
Roland McGrath committed
922
    (while files
923 924
      (setq file (file-truename
		  (expand-file-name (substitute-in-file-name (car files))))
Roland McGrath's avatar
Roland McGrath committed
925
	    ;;>> un*x specific <<
Jim Blandy's avatar
Jim Blandy committed
926 927 928 929
	    ;; The "+" used to be "~", which is an extremely poor choice;
	    ;; it might accidentally be deleted when space is low
	    ;; (as happened to me!).
	    tofile (concat file "+"))
Roland McGrath's avatar
Roland McGrath committed
930 931 932
      ;; If getting from mail spool directory,
      ;; use movemail to move rather than just renaming,
      ;; so as to interlock with the mailer.
933 934 935 936
      (setq movemail (string= file
			      (file-truename
			       (concat rmail-spool-directory
				       (file-name-nondirectory file))))
937 938 939
	    popmail (string-match "^po:" (file-name-nondirectory file)))
      (if popmail (setq file (file-name-nondirectory file)
			renamep t))
Roland McGrath's avatar
Roland McGrath committed
940 941 942
      (if movemail
	  (progn
	    (setq tofile (expand-file-name
943 944 945 946 947 948 949 950 951
			   ;; Generate name to move to from inbox name,
			   ;; in case of multiple inboxes that need moving.
			   (concat ".newmail-" (file-name-nondirectory file))
			   ;; Use the directory of this rmail file
			   ;; because it's a nuisance to use the homedir
			   ;; if that is on a full disk and this rmail
			   ;; file isn't.
			   (file-name-directory
			     (expand-file-name buffer-file-name))))
Roland McGrath's avatar
Roland McGrath committed
952 953 954
	    ;; On some systems, /usr/spool/mail/foo is a directory
	    ;; and the actual inbox is /usr/spool/mail/foo/foo.
	    (if (file-directory-p file)
955
		(setq file (expand-file-name (user-login-name)
Roland McGrath's avatar
Roland McGrath committed
956
					     file)))))
957 958 959 960 961 962 963 964
      (cond (popmail
	     (message "Getting mail from post office ..."))
	    ((and (file-exists-p tofile)
		  (/= 0 (nth 7 (file-attributes tofile))))
	     (message "Getting mail from %s..." tofile))
	    ((and (file-exists-p file)
		  (/= 0 (nth 7 (file-attributes file))))
	     (message "Getting mail from %s..." file)))
Roland McGrath's avatar
Roland McGrath committed
965 966 967 968
      ;; Set TOFILE if have not already done so, and
      ;; rename or copy the file FILE to TOFILE if and as appropriate.
      (cond ((not renamep)
	     (setq tofile file))
969 970
	    ((or (file-exists-p tofile) (and (not popmail)
					     (not (file-exists-p file))))
Roland McGrath's avatar
Roland McGrath committed
971
	     nil)
972
	    ((and (not movemail) (not popmail))
973 974 975 976 977
	     ;; Try copying.  If that fails (perhaps no space),
	     ;; rename instead.
	     (condition-case nil
		 (copy-file file tofile nil)
	       (error
978 979
		;; Third arg is t so we can replace existing file TOFILE.
		(rename-file file tofile t)))
Richard M. Stallman's avatar
Richard M. Stallman committed
980 981 982 983 984 985
	     ;; Make the real inbox file empty.
	     ;; Leaving it deleted could cause lossage
	     ;; because mailers often won't create the file.
	     (condition-case ()
		 (write-region (point) (point) file)
	       (file-error nil)))
Roland McGrath's avatar
Roland McGrath committed
986 987 988 989 990 991 992
	    (t
	     (let ((errors nil))
	       (unwind-protect
		   (save-excursion
		     (setq errors (generate-new-buffer " *rmail loss*"))
		     (buffer-disable-undo errors)
		     (call-process
993 994 995
		      (or rmail-movemail-program
			  (expand-file-name "movemail" exec-directory))
		      nil errors nil file tofile)
Roland McGrath's avatar
Roland McGrath committed
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
		     (if (not (buffer-modified-p errors))
			 ;; No output => movemail won
			 nil
		       (set-buffer errors)
		       (subst-char-in-region (point-min) (point-max)
					     ?\n ?\  )
		       (goto-char (point-max))
		       (skip-chars-backward " \t")
		       (delete-region (point) (point-max))
		       (goto-char (point-min))
		       (if (looking-at "movemail: ")
			   (delete-region (point-min) (match-end 0)))
		       (beep t)
		       (message (concat "movemail: "
					(buffer-substring (point-min)
							  (point-max))))
		       (sit-for 3)
		       nil))
		 (if errors (kill-buffer errors))))))
      ;; At this point, TOFILE contains the name to read:
      ;; Either the alternate name (if we renamed)
      ;; or the actual inbox (if not renaming).
      (if (file-exists-p tofile)
	  (let (size)
	    (goto-char (point-max))
	    (setq size (nth 1 (insert-file-contents tofile)))
	    (goto-char (point-max))
	    (or (= (preceding-char) ?\n)
		(zerop size)
		(insert ?\n))
	    (setq delete-files (cons tofile delete-files))))
      (message "")
      (setq files (cdr files)))
    delete-files))

;; the  rmail-break-forwarded-messages  feature is not implemented
(defun rmail-convert-to-babyl-format ()
  (let ((count 0) start
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
	(case-fold-search nil)
	(invalid-input-resync
	 (function (lambda ()
		     (message "Invalid Babyl format in inbox!")
		     (sit-for 1)
		     ;; Try to get back in sync with a real message.
		     (if (re-search-forward
			  (concat mmdf-delim1 "\\|^From") nil t)
			 (beginning-of-line)
		       (goto-char (point-max)))))))
Roland McGrath's avatar
Roland McGrath committed
1044 1045 1046 1047
    (goto-char (point-min))
    (save-restriction
      (while (not (eobp))
	(cond ((looking-at "BABYL OPTIONS:");Babyl header
1048 1049 1050 1051
	       (if (search-forward "\n\^_" nil t)
		   ;; If we find the proper terminator, delete through there.
		   (delete-region (point-min) (point))
		 (funcall invalid-input-resync)
1052
		 (delete-region (point-min) (point))))
Roland McGrath's avatar
Roland McGrath committed
1053 1054 1055
	      ;; Babyl format message
	      ((looking-at "\^L")
	       (or (search-forward "\n\^_" nil t)
1056
		   (funcall invalid-input-resync))
Roland McGrath's avatar
Roland McGrath committed
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
	       (setq count (1+ count))
	       ;; Make sure there is no extra white space after the ^_
	       ;; at the end of the message.
	       ;; Narrowing will make sure that whatever follows the junk
	       ;; will be treated properly.
	       (delete-region (point)
			      (save-excursion
				(skip-chars-forward " \t\n")
				(point)))
	       (narrow-to-region (point) (point-max)))
	      ;;*** MMDF format
	      ((let ((case-fold-search t))
		 (looking-at mmdf-delim1))
	       (let ((case-fold-search t))
		 (replace-match "\^L\n0, unseen,,\n*** EOOH ***\n")
		 (setq start (point))
		 (re-search-forward mmdf-delim2 nil t)
		 (replace-match "\^_"))
	       (save-excursion
		 (save-restriction
		   (narrow-to-region start (1- (point)))
		   (goto-char (point-min))
		   (while (search-forward "\n\^_" nil t); single char "\^_"
		     (replace-match "\n^_")))); 2 chars: "^" and "_"
	       (narrow-to-region (point) (point-max))
	       (setq count (1+ count)))
	      ;;*** Mail format
	      ((looking-at "^From ")
	       (setq start (point))
	       (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
	       (rmail-nuke-pinhead-header)
1088 1089 1090 1091
	       ;; If this message has a Content-Length field,
	       ;; skip to the end of the contents.
	       (let* ((header-end (save-excursion
				    (and (re-search-forward "\n\n" nil t)
1092
					 (1- (point)))))
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
		      (case-fold-search t)
		      (size
		       ;; Get the numeric value from the Content-Length field.
		       (save-excursion
			 ;; Back up to end of prev line,
			 ;; in case the Content-Length field comes first.
			 (forward-char -1)
			 (and (search-forward "\ncontent-length: "
					      header-end t)
			      (let ((beg (point))
				    (eol (progn (end-of-line) (point))))
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
				(string-to-int (buffer-substring beg eol)))))))
		 (and size
		      (if (and (natnump size)
			       (<= (+ header-end size) (point-max))
			       ;; Make sure this would put us at a position
			       ;; that we could continue from.
			       (save-excursion
				 (goto-char (+ header-end size))
				 (skip-chars-forward "\n")
				 (or (eobp)
				     (and (looking-at "BABYL OPTIONS:")
					  (search-forward "\n\^_" nil t))
				     (and (looking-at "\^L")
					  (search-forward "\n\^_" nil t))
				     (let ((case-fold-search t))
				       (looking-at mmdf-delim1))
				     (looking-at "From "))))
			  (goto-char (+ header-end size))
			(message "Ignoring invalid Content-Length field")
			(sit-for 1 0 t))))
1124

Roland McGrath's avatar
Roland McGrath committed
1125 1126
	       (if (re-search-forward
		    (concat "^[\^_]?\\("
Jim Blandy's avatar
Jim Blandy committed
1127 1128
			    rmail-unix-mail-delimiter
			    "\\|"
Roland McGrath's avatar
Roland McGrath committed
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
			    mmdf-delim1 "\\|"
			    "^BABYL OPTIONS:\\|"
			    "\^L\n[01],\\)") nil t)
		   (goto-char (match-beginning 1))
		 (goto-char (point-max)))
	       (setq count (1+ count))
	       (save-excursion
		 (save-restriction
		   (narrow-to-region start (point))
		   (goto-char (point-min))
		   (while (search-forward "\n\^_" nil t); single char
		     (replace-match "\n^_")))); 2 chars: "^" and "_"
	       (insert ?\^_)
	       (narrow-to-region (point) (point-max)))
	      ;;
1144 1145 1146 1147 1148
	      ;; This kludge is because some versions of sendmail.el
	      ;; insert an extra newline at the beginning that shouldn't
	      ;; be there.  sendmail.el has been fixed, but old versions
	      ;; may still be in use.  -- rms, 7 May 1993.
	      ((eolp) (delete-char 1))
1149
	      (t (error "Cannot convert to babyl format")))))
Roland McGrath's avatar
Roland McGrath committed
1150 1151 1152 1153
    count))

;; Delete the "From ..." line, creating various other headers with
;; information from it if they don't already exist.  Now puts the
1154 1155
;; original line into a mail-from: header line for debugging and for
;; use by the rmail-output function.
Roland McGrath's avatar
Roland McGrath committed
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
(defun rmail-nuke-pinhead-header ()
  (save-excursion
    (save-restriction
      (let ((start (point))
  	    (end (progn
		   (condition-case ()
		       (search-forward "\n\n")
		     (error
		      (goto-char (point-max))
		      (insert "\n\n")))
		   (point)))
	    has-from has-date)
	(narrow-to-region start end)
	(let ((case-fold-search t))
	  (goto-char start)
	  (setq has-from (search-forward "\nFrom:" nil t))
	  (goto-char start)
	  (setq has-date (and (search-forward "\nDate:" nil t) (point)))
	  (goto-char start))
	(let ((case-fold-search nil))
Jim Blandy's avatar
Jim Blandy committed
1176
	  (if (re-search-forward (concat "^" rmail-unix-mail-delimiter) nil t)
Roland McGrath's avatar
Roland McGrath committed
1177 1178 1179 1180 1181 1182 1183
	      (replace-match
		(concat
		  "Mail-from: \\&"
		  ;; Keep and reformat the date if we don't
		  ;;  have a Date: field.
		  (if has-date
		      ""
Jim Blandy's avatar
Jim Blandy committed
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
		    (concat
		     "Date: \\3, \\5 \\4 \\9 \\6 "
		    
		     ;; The timezone could be matched by group 7 or group 10.
		     ;; If neither of them matched, assume EST, since only
		     ;; Easterners would be so sloppy.
		     ;; It's a shame the substitution can't use "\\10".
		     (cond
		      ((/= (match-beginning 7) (match-end 7)) "\\7")
		      ((/= (match-beginning 10) (match-end 10))
		       (buffer-substring (match-beginning 10)
					 (match-end 10)))
		      (t "EST"))
		     "\n"))
Roland McGrath's avatar
Roland McGrath committed
1198 1199 1200 1201
		  ;; Keep and reformat the sender if we don't
		  ;; have a From: field.
		  (if has-from
		      ""
1202 1203
		    "From: \\1\n"))
		t)))))))
Roland McGrath's avatar
Roland McGrath committed
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216

;;;; *** Rmail Message Formatting and Header Manipulation ***

(defun rmail-reformat-message (beg end)
  (goto-char beg)
  (forward-line 1)
  (if (/= (following-char) ?0)
      (error "Bad format in RMAIL file."))
  (let ((buffer-read-only nil)
	(delta (- (buffer-size) end)))
    (delete-char 1)
    (insert ?1)
    (forward-line 1)
1217
    (let ((case-fold-search t))
1218 1219
      (while (looking-at "Summary-line:\\|Mail-From:")
 	(forward-line 1)))
Roland McGrath's avatar
Roland McGrath committed
1220 1221 1222 1223 1224 1225 1226 1227 1228
    (if (looking-at "\\*\\*\\* EOOH \\*\\*\\*\n")
	(delete-region (point)
		       (progn (forward-line 1) (point))))
    (let ((str (buffer-substring (point)
				 (save-excursion (search-forward "\n\n" end 'move)
						 (point)))))
      (insert str "*** EOOH ***\n")
      (narrow-to-region (point) (- (buffer-size) delta)))
    (goto-char (point-min))
1229
    (if rmail-message-filter (funcall rmail-message-filter))
1230 1231
    (if (or rmail-displayed-headers rmail-ignored-headers)
	(rmail-clear-headers))))
Roland McGrath's avatar
Roland McGrath committed
1232

1233
(defun rmail-clear-headers (&optional ignored-headers)
1234 1235 1236 1237 1238 1239
  "Delete all header fields that Rmail should not show.
If the optional argument IGNORED-HEADERS is non-nil,
delete all header fields whose names match that regexp.
Otherwise, if `rmail-displayed-headers' is non-nil,
delete all header fields *except* those whose names match that regexp.
Otherwise, delete all header fields whose names match `rmail-ignored-headers'."
Roland McGrath's avatar
Roland McGrath committed
1240
  (if (search-forward "\n\n" nil t)
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
      (if (and rmail-displayed-headers (null ignored-headers))
	  (save-restriction
	    (narrow-to-region (point-min) (point))
	    (let ((buffer-read-only nil) lim)
	      (goto-char (point-min))
	      (while (save-excursion
		       (re-search-forward "\n[^ \t]")
		       (and (not (eobp))
			    (setq lim (1- (point)))))
		(if (save-excursion
		      (re-search-forward rmail-displayed-headers lim t))
		    (goto-char lim)
		  (delete-region (point) lim))))
	    (goto-char (point-min)))
	(or ignored-headers (setq ignored-headers rmail-ignored-headers))
	(save-restriction
	  (narrow-to-region (point-min) (point))
	  (let ((buffer-read-only nil))
	    (while (let ((case-fold-search t))
		     (goto-char (point-min))
		     (re-search-forward ignored-headers nil t))
	      (beginning-of-line)
	      (delete-region (point)
			     (progn (re-search-forward "\n[^ \t]")
				    (1- (point))))))))))
Roland McGrath's avatar
Roland McGrath committed
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278

(defun rmail-toggle-header ()
  "Show original message header if pruned header currently shown, or vice versa."
  (interactive)
  (rmail-maybe-set-message-counters)
  (narrow-to-region (rmail-msgbeg rmail-current-message) (point-max))
  (let ((buffer-read-only nil))
    (goto-char (point-min))
    (forward-line 1)
    (if (= (following-char) ?1)
	(progn (delete-char 1)
	       (insert ?0)
	       (forward-line 1)