*** empty log message ***
[gnus] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2 ;; Copyright (C) 1996 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
5 ;; Keywords: mail, news
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 ;; This mode provides mail-sending facilities from within Emacs.  It
27 ;; consists mainly of large chunks of code from the sendmail.el,
28 ;; gnus-msg.el and rnewspost.el files.
29
30 ;;; Code:
31
32 (eval-when-compile 
33   (require 'cl))
34 (require 'mailheader)
35 (require 'rmail)
36 (require 'nnheader)
37 (require 'timezone)
38 (require 'easymenu)
39 (if (string-match "XEmacs\\|Lucid" emacs-version)
40     (require 'mail-abbrevs)
41   (require 'mailabbrev))
42
43 (defvar message-directory "~/Mail/"
44   "*Directory from which all other mail file variables are derived.")
45
46 (defvar message-max-buffers 10
47   "*How many buffers to keep before starting to kill them off.")
48
49 (defvar message-send-rename-function nil
50   "Function called to rename the buffer after sending it.")
51
52 ;;;###autoload
53 (defvar message-fcc-handler-function 'rmail-output
54   "*A function called to save outgoing articles.
55 This function will be called with the name of the file to store the
56 article in. The default function is `rmail-output' which saves in Unix
57 mailbox format.")
58
59 ;;;###autoload
60 (defvar message-courtesy-message
61   "The following message is a courtesy copy of an article\nthat has been posted as well.\n\n"
62   "*This is inserted at the start of a mailed copy of a posted message.
63 If this variable is nil, no such courtesy message will be added.")
64
65 ;;;###autoload
66 (defvar message-ignored-bounced-headers "^\\(Received\\|Return-Path\\):"
67   "*Regexp that matches headers to be removed in resent bounced mail.")
68
69 ;;;###autoload
70 (defvar message-from-style 'default
71   "*Specifies how \"From\" headers look.
72
73 If `nil', they contain just the return address like:
74         king@grassland.com
75 If `parens', they look like:
76         king@grassland.com (Elvis Parsley)
77 If `angles', they look like:
78         Elvis Parsley <king@grassland.com>
79
80 Otherwise, most addresses look like `angles', but they look like
81 `parens' if `angles' would need quoting and `parens' would not.")
82
83 ;;;###autoload
84 (defvar message-syntax-checks nil
85   "Controls what syntax checks should not be performed on outgoing posts.
86 To disable checking of long signatures, for instance, add
87  `(signature . disabled)' to this list.
88
89 Don't touch this variable unless you really know what you're doing.
90
91 Checks include subject-cmsg multiple-headers sendsys message-id from
92 long-lines control-chars size new-text redirected-followup signature
93 approved sender empty empty-headers message-id from subject.")
94
95 ;;;###autoload
96 (defvar message-required-news-headers
97   '(From Newsgroups Subject Date Message-ID 
98          (optional . Organization) Lines 
99          (optional . X-Newsreader))
100   "*Headers to be generated or prompted for when posting an article.
101 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
102 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
103 X-Newsreader are optional.  If don't you want message to insert some
104 header, remove it from this list.")
105
106 ;;;###autoload
107 (defvar message-required-mail-headers 
108   '(From Subject Date (optional . In-Reply-To) Message-ID Lines
109          (optional . X-Mailer))
110   "*Headers to be generated or prompted for when mailing a message.
111 RFC822 required that From, Date, To, Subject and Message-ID be
112 included.  Organization, Lines and X-Mailer are optional.")
113
114 ;;;###autoload
115 (defvar message-deletable-headers '(Message-ID Date)
116   "*Headers to be deleted if they already exist and were generated by message previously.")
117
118 ;;;###autoload
119 (defvar message-ignored-news-headers 
120   "^NNTP-Posting-Host:\\|^Xref:\\|^Bcc:\\|^Gcc:\\|^Fcc:"
121   "*Regexp of headers to be removed unconditionally before posting.")
122
123 ;;;###autoload
124 (defvar message-ignored-mail-headers "^Gcc:\\|^Fcc:"
125   "*Regexp of headers to be removed unconditionally before mailing.")
126
127 ;;;###autoload
128 (defvar message-ignored-supersedes-headers "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|Return-Path:\\|^Supersedes:"
129   "*Header lines matching this regexp will be deleted before posting.
130 It's best to delete old Path and Date headers before posting to avoid
131 any confusion.")
132
133 ;;;###autoload
134 (defvar message-signature-separator "^-- *$"
135   "Regexp matching the signature separator.")
136
137 ;;;###autoload
138 (defvar message-interactive nil 
139   "Non-nil means when sending a message wait for and display errors.
140 nil means let mailer mail back a message to report errors.")
141
142 ;;;###autoload
143 (defvar message-generate-new-buffers t
144   "*Non-nil means that a new message buffer will be created whenever `mail-setup' is called.
145 If this is a function, call that function with three parameters:  The type,
146 the to address and the group name.  (Any of these may be nil.)  The function
147 should return the new buffer name.")
148
149 ;;;###autoload
150 (defvar message-kill-buffer-on-exit nil
151   "*Non-nil means that the message buffer will be killed after sending a message.")
152
153 (defvar gnus-local-organization)
154 (defvar message-user-organization 
155   (or (and (boundp 'gnus-local-organization)
156            gnus-local-organization)
157       (getenv "ORGANIZATION")
158       t)
159   "*String to be used as an Organization header.
160 If t, use `message-user-organization-file'.")
161
162 ;;;###autoload
163 (defvar message-user-organization-file "/usr/lib/news/organization"
164   "*Local news organization file.")
165
166 (defvar message-autosave-directory "~/"
167   ; (concat (file-name-as-directory message-directory) "drafts/")
168   "*Directory where message autosaves buffers.
169 If nil, message won't autosave.")
170
171 (defvar message-forward-start-separator 
172   "------- Start of forwarded message -------\n"
173   "*Delimiter inserted before forwarded messages.")
174
175 (defvar message-forward-end-separator
176   "------- End of forwarded message -------\n"
177   "*Delimiter inserted after forwarded messages.")
178
179 ;;;###autoload
180 (defvar message-signature-before-forwarded-message t
181   "*If non-nil, put the signature before any included forwarded message.")
182
183 ;;;###autoload
184 (defvar message-included-forward-headers 
185   "^From:\\|^Newsgroups:\\|^Subject:\\|^Date:\\|^Followup-To:\\|^Reply-To:\\|^Organization:\\|^Summary:\\|^Keywords:\\|^To:\\|^Cc:\\|^Posted-To:\\|^Mail-Copies-To:\\|^Apparently-To:\\|^Gnus-Warning:\\|^Resent-\\|^Message-ID:\\|^References:"
186   "*Regexp matching headers to be included in forwarded messages.")
187
188 ;;;###autoload
189 (defvar message-ignored-resent-headers "^Return-receipt"
190   "*All headers that match this regexp will be deleted when resending a message.")
191
192 ;;;###autoload
193 (defvar message-ignored-cited-headers "."
194   "Delete these headers from the messages you yank.")
195
196 ;; Useful to set in site-init.el
197 ;;;###autoload
198 (defvar message-send-mail-function 'message-send-mail-with-sendmail
199   "Function to call to send the current buffer as mail.
200 The headers should be delimited by a line whose contents match the
201 variable `mail-header-separator'.
202
203 Legal values include `message-send-mail-with-mh' and
204 `message-send-mail-with-sendmail', which is the default.")
205
206 ;;;###autoload
207 (defvar message-send-news-function 'message-send-news
208   "Function to call to send the current buffer as news.
209 The headers should be delimited by a line whose contents match the
210 variable `mail-header-separator'.")
211
212 ;;;###autoload
213 (defvar message-reply-to-function nil
214   "Function that should return a list of headers.
215 This function should pick out addresses from the To, Cc, and From headers
216 and respond with new To and Cc headers.")
217
218 ;;;###autoload
219 (defvar message-wide-reply-to-function nil
220   "Function that should return a list of headers.
221 This function should pick out addresses from the To, Cc, and From headers
222 and respond with new To and Cc headers.")
223
224 ;;;###autoload
225 (defvar message-followup-to-function nil
226   "Function that should return a list of headers.
227 This function should pick out addresses from the To, Cc, and From headers
228 and respond with new To and Cc headers.")
229
230 ;;;###autoload
231 (defvar message-use-followup-to 'ask
232   "*Specifies what to do with Followup-To header.
233 If nil, ignore the header. If it is t, use its value, but query before
234 using the \"poster\" value.  If it is the symbol `ask', query the user
235 whether to ignore the \"poster\" value.  If it is the symbol `use',
236 always use the value.")
237
238 (defvar gnus-post-method)
239 (defvar gnus-select-method)
240 ;;;###autoload
241 (defvar message-post-method 
242   (cond ((and (boundp 'gnus-post-method)
243               gnus-post-method)
244          gnus-post-method)
245         ((boundp 'gnus-select-method)
246          gnus-select-method)
247         (t '(nnspool "")))
248   "Method used to post news.")
249
250 ;;;###autoload
251 (defvar message-generate-headers-first nil
252   "*If non-nil, generate all possible headers before composing.")
253
254 (defvar message-setup-hook nil
255   "Normal hook, run each time a new outgoing message is initialized.
256 The function `message-setup' runs this hook.")
257
258 (defvar message-signature-setup-hook nil
259   "Normal hook, run each time a new outgoing message is initialized.
260 It is run after the headers have been inserted and before 
261 the signature is inserted.")
262
263 (defvar message-mode-hook nil
264   "Hook run in message mode buffers.")
265
266 (defvar message-header-hook nil
267   "Hook run in a message mode buffer narrowed to the headers.")
268
269 (defvar message-header-setup-hook nil
270   "Hook called narrowed to the headers when setting up a message buffer.")
271
272 ;;;###autoload
273 (defvar message-citation-line-function 'message-insert-citation-line
274   "*Function called to insert the \"Whomever writes:\" line.")
275
276 ;;;###autoload
277 (defvar message-yank-prefix "> "
278   "*Prefix inserted on the lines of yanked messages.
279 nil means use indentation.")
280
281 (defvar message-indentation-spaces 3
282   "*Number of spaces to insert at the beginning of each cited line.
283 Used by `message-yank-original' via `message-yank-cite'.")
284
285 ;;;###autoload
286 (defvar message-cite-function 'message-cite-original
287   "*Function for citing an original message.")
288
289 ;;;###autoload
290 (defvar message-indent-citation-function 'message-indent-citation
291   "*Function for modifying a citation just inserted in the mail buffer.
292 This can also be a list of functions.  Each function can find the
293 citation between (point) and (mark t).  And each function should leave
294 point and mark around the citation text as modified.")
295
296 (defvar message-abbrevs-loaded nil)
297
298 ;;;###autoload
299 (defvar message-signature t
300   "*String to be inserted at the end of the message buffer.
301 If t, the `message-signature-file' file will be inserted instead.
302 If a function, the result from the function will be used instead.
303 If a form, the result from the form will be used instead.")
304
305 ;;;###autoload
306 (defvar message-signature-file "~/.signature"
307   "*File containing the text inserted at end of message. buffer.")
308
309 (defvar message-distribution-function nil
310   "*Function called to return a Distribution header.")
311
312 (defvar message-expires 14
313   "*Number of days before your article expires.")
314
315 (defvar message-user-path nil
316   "If nil, use the NNTP server name in the Path header.
317 If stringp, use this; if non-nil, use no host name (user name only).")
318
319 (defvar message-reply-buffer nil)
320 (defvar message-reply-headers nil)
321 (defvar message-newsreader nil)
322 (defvar message-mailer nil)
323 (defvar message-sent-message-via nil)
324 (defvar message-checksum nil)
325 (defvar message-send-actions nil
326   "A list of actions to be performed upon successful sending of a message.")
327 (defvar message-exit-actions nil
328   "A list of actions to be performed upon exiting after sending a message.")
329 (defvar message-kill-actions nil
330   "A list of actions to be performed before killing a message buffer.")
331 (defvar message-postpone-actions nil
332   "A list of actions to be performed after postponing a message.")
333
334 ;;;###autoload
335 (defvar message-default-headers nil
336   "*A string containing header lines to be inserted in outgoing messages.
337 It is inserted before you edit the message, so you can edit or delete
338 these lines.")
339
340 ;;;###autoload
341 (defvar message-default-mail-headers nil
342   "*A string of header lines to be inserted in outgoing mails.")
343
344 ;;;###autoload
345 (defvar message-default-news-headers nil
346   "*A string of header lines to be inserted in outgoing news articles.")
347
348 ;; Note: could use /usr/ucb/mail instead of sendmail;
349 ;; options -t, and -v if not interactive.
350 (defvar message-mailer-swallows-blank-line
351   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)" 
352                          system-configuration)
353            (file-readable-p "/etc/sendmail.cf")
354            (let ((buffer (get-buffer-create " *temp*")))
355              (unwind-protect
356                  (save-excursion
357                    (set-buffer buffer)
358                    (insert-file-contents "/etc/sendmail.cf")
359                    (goto-char (point-min))
360                    (let ((case-fold-search nil))
361                      (re-search-forward "^OR\\>" nil t)))
362                (kill-buffer buffer))))
363       ;; According to RFC822, "The field-name must be composed of printable
364       ;; ASCII characters (i.e. characters that have decimal values between
365       ;; 33 and 126, except colon)", i.e. any chars except ctl chars,
366       ;; space, or colon.
367       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
368   "Set this non-nil if the system's mailer runs the header and body together.
369 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
370 The value should be an expression to test whether the problem will
371 actually occur.")
372
373 (defvar message-mode-syntax-table 
374   (let ((table (copy-syntax-table text-mode-syntax-table)))
375     (modify-syntax-entry ?% ". " table)
376     table)
377   "Syntax table used while in Message mode.")
378
379 (defvar message-mode-abbrev-table text-mode-abbrev-table
380   "Abbrev table used in Message mode buffers.
381 Defaults to `text-mode-abbrev-table'.")
382
383 (defvar message-font-lock-keywords
384   (let* ((cite-prefix "A-Za-z") (cite-suffix (concat cite-prefix "0-9_.@-")))
385     (list '("^To:" . font-lock-function-name-face)
386           '("^[GBF]?[Cc][Cc]:\\|^Reply-To:" . font-lock-keyword-face)
387           '("^\\(Subject:\\)[ \t]*\\(.+\\)?"
388             (1 font-lock-comment-face) (2 font-lock-type-face nil t))
389           (list (concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
390                 1 'font-lock-comment-face)
391           (cons (concat "^[ \t]*"
392                         "\\([" cite-prefix "]+[" cite-suffix "]*\\)?"
393                         "[>|}].*")
394                 'font-lock-reference-face)
395           '("^\\(X-[A-Za-z0-9-]+\\|In-reply-to\\):.*"
396             . font-lock-string-face)))
397   "Additional expressions to highlight in Message mode.")
398
399 (defvar message-face-alist
400   '((bold . bold-region)
401     (underline . underline-region)
402     (default . (lambda (b e) 
403                  (unbold-region b e)
404                  (ununderline-region b e))))
405   "Alist of mail and news faces for facemenu.
406 The cdr of ech entry is a function for applying the face to a region.")
407
408 (defvar message-send-hook nil
409   "Hook run before sending messages.")
410
411 (defvar message-sent-hook nil
412   "Hook run after sending messages.")
413
414 ;;; Internal variables.
415
416 (defvar message-buffer-list nil)
417
418 ;;; Regexp matching the delimiter of messages in UNIX mail format
419 ;;; (UNIX From lines), minus the initial ^.  
420 (defvar message-unix-mail-delimiter
421   (let ((time-zone-regexp
422          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
423                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
424                  "\\|"
425                  "\\) *")))
426     (concat
427      "From "
428
429      ;; Username, perhaps with a quoted section that can contain spaces.
430      "\\("
431      "[^ \n]*"
432      "\\(\\|\".*\"[^ \n]*\\)"
433      "\\|<[^<>\n]+>"
434      "\\)  ?"
435
436      ;; The time the message was sent.
437      "\\([^ \n]*\\) *"                  ; day of the week
438      "\\([^ ]*\\) *"                    ; month
439      "\\([0-9]*\\) *"                   ; day of month
440      "\\([0-9:]*\\) *"                  ; time of day
441
442      ;; Perhaps a time zone, specified by an abbreviation, or by a
443      ;; numeric offset.
444      time-zone-regexp
445
446      ;; The year.
447      " [0-9][0-9]\\([0-9]*\\) *"
448
449      ;; On some systems the time zone can appear after the year, too.
450      time-zone-regexp
451
452      ;; Old uucp cruft.
453      "\\(remote from .*\\)?"
454
455      "\n")))
456
457 (defvar message-unsent-separator
458   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
459           "^ *---+ +Returned message +---+ *$\\|"
460           "^Start of returned message$\\|"
461           "^ *---+ +Original message +---+ *$\\|"
462           "^ *--+ +begin message +--+ *$\\|"
463           "^ *---+ +Original message follows +---+ *$\\|"
464           "^|? *---+ +Message text follows: +---+ *|?$")
465   "A regexp that matches the separator before the text of a failed message.")
466
467 (defvar message-header-format-alist 
468   `((Newsgroups)
469     (To . message-fill-address) 
470     (Cc . message-fill-address)
471     (Subject)
472     (In-Reply-To)
473     (Fcc)
474     (Bcc)
475     (Date)
476     (Organization)
477     (Distribution)
478     (Lines)
479     (Expires)
480     (Message-ID)
481     (References . message-fill-header)
482     (X-Mailer)
483     (X-Newsreader))
484   "Alist used for formatting headers.")
485
486 (eval-and-compile
487   (autoload 'message-setup-toolbar "messagexmas")
488   (autoload 'mh-send-letter "mh-comp"))
489
490 \f
491
492 ;;; 
493 ;;; Utility functions.
494 ;;;
495
496 (defun message-point-at-bol ()
497   "Return point at the beginning of the line."
498   (let ((p (point)))
499     (beginning-of-line)
500     (prog1
501         (point)
502       (goto-char p))))
503
504 (defun message-point-at-eol ()
505   "Return point at the end of the line."
506   (let ((p (point)))
507     (end-of-line)
508     (prog1
509         (point)
510       (goto-char p))))
511
512 ;; Delete the current line (and the next N lines.);
513 (defmacro message-delete-line (&optional n)
514   `(delete-region (progn (beginning-of-line) (point))
515                   (progn (forward-line ,(or n 1)) (point))))
516
517 (defun message-tokenize-header (header &optional separator)
518   "Split HEADER into a list of header elements.
519 \",\" is used as the separator."
520   (let ((regexp (format "[%s]+" (or separator ",")))
521         (beg 1)
522         (first t)
523         quoted elems)
524     (save-excursion
525       (message-set-work-buffer)
526       (insert header)
527       (goto-char (point-min))
528       (while (not (eobp))
529         (if first
530             (setq first nil)
531           (forward-char 1))
532         (cond ((and (> (point) beg)
533                     (or (eobp)
534                         (and (looking-at regexp)
535                              (not quoted))))
536                (push (buffer-substring beg (point)) elems)
537                (setq beg (match-end 0)))
538               ((= (following-char) ?\")
539                (setq quoted (not quoted)))))
540       (nreverse elems))))
541
542 (defun message-fetch-field (header)
543   "The same as `mail-fetch-field', only remove all newlines."
544   (let ((value (mail-fetch-field header)))
545     (when value
546       (nnheader-replace-chars-in-string value ?\n ? ))))
547
548 (defun message-fetch-reply-field (header)
549   "Fetch FIELD from the message we're replying to."
550   (when (and message-reply-buffer
551              (buffer-name message-reply-buffer))
552     (save-excursion
553       (set-buffer message-reply-buffer)
554       (message-fetch-field header))))
555
556 (defun message-set-work-buffer ()
557   (if (get-buffer " *message work*")
558       (progn
559         (set-buffer " *message work*")
560         (erase-buffer))
561     (set-buffer (get-buffer-create " *message work*"))
562     (kill-all-local-variables)
563     (buffer-disable-undo (current-buffer))))
564
565 (defun message-functionp (form)
566   "Return non-nil if FORM is funcallable."
567   (or (and (symbolp form) (fboundp form))
568       (and (listp form) (eq (car form) 'lambda))))
569
570 (defun message-strip-subject-re (subject)
571   "Remove \"Re:\" from subject lines."
572   (if (string-match "^[Rr][Ee]: *" subject)
573       (substring subject (match-end 0))
574     subject))
575
576 (defun message-remove-header (header &optional is-regexp first reverse)
577   "Remove HEADER in the narrowed buffer.
578 If REGEXP, HEADER is a regular expression.
579 If FIRST, only remove the first instance of the header.
580 Return the number of headers removed."
581   (goto-char (point-min))
582   (let ((regexp (if is-regexp header (concat "^" header ":")))
583         (number 0)
584         (case-fold-search t)
585         last)
586     (while (and (not (eobp))
587                 (not last))
588       (if (if reverse
589               (not (looking-at regexp))
590             (looking-at regexp))
591           (progn
592             (incf number)
593             (when first
594               (setq last t))
595             (delete-region
596              (point)
597              ;; There might be a continuation header, so we have to search
598              ;; until we find a new non-continuation line.
599              (progn
600                (forward-line 1)
601                (if (re-search-forward "^[^ \t]" nil t)
602                    (goto-char (match-beginning 0))
603                  (point-max)))))
604         (forward-line 1)
605         (if (re-search-forward "^[^ \t]" nil t)
606             (goto-char (match-beginning 0))
607           (point-max))))
608     number))
609
610 (defun message-narrow-to-headers ()
611   "Narrow the buffer to the head of the message."
612   (widen)
613   (narrow-to-region
614    (goto-char (point-min))
615    (if (re-search-forward
616         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
617        (match-beginning 0)
618      (point-max)))
619   (goto-char (point-min)))
620
621 (defun message-narrow-to-head ()
622   "Narrow the buffer to the head of the message."
623   (widen)
624   (narrow-to-region
625    (goto-char (point-min))
626    (if (search-forward "\n\n" nil 1)
627        (1- (point))
628      (point-max)))
629   (goto-char (point-min)))
630
631 (defun message-news-p ()
632   "Say whether the current buffer contains a news message."
633   (save-excursion
634     (save-restriction
635       (message-narrow-to-headers)
636       (message-fetch-field "newsgroups"))))
637
638 (defun message-mail-p ()
639   "Say whether the current buffer contains a mail message."
640   (save-excursion
641     (save-restriction
642       (message-narrow-to-headers)
643       (or (message-fetch-field "to")
644           (message-fetch-field "cc")
645           (message-fetch-field "bcc")))))
646
647 (defun message-next-header ()
648   "Go to the beginning of the next header."
649   (beginning-of-line)
650   (or (eobp) (forward-char 1))
651   (not (if (re-search-forward "^[^ \t]" nil t)
652            (beginning-of-line)
653          (goto-char (point-max)))))
654     
655 (defun message-sort-headers-1 ()
656   "Sort the buffer as headers using `message-rank' text props."
657   (goto-char (point-min))
658   (sort-subr 
659    nil 'message-next-header 
660    (lambda ()
661      (message-next-header)
662      (unless (bobp)
663        (forward-char -1)))
664    (lambda ()
665      (or (get-text-property (point) 'message-rank)
666          0))))
667
668 (defun message-sort-headers ()
669   "Sort the headers of the current message according to `message-header-format-alist'."
670   (interactive)
671   (save-excursion
672     (save-restriction
673       (let ((max (1+ (length message-header-format-alist)))
674             rank)
675         (message-narrow-to-headers)
676         (while (re-search-forward "^[^ \n]+:" nil t)
677           (put-text-property
678            (match-beginning 0) (1+ (match-beginning 0))
679            'message-rank
680            (if (setq rank (length (memq (assq (intern (buffer-substring
681                                                        (match-beginning 0)
682                                                        (1- (match-end 0))))
683                                               message-header-format-alist)
684                                         message-header-format-alist)))
685                (- max rank)
686              (1+ max)))))
687       (message-sort-headers-1))))
688
689 \f
690
691 ;;;
692 ;;; Message mode
693 ;;;
694
695 ;;; Set up keymap.
696
697 (defvar message-mode-map nil)
698
699 (unless message-mode-map
700   (setq message-mode-map (copy-keymap text-mode-map))
701   (define-key message-mode-map "\C-c?" 'describe-mode)
702
703   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
704   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
705   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
706   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
707   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
708   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
709   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
710   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
711   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
712   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
713   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
714   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
715   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
716
717   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
718   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
719   
720   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
721   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
722   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
723   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
724   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
725   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
726
727   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
728   (define-key message-mode-map "\C-c\C-s" 'message-send)
729   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
730   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
731
732   (define-key message-mode-map "\t" 'message-tab))
733
734 (easy-menu-define message-mode-menu message-mode-map
735   "Message Menu."
736   '("Message"
737     "Go to Field:"
738     "----"
739     ["To" message-goto-to t]
740     ["Subject" message-goto-subject t]
741     ["Cc" message-goto-cc t]
742     ["Reply-to" message-goto-reply-to t]
743     ["Summary" message-goto-summary t]
744     ["Keywords" message-goto-keywords t]
745     ["Newsgroups" message-goto-newsgroups t]
746     ["Followup-To" message-goto-followup-to t]
747     ["Distribution" message-goto-distribution t]
748     ["Body" message-goto-body t]
749     ["Signature" message-goto-signature t]
750     "----"
751     "Miscellaneous Commands:"
752     "----"
753     ["Sort Headers" message-sort-headers t]
754     ["Yank Original" message-yank-original t]
755     ["Fill Yanked Message" message-fill-yanked-message t]
756     ["Insert Signature" message-insert-signature t]
757     ["Caesar (rot13) Message" message-caesar-buffer-body t]
758     ["Rename buffer" message-rename-buffer t]
759     ["Spellcheck" ispell-message t]
760     "----"
761     ["Send Message" message-send-and-exit t]
762     ["Abort Message" message-dont-send t]))
763
764 (defvar facemenu-add-face-function)
765 (defvar facemenu-remove-face-function)
766
767 ;;;###autoload
768 (defun message-mode ()
769   "Major mode for editing mail and news to be sent.
770 Like Text Mode but with these additional commands:
771 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
772 C-c C-f  move to a header field (and create it if there isn't):
773          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
774          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
775          C-c C-f C-f  move to Fcc       C-c C-f C-r  move to Reply-To
776          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
777          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
778          C-c C-f C-o  move to Followup-To
779 C-c C-t  message-insert-to (add a To header to a news followup)
780 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
781 C-c C-b  message-goto-body (move to beginning of message text).
782 C-c C-i  message-goto-signature (move to the beginning of the signature).
783 C-c C-w  message-insert-signature (insert `message-signature-file' file).
784 C-c C-y  message-yank-original (insert current message, if any).
785 C-c C-q  message-fill-yanked-message (fill what was yanked).
786 C-c C-r  message-ceasar-buffer-body (rot13 the message body)."
787   (interactive)
788   (kill-all-local-variables)
789   (make-local-variable 'message-reply-buffer)
790   (setq message-reply-buffer nil)
791   (make-local-variable 'message-send-actions)
792   (make-local-variable 'message-exit-actions)
793   (make-local-variable 'message-kill-actions)
794   (make-local-variable 'message-postpone-actions)
795   (set-syntax-table message-mode-syntax-table)
796   (use-local-map message-mode-map)
797   (setq local-abbrev-table message-mode-abbrev-table)
798   (setq major-mode 'message-mode)
799   (setq mode-name "Message")
800   (setq buffer-offer-save t)
801   (make-local-variable 'font-lock-defaults)
802   (setq font-lock-defaults '(message-font-lock-keywords t))
803   (make-local-variable 'facemenu-add-face-function)
804   (make-local-variable 'facemenu-remove-face-function)
805   (setq facemenu-add-face-function
806         (lambda (face end)
807           (let ((face-fun (cdr (assq face message-face-alist))))
808             (if face-fun
809                 (funcall face-fun (point) end)
810               (error "Face %s not configured for %s mode" face mode-name)))
811           "")
812         facemenu-remove-face-function t)
813   (make-local-variable 'paragraph-separate)
814   (make-local-variable 'paragraph-start)
815   (setq paragraph-start (concat (regexp-quote mail-header-separator)
816                                 "$\\|[ \t]*[-_][-_][-_]+$\\|"
817                                 "-- $\\|"
818                                 paragraph-start))
819   (setq paragraph-separate (concat (regexp-quote mail-header-separator)
820                                    "$\\|[ \t]*[-_][-_][-_]+$\\|"
821                                    "-- $\\|"
822                                    paragraph-separate))
823   (make-local-variable 'message-reply-headers)
824   (setq message-reply-headers nil)
825   (make-local-variable 'message-newsreader)
826   (make-local-variable 'message-mailer)
827   (make-local-variable 'message-post-method)
828   (make-local-variable 'message-sent-message-via)
829   (setq message-sent-message-via nil)
830   (make-local-variable 'message-checksum)
831   (setq message-checksum nil)
832   ;;(when (fboundp 'mail-hist-define-keys)
833   ;;  (mail-hist-define-keys))
834   (when (string-match "XEmacs\\|Lucid" emacs-version)
835     (message-setup-toolbar))
836   (easy-menu-add message-mode-menu message-mode-map)
837   ;; Allow mail alias things.
838   (if (fboundp 'mail-abbrevs-setup)
839       (mail-abbrevs-setup)
840     (funcall (intern "mail-aliases-setup")))
841   (run-hooks 'text-mode-hook 'message-mode-hook))
842
843 \f
844
845 ;;;
846 ;;; Message mode commands
847 ;;;
848
849 ;;; Movement commands
850
851 (defun message-goto-to ()
852   "Move point to the To header."
853   (interactive)
854   (message-position-on-field "To"))
855
856 (defun message-goto-subject ()
857   "Move point to the Subject header."
858   (interactive)
859   (message-position-on-field "Subject"))
860
861 (defun message-goto-cc ()
862   "Move point to the Cc header."
863   (interactive)
864   (message-position-on-field "Cc" "To"))
865
866 (defun message-goto-bcc ()
867   "Move point to the Bcc  header."
868   (interactive)
869   (message-position-on-field "Bcc" "Cc" "To"))
870
871 (defun message-goto-fcc ()
872   "Move point to the Fcc header."
873   (interactive)
874   (message-position-on-field "Fcc" "To" "Newsgroups"))
875
876 (defun message-goto-reply-to ()
877   "Move point to the Reply-To header."
878   (interactive)
879   (message-position-on-field "Reply-To" "Subject"))
880
881 (defun message-goto-newsgroups ()
882   "Move point to the Newsgroups header."
883   (interactive)
884   (message-position-on-field "Newsgroups"))
885
886 (defun message-goto-distribution ()
887   "Move point to the Distribution header."
888   (interactive)
889   (message-position-on-field "Distribution"))
890
891 (defun message-goto-followup-to ()
892   "Move point to the Followup-To header."
893   (interactive)
894   (message-position-on-field "Followup-To" "Newsgroups"))
895
896 (defun message-goto-keywords ()
897   "Move point to the Keywords header."
898   (interactive)
899   (message-position-on-field "Keywords" "Subject"))
900
901 (defun message-goto-summary ()
902   "Move point to the Summary header."
903   (interactive)
904   (message-position-on-field "Summary" "Subject"))
905
906 (defun message-goto-body ()
907   "Move point to the beginning of the message body."
908   (interactive)
909   (if (looking-at "[ \t]*\n") (expand-abbrev))
910   (goto-char (point-min))
911   (search-forward (concat "\n" mail-header-separator "\n") nil t))
912
913 (defun message-goto-signature ()
914   "Move point to the beginning of the message signature."
915   (interactive)
916   (goto-char (point-min))
917   (or (re-search-forward message-signature-separator nil t)
918       (goto-char (point-max))))
919
920 \f
921
922 (defun message-insert-to ()
923   "Insert a To header that points to the author of the article being replied to."
924   (interactive)
925   (when (and (message-position-on-field "To")
926              (mail-fetch-field "to")
927              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
928     (insert ", "))
929   (insert (or (message-fetch-reply-field "reply-to")
930               (message-fetch-reply-field "from") "")))
931
932 (defun message-insert-newsgroups ()
933   "Insert the Newsgroups header from the article being replied to."
934   (interactive)
935   (when (and (message-position-on-field "Newsgroups")
936              (mail-fetch-field "newsgroups")
937              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
938     (insert ","))
939   (insert (or (message-fetch-reply-field "newsgroups") "")))
940
941 \f
942
943 ;;; Various commands
944
945 (defun message-insert-signature (&optional force)
946   "Insert a signature.  See documentation for the `message-signature' variable."
947   (interactive (list 0))
948   (let* ((signature 
949           (cond ((and (null message-signature)
950                       (eq force 0))
951                  (save-excursion
952                    (goto-char (point-max))
953                    (not (re-search-backward
954                          message-signature-separator nil t))))
955                 ((and (null message-signature)
956                       force)
957                  t)
958                 ((message-functionp message-signature)
959                  (funcall message-signature))
960                 ((listp message-signature)
961                  (eval message-signature))
962                 (t message-signature)))
963          (signature
964           (cond ((stringp signature)
965                  signature)
966                 ((and (eq t signature)
967                       message-signature-file
968                       (file-exists-p message-signature-file))
969                  signature))))
970     (when signature
971       (goto-char (point-max))
972       ;; Insert the signature.
973       (unless (bolp)
974         (insert "\n"))
975       (insert "\n-- \n")
976       (if (eq signature t)
977           (insert-file-contents message-signature-file)
978         (insert signature))
979       (goto-char (point-max))
980       (or (bolp) (insert "\n")))))
981
982 (defvar message-caesar-translation-table nil)
983
984 (defun message-caesar-region (b e &optional n)
985   "Caesar rotation of region by N, default 13, for decrypting netnews."
986   (interactive
987    (list
988     (min (point) (or (mark t) (point)))
989     (max (point) (or (mark t) (point)))
990     (when current-prefix-arg
991       (prefix-numeric-value current-prefix-arg))))
992
993   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
994   (unless (or (zerop n)                 ; no action needed for a rot of 0
995               (= b e))                  ; no region to rotate
996     ;; We build the table, if necessary.
997     (when (or (not message-caesar-translation-table)
998               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
999       (let ((i -1) 
1000             (table (make-string 256 0)))
1001         (while (< (incf i) 256)
1002           (aset table i i))
1003         (setq table
1004               (concat
1005                (substring table 0 ?A)
1006                (substring table (+ ?A n) (+ ?A n (- 26 n)))
1007                (substring table ?A (+ ?A n))
1008                (substring table (+ ?A 26) ?a)
1009                (substring table (+ ?a n) (+ ?a n (- 26 n)))
1010                (substring table ?a (+ ?a n))
1011                (substring table (+ ?a 26) 255)))
1012         (setq message-caesar-translation-table table)))
1013     ;; Then we translate the region.  Do it this way to retain 
1014     ;; text properties.
1015     (while (< b e)
1016       (subst-char-in-region 
1017        b (1+ b) (char-after b)
1018        (aref message-caesar-translation-table (char-after b)))
1019       (incf b))))
1020
1021 (defun message-caesar-buffer-body (&optional rotnum)
1022   "Caesar rotates all letters in the current buffer by 13 places.
1023 Used to encode/decode possibly offensive messages (commonly in net.jokes).
1024 With prefix arg, specifies the number of places to rotate each letter forward.
1025 Mail and USENET news headers are not rotated."
1026   (interactive (if current-prefix-arg
1027                    (list (prefix-numeric-value current-prefix-arg))
1028                  (list nil)))
1029   (save-excursion
1030     (save-restriction
1031       (when (message-goto-body)
1032         (narrow-to-region (point) (point-max)))
1033       (message-caesar-region (point-min) (point-max) rotnum))))
1034
1035 (defun message-rename-buffer (&optional enter-string)
1036   "Rename the *message* buffer to \"*message* RECIPIENT\".  
1037 If the function is run with a prefix, it will ask for a new buffer
1038 name, rather than giving an automatic name."
1039   (interactive "Pbuffer name: ")
1040   (save-excursion
1041     (save-restriction
1042       (goto-char (point-min))
1043       (narrow-to-region (point) 
1044                         (search-forward mail-header-separator nil 'end))
1045       (let* ((mail-to (if (message-news-p) (message-fetch-field "Newsgroups")
1046                         (message-fetch-field "To")))
1047              (mail-trimmed-to
1048               (if (string-match "," mail-to)
1049                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1050                 mail-to))
1051              (name-default (concat "*message* " mail-trimmed-to))
1052              (name (if enter-string
1053                        (read-string "New buffer name: " name-default)
1054                      name-default)))
1055         (rename-buffer name t)
1056         (setq buffer-auto-save-file-name
1057               (format "%s%s"
1058                       (file-name-as-directory message-autosave-directory)
1059                       (file-name-nondirectory buffer-auto-save-file-name)))))))
1060
1061 (defun message-fill-yanked-message (&optional justifyp)
1062   "Fill the paragraphs of a message yanked into this one.
1063 Numeric argument means justify as well."
1064   (interactive "P")
1065   (save-excursion
1066     (goto-char (point-min))
1067     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1068     (let ((fill-prefix message-yank-prefix))
1069       (fill-individual-paragraphs (point) (point-max) justifyp t))))
1070
1071 (defun message-indent-citation ()
1072   "Modify text just inserted from a message to be cited.
1073 The inserted text should be the region.
1074 When this function returns, the region is again around the modified text.
1075
1076 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1077 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1078   (let ((start (point)))
1079     ;; Remove unwanted headers.
1080     (when message-ignored-cited-headers
1081       (save-restriction
1082         (narrow-to-region 
1083          (goto-char start)
1084          (if (search-forward "\n\n" nil t)
1085              (1- (point))
1086            (point)))
1087         (message-remove-header message-ignored-cited-headers t)))
1088     ;; Do the indentation.
1089     (if (null message-yank-prefix)
1090         (indent-rigidly start (mark t) message-indentation-spaces)
1091       (save-excursion
1092         (goto-char start)
1093         (while (< (point) (mark t))
1094           (insert message-yank-prefix)
1095           (forward-line 1)))
1096       (goto-char start))))
1097
1098 (defun message-yank-original (&optional arg)
1099   "Insert the message being replied to, if any.
1100 Puts point before the text and mark after.
1101 Normally indents each nonblank line ARG spaces (default 3).  However,
1102 if `message-yank-prefix' is non-nil, insert that prefix on each line.
1103
1104 This function uses `message-cite-function' to do the actual citing.
1105
1106 Just \\[universal-argument] as argument means don't indent, insert no
1107 prefix, and don't delete any headers."
1108   (interactive "P")
1109   (let ((modified (buffer-modified-p)))
1110     (when (and message-reply-buffer
1111                message-cite-function)
1112       (delete-windows-on message-reply-buffer t)
1113       (insert-buffer message-reply-buffer)
1114       (funcall message-cite-function)
1115       (message-exchange-point-and-mark)
1116       (unless (bolp)
1117         (insert ?\n))
1118       (unless modified
1119         (setq message-checksum (cons (message-checksum) (buffer-size)))))))
1120
1121 (defun message-cite-original ()    
1122   (let ((start (point))
1123         (functions 
1124          (when message-indent-citation-function
1125            (if (listp message-indent-citation-function)
1126                message-indent-citation-function
1127              (list message-indent-citation-function)))))
1128     (goto-char start)
1129     (while functions
1130       (funcall (pop functions)))
1131     (when message-citation-line-function
1132       (unless (bolp)
1133         (insert "\n"))
1134       (funcall message-citation-line-function))))
1135
1136 (defun message-insert-citation-line ()
1137   "Function that inserts a simple citation line."
1138   (when message-reply-headers
1139     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
1140
1141 (defun message-position-on-field (header &rest afters)
1142   (let ((case-fold-search t))
1143     (save-restriction
1144       (narrow-to-region
1145        (goto-char (point-min))
1146        (progn
1147          (re-search-forward 
1148           (concat "^" (regexp-quote mail-header-separator) "$"))
1149          (match-beginning 0)))
1150       (goto-char (point-min))
1151       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
1152           (progn
1153             (re-search-forward "^[^ \t]" nil 'move)
1154             (beginning-of-line)
1155             (skip-chars-backward "\n")
1156             t)
1157         (while (and afters
1158                     (not (re-search-forward 
1159                           (concat "^" (regexp-quote (car afters)) ":")
1160                           nil t)))
1161           (pop afters))
1162         (when afters
1163           (re-search-forward "^[^ \t]" nil 'move)
1164           (beginning-of-line))
1165         (insert header ": \n")
1166         (forward-char -1)
1167         nil))))
1168
1169 (defun message-remove-signature ()
1170   "Remove the signature from the text between point and mark.
1171 The text will also be indented the normal way."
1172   (save-excursion
1173     (let ((start (point))
1174           mark)
1175     (if (not (re-search-forward message-signature-separator (mark t) t))
1176         ;; No signature here, so we just indent the cited text.
1177         (message-indent-citation)
1178       ;; Find the last non-empty line.
1179       (forward-line -1)
1180       (while (looking-at "[ \t]*$")
1181         (forward-line -1))
1182       (forward-line 1)
1183       (setq mark (set-marker (make-marker) (point)))
1184       (goto-char start)
1185       (message-indent-citation)
1186       ;; Enable undoing the deletion.
1187       (undo-boundary)
1188       (delete-region mark (mark t))
1189       (set-marker mark nil)))))
1190
1191 \f
1192
1193 ;;;
1194 ;;; Sending messages
1195 ;;;
1196
1197 (defun message-send-and-exit (&optional arg)
1198   "Send message like `message-send', then, if no errors, exit from mail buffer."
1199   (interactive "P")
1200   (let ((buf (current-buffer))
1201         (actions message-exit-actions))
1202     (when (and (message-send arg)
1203                (buffer-name buf))
1204       (if message-kill-buffer-on-exit
1205           (kill-buffer buf)
1206         (bury-buffer buf)
1207         (when (eq buf (current-buffer))
1208           (message-bury buf)))
1209       (message-do-actions actions))))
1210
1211 (defun message-dont-send ()
1212   "Don't send the message you have been editing."
1213   (interactive)
1214   (message-bury (current-buffer))
1215   (message-do-actions message-postpone-actions))
1216
1217 (defun message-kill-buffer ()
1218   "Kill the current buffer."
1219   (interactive)
1220   (let ((actions message-kill-actions))
1221     (kill-buffer (current-buffer))
1222     (message-do-actions actions)))
1223
1224 (defun message-bury (buffer)
1225   "Bury this mail buffer."
1226   (let ((newbuf (other-buffer buffer)))
1227     (bury-buffer buffer)
1228     (if (and (fboundp 'frame-parameters)
1229              (cdr (assq 'dedicated (frame-parameters)))
1230              (not (null (delq (selected-frame) (visible-frame-list)))))
1231         (delete-frame (selected-frame))
1232       (switch-to-buffer newbuf))))
1233
1234 (defun message-send (&optional arg)
1235   "Send the message in the current buffer.
1236 If `message-interactive' is non-nil, wait for success indication
1237 or error messages, and inform user.
1238 Otherwise any failure is reported in a message back to
1239 the user from the mailer."
1240   (interactive "P")
1241   (when (if buffer-file-name
1242             (y-or-n-p (format "Send buffer contents as %s message? "
1243                               (if (message-mail-p)
1244                                   (if (message-news-p) "mail and news" "mail")
1245                                 "news")))
1246           (or (buffer-modified-p)
1247               (y-or-n-p "No changes in the buffer; really send? ")))
1248     ;; Make it possible to undo the coming changes.
1249     (undo-boundary)
1250     (let ((inhibit-read-only t))
1251       (put-text-property (point-min) (point-max) 'read-only nil))
1252     (message-fix-before-sending)
1253     (run-hooks 'message-send-hook)
1254     (message "Sending...")
1255     (when (and (or (not (message-news-p))
1256                    (and (or (not (memq 'news message-sent-message-via))
1257                             (y-or-n-p
1258                              "Already sent message via news; resend? "))
1259                         (funcall message-send-news-function arg)))
1260                (or (not (message-mail-p))
1261                    (and (or (not (memq 'mail message-sent-message-via))
1262                             (y-or-n-p
1263                              "Already sent message via mail; resend? "))
1264                         (message-send-mail arg))))
1265       (message-do-fcc)
1266       ;;(when (fboundp 'mail-hist-put-headers-into-history)
1267       ;; (mail-hist-put-headers-into-history))
1268       (run-hooks 'message-sent-hook)
1269       (message "Sending...done")
1270       ;; If buffer has no file, mark it as unmodified and delete autosave.
1271       (unless buffer-file-name
1272         (set-buffer-modified-p nil)
1273         (delete-auto-save-file-if-necessary t))
1274       ;; Delete other mail buffers and stuff.
1275       (message-do-send-housekeeping)
1276       (message-do-actions message-send-actions)
1277       ;; Return success.
1278       t)))
1279
1280 (defun message-fix-before-sending ()
1281   "Do various things to make the message nice before sending it."
1282   ;; Make sure there's a newline at the end of the message.
1283   (goto-char (point-max))
1284   (unless (bolp)
1285     (insert "\n")))
1286
1287 (defun message-add-action (action &rest types)
1288   "Add ACTION to be performed when doing an exit of type TYPES."
1289   (let (var)
1290     (while types
1291       (set (setq var (intern (format "message-%s-actions" (pop types))))
1292            (nconc (symbol-value var) (list action))))))
1293
1294 (defun message-do-actions (actions)
1295   "Perform all actions in ACTIONS."
1296   ;; Now perform actions on successful sending.
1297   (while actions
1298     (condition-case nil
1299         (cond 
1300          ;; A simple function.
1301          ((message-functionp (car actions))
1302           (funcall (car actions)))
1303          ;; Something to be evaled.
1304          (t
1305           (eval (car actions))))
1306       (error))
1307     (pop actions)))
1308
1309 (defun message-send-mail (&optional arg)
1310   (require 'mail-utils)
1311   (let ((tembuf (generate-new-buffer " message temp"))
1312         (case-fold-search nil)
1313         (news (message-news-p))
1314         (mailbuf (current-buffer)))
1315     (save-restriction
1316       (message-narrow-to-headers)
1317       ;; Insert some headers.
1318       (let ((message-deletable-headers
1319              (if news nil message-deletable-headers)))
1320         (message-generate-headers message-required-mail-headers))
1321       ;; Let the user do all of the above.
1322       (run-hooks 'message-header-hook))
1323     (unwind-protect
1324         (save-excursion
1325           (set-buffer tembuf)
1326           (erase-buffer)
1327           ;; Avoid copying text props.
1328           (insert (format 
1329                    "%s" (save-excursion
1330                           (set-buffer mailbuf)
1331                           (buffer-string))))
1332           ;; Remove some headers.
1333           (save-restriction
1334             (message-narrow-to-headers)
1335             ;; Remove some headers.
1336             (message-remove-header message-ignored-mail-headers t))
1337           (goto-char (point-max))
1338           ;; require one newline at the end.
1339           (or (= (preceding-char) ?\n)
1340               (insert ?\n))
1341           (when (and news
1342                      (or (message-fetch-field "cc")
1343                          (message-fetch-field "to")))
1344             (message-insert-courtesy-copy))
1345           (funcall message-send-mail-function))
1346       (kill-buffer tembuf))
1347     (set-buffer mailbuf)
1348     (push 'mail message-sent-message-via)))
1349
1350 (defun message-send-mail-with-sendmail ()
1351   "Send off the prepared buffer with sendmail."
1352   (let ((errbuf (if message-interactive
1353                     (generate-new-buffer " sendmail errors")
1354                   0))
1355         resend-to-addresses delimline)
1356     (let ((case-fold-search t))
1357       (save-restriction
1358         (message-narrow-to-headers)
1359         (setq resend-to-addresses (message-fetch-field "resent-to")))
1360       ;; Change header-delimiter to be what sendmail expects.
1361       (goto-char (point-min))
1362       (re-search-forward
1363        (concat "^" (regexp-quote mail-header-separator) "\n"))
1364       (replace-match "\n")
1365       (backward-char 1)
1366       (setq delimline (point-marker))
1367       ;; Insert an extra newline if we need it to work around
1368       ;; Sun's bug that swallows newlines.
1369       (goto-char (1+ delimline))
1370       (when (eval message-mailer-swallows-blank-line)
1371         (newline))
1372       (when message-interactive
1373         (save-excursion
1374           (set-buffer errbuf)
1375           (erase-buffer))))
1376     (let ((default-directory "/"))
1377       (apply 'call-process-region
1378              (append (list (point-min) (point-max)
1379                            (if (boundp 'sendmail-program)
1380                                sendmail-program
1381                              "/usr/lib/sendmail")
1382                            nil errbuf nil "-oi")
1383                      ;; Always specify who from,
1384                      ;; since some systems have broken sendmails.
1385                      (list "-f" (user-login-name))
1386                      ;; These mean "report errors by mail"
1387                      ;; and "deliver in background".
1388                      (if (null message-interactive) '("-oem" "-odb"))
1389                      ;; Get the addresses from the message
1390                      ;; unless this is a resend.
1391                      ;; We must not do that for a resend
1392                      ;; because we would find the original addresses.
1393                      ;; For a resend, include the specific addresses.
1394                      (if resend-to-addresses
1395                          (list resend-to-addresses)
1396                        '("-t")))))
1397     (when message-interactive
1398       (save-excursion
1399         (set-buffer errbuf)
1400         (goto-char (point-min))
1401         (while (re-search-forward "\n\n* *" nil t)
1402           (replace-match "; "))
1403         (if (not (zerop (buffer-size)))
1404             (error "Sending...failed to %s"
1405                    (buffer-substring (point-min) (point-max)))))
1406       (when (bufferp errbuf)
1407         (kill-buffer errbuf)))))
1408
1409 (defun message-send-mail-with-mh ()
1410   "Send the prepared message buffer with mh."
1411   (let ((mh-previous-window-config nil)
1412         (name (make-temp-name
1413                (concat (file-name-as-directory message-autosave-directory)
1414                        "msg."))))
1415     (setq buffer-file-name name)
1416     (mh-send-letter)
1417     (condition-case ()
1418         (delete-file name)
1419       (error nil))))
1420
1421 (defun message-send-news (&optional arg)
1422   (let ((tembuf (generate-new-buffer " *message temp*"))
1423         (case-fold-search nil)
1424         (method (if (message-functionp message-post-method)
1425                     (funcall message-post-method arg)
1426                   message-post-method))
1427         (messbuf (current-buffer))
1428         (message-syntax-checks
1429          (if arg
1430              (cons '(existing-newsgroups . disabled)
1431                    message-syntax-checks)
1432            message-syntax-checks))
1433         result)
1434     (save-restriction
1435       (message-narrow-to-headers)
1436       ;; Insert some headers.
1437       (message-generate-headers message-required-news-headers)
1438       ;; Let the user do all of the above.
1439       (run-hooks 'message-header-hook))
1440     (message-cleanup-headers)
1441     (when (message-check-news-syntax)
1442       (unwind-protect
1443           (save-excursion
1444             (set-buffer tembuf)
1445             (buffer-disable-undo (current-buffer))
1446             (erase-buffer) 
1447             ;; Avoid copying text props.
1448           (insert (format 
1449                    "%s" (save-excursion
1450                           (set-buffer messbuf)
1451                           (buffer-string))))
1452             ;; Remove some headers.
1453             (save-restriction
1454               (message-narrow-to-headers)
1455               ;; Remove some headers.
1456               (message-remove-header message-ignored-news-headers t))
1457             (goto-char (point-max))
1458             ;; require one newline at the end.
1459             (or (= (preceding-char) ?\n)
1460                 (insert ?\n))
1461             (let ((case-fold-search t))
1462               ;; Remove the delimeter.
1463               (goto-char (point-min))
1464               (re-search-forward
1465                (concat "^" (regexp-quote mail-header-separator) "\n"))
1466               (replace-match "\n")
1467               (backward-char 1))
1468             (require (car method))
1469             (funcall (intern (format "%s-open-server" (car method)))
1470                      (cadr method) (cddr method))
1471             (setq result
1472                   (funcall (intern (format "%s-request-post" (car method))))))
1473         (kill-buffer tembuf))
1474       (set-buffer messbuf)
1475       (if result
1476           (push 'news message-sent-message-via)
1477         (message "Couldn't send message via news: %s"
1478                  (nnheader-get-report (car method)))
1479         nil))))
1480
1481 ;;;
1482 ;;; Header generation & syntax checking.
1483 ;;;
1484
1485 (defun message-check-news-syntax ()
1486   "Check the syntax of the message."
1487   (and 
1488    ;; We narrow to the headers and check them first.
1489    (save-excursion
1490      (save-restriction
1491        (message-narrow-to-headers)
1492        (and 
1493         ;; Check for commands in Subject.
1494         (or 
1495          (message-check-element 'subject-cmsg)
1496          (save-excursion
1497            (if (string-match "^cmsg " (message-fetch-field "subject"))
1498                (y-or-n-p
1499                 "The control code \"cmsg \" is in the subject. Really post? ")
1500              t)))
1501         ;; Check for multiple identical headers.
1502         (or (message-check-element 'multiple-headers)
1503             (save-excursion
1504               (let (found)
1505                 (while (and (not found) 
1506                             (re-search-forward "^[^ \t:]+: " nil t))
1507                   (save-excursion
1508                     (or (re-search-forward 
1509                          (concat "^" (setq found
1510                                            (buffer-substring 
1511                                             (match-beginning 0) 
1512                                             (- (match-end 0) 2))))
1513                          nil t)
1514                         (setq found nil))))
1515                 (if found
1516                     (y-or-n-p 
1517                      (format "Multiple %s headers. Really post? " found))
1518                   t))))
1519         ;; Check for Version and Sendsys.
1520         (or (message-check-element 'sendsys)
1521             (save-excursion
1522               (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
1523                   (y-or-n-p
1524                    (format "The article contains a %s command. Really post? "
1525                            (buffer-substring (match-beginning 0) 
1526                                              (1- (match-end 0)))))
1527                 t)))
1528         ;; See whether we can shorten Followup-To.
1529         (or (message-check-element 'shorten-followup-to)
1530             (let ((newsgroups (message-fetch-field "newsgroups"))
1531                   (followup-to (message-fetch-field "followup-to"))
1532                   to)
1533               (when (and newsgroups (string-match "," newsgroups)
1534                          (not followup-to)
1535                          (not
1536                           (zerop
1537                            (length
1538                             (setq to (completing-read 
1539                                       "Followups to: (default all groups) " 
1540                                       (mapcar (lambda (g) (list g))
1541                                               (cons "poster" 
1542                                                     (message-tokenize-header 
1543                                                      newsgroups)))))))))
1544                 (goto-char (point-min))
1545                 (insert "Followup-To: " to "\n"))
1546               t))
1547         ;; Check "Shoot me".
1548         (or (message-check-element 'shoot)
1549             (save-excursion
1550               (if (re-search-forward
1551                    "Message-ID.*.i-have-a-misconfigured-system-so-shoot-me"
1552                    nil t)
1553                   (y-or-n-p
1554                    "You appear to have a misconfigured system.  Really post? ")
1555                 t)))
1556         ;; Check for Approved.
1557         (or (message-check-element 'approved)
1558             (save-excursion
1559               (if (re-search-forward "^Approved:" nil t)
1560                   (y-or-n-p
1561                    "The article contains an Approved header. Really post? ")
1562                 t)))
1563         ;; Check the Message-Id header.
1564         (or (message-check-element 'message-id)
1565             (save-excursion
1566               (let* ((case-fold-search t)
1567                      (message-id (message-fetch-field "message-id")))
1568                 (or (not message-id)
1569                     (and (string-match "@" message-id)
1570                          (string-match "@[^\\.]*\\." message-id))
1571                     (y-or-n-p
1572                      (format 
1573                       "The Message-ID looks strange: \"%s\". Really post? "
1574                       message-id))))))
1575         ;; Check the Subject header.
1576         (or 
1577          (message-check-element 'subject)
1578          (save-excursion
1579            (let* ((case-fold-search t)
1580                   (subject (message-fetch-field "subject")))
1581              (or
1582               (and subject
1583                    (not (string-match "\\`[ \t]*\\'" subject)))
1584               (progn
1585                 (message 
1586                  "The subject field is empty or missing.  Posting is denied.")
1587                 nil)))))
1588         ;; Check the Newsgroups & Followup-To headers.
1589         (or
1590          (message-check-element 'existing-newsgroups)
1591          (let* ((case-fold-search t)
1592                 (newsgroups (message-fetch-field "newsgroups"))
1593                 (followup-to (message-fetch-field "followup-to"))
1594                 (groups (message-tokenize-header
1595                          (if followup-to
1596                              (concat newsgroups "," followup-to)
1597                            newsgroups)))
1598                 (hashtb (and (boundp 'gnus-active-hashtb)
1599                              gnus-active-hashtb))
1600                 errors)
1601            (if (not hashtb)
1602                t
1603              (while groups
1604                (when (and (not (boundp (intern (car groups) hashtb)))
1605                           (not (equal (car groups) "poster")))
1606                  (push (car groups) errors))
1607                (pop groups))
1608              (if (not errors)
1609                  t
1610                (y-or-n-p
1611                 (format
1612                  "Really post to %s unknown group%s: %s "
1613                  (if (= (length errors) 1) "this" "these")
1614                  (if (= (length errors) 1) "" "s")
1615                  (mapconcat 'identity errors ", ")))))))
1616         ;; Check the Newsgroups & Followup-To headers for syntax errors.
1617         (or
1618          (message-check-element 'valid-newsgroups)
1619          (let ((case-fold-search t)
1620                (headers '("Newsgroups" "Followup-To"))
1621                header error)
1622            (while (and headers (not error))
1623              (when (setq header (mail-fetch-field (car headers)))
1624                (if (or
1625                     (not 
1626                      (string-match
1627                       "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-.a-zA-Z0-9]+\\)*\\'"
1628                       header))
1629                     (memq 
1630                      nil (mapcar 
1631                           (lambda (g)
1632                             (not (string-match "\\.\\'\\|\\.\\." g)))
1633                           (message-tokenize-header header ","))))
1634                    (setq error t)))
1635              (unless error
1636                (pop headers)))
1637            (if (not error)
1638                t
1639              (y-or-n-p
1640               (format "The %s header looks odd: \"%s\".  Really post? "
1641                       (car headers) header)))))
1642         ;; Check the From header.
1643         (or 
1644          (save-excursion
1645            (let* ((case-fold-search t)
1646                   (from (message-fetch-field "from")))
1647              (cond
1648               ((not from)
1649                (message "There is no From line.  Posting is denied.")
1650                nil)
1651               ((not (string-match "@[^\\.]*\\." from))
1652                (message
1653                 "Denied posting -- the From looks strange: \"%s\"." from)
1654                nil)
1655               ((string-match "@[^@]*@" from)
1656                (message 
1657                 "Denied posting -- two \"@\"'s in the From header: %s." from)
1658                nil)
1659               ((string-match "(.*).*(.*)" from)
1660                (message
1661                 "Denied posting -- the From header looks strange: \"%s\"." 
1662                 from)
1663                nil)
1664               (t t))))))))
1665    ;; Check for long lines.
1666    (or (message-check-element 'long-lines)
1667        (save-excursion
1668          (goto-char (point-min))
1669          (re-search-forward
1670           (concat "^" (regexp-quote mail-header-separator) "$"))
1671          (while (and
1672                  (progn
1673                    (end-of-line)
1674                    (< (current-column) 80))
1675                  (zerop (forward-line 1))))
1676          (or (bolp)
1677              (eobp)
1678              (y-or-n-p
1679               "You have lines longer than 79 characters.  Really post? "))))
1680    ;; Check whether the article is empty.
1681    (or (message-check-element 'empty)
1682        (save-excursion
1683          (goto-char (point-min))
1684          (re-search-forward
1685           (concat "^" (regexp-quote mail-header-separator) "$"))
1686          (forward-line 1)
1687          (let ((b (point)))
1688            (goto-char (point-max))
1689            (re-search-backward message-signature-separator nil t)
1690            (beginning-of-line)
1691            (or (re-search-backward "[^ \n\t]" b t)
1692                (y-or-n-p "Empty article.  Really post? ")))))
1693    ;; Check for control characters.
1694    (or (message-check-element 'control-chars)
1695        (save-excursion
1696          (if (re-search-forward "[\000-\007\013\015-\037\200-\237]" nil t)
1697              (y-or-n-p 
1698               "The article contains control characters. Really post? ")
1699            t)))
1700    ;; Check excessive size.
1701    (or (message-check-element 'size)
1702        (if (> (buffer-size) 60000)
1703            (y-or-n-p
1704             (format "The article is %d octets long. Really post? "
1705                     (buffer-size)))
1706          t))
1707    ;; Check whether any new text has been added.
1708    (or (message-check-element 'new-text)
1709        (not message-checksum)
1710        (not (and (eq (message-checksum) (car message-checksum))
1711                  (eq (buffer-size) (cdr message-checksum))))
1712        (y-or-n-p
1713         "It looks like no new text has been added.  Really post? "))
1714    ;; Check the length of the signature.
1715    (or
1716     (message-check-element 'signature)
1717     (progn
1718       (goto-char (point-max))
1719       (if (or (not (re-search-backward message-signature-separator nil t))
1720               (search-forward message-forward-end-separator nil t))
1721           t
1722         (if (> (count-lines (point) (point-max)) 5)
1723             (y-or-n-p
1724              (format
1725               "Your .sig is %d lines; it should be max 4.  Really post? "
1726               (count-lines (point) (point-max))))
1727           t))))))
1728
1729 (defun message-check-element (type)
1730   "Returns non-nil if this type is not to be checked."
1731   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
1732       t
1733     (let ((able (assq type message-syntax-checks)))
1734       (and (consp able)
1735            (eq (cdr able) 'disabled)))))
1736
1737 (defun message-checksum ()
1738   "Return a \"checksum\" for the current buffer."
1739   (let ((sum 0))
1740     (save-excursion
1741       (goto-char (point-min))
1742       (re-search-forward
1743        (concat "^" (regexp-quote mail-header-separator) "$"))
1744       (while (not (eobp))
1745         (when (not (looking-at "[ \t\n]"))
1746           (setq sum (logxor (ash sum 1) (following-char))))
1747         (forward-char 1)))
1748     sum))
1749
1750 (defun message-do-fcc ()
1751   "Process Fcc headers in the current buffer."
1752   (let ((case-fold-search t)
1753         (buf (current-buffer))
1754         list file)
1755     (save-excursion
1756       (set-buffer (get-buffer-create " *message temp*"))
1757       (buffer-disable-undo (current-buffer))
1758       (erase-buffer)
1759       (insert-buffer-substring buf)
1760       (save-restriction
1761         (message-narrow-to-headers)
1762         (while (setq file (message-fetch-field "fcc"))
1763           (push file list)
1764           (message-remove-header "fcc" nil t)))
1765       (goto-char (point-min))
1766       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
1767       (replace-match "" t t)
1768       ;; Process FCC operations.
1769       (while list
1770         (setq file (pop list))
1771         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
1772             ;; Pipe the article to the program in question.
1773             (call-process-region (point-min) (point-max) shell-file-name
1774                                  nil nil nil shell-command-switch
1775                                  (match-string 1 file))
1776           ;; Save the article.
1777           (setq file (expand-file-name file))
1778           (unless (file-exists-p (file-name-directory file))
1779             (make-directory (file-name-directory file) t))
1780           (if (and message-fcc-handler-function
1781                    (not (eq message-fcc-handler-function 'rmail-output)))
1782               (funcall message-fcc-handler-function file)
1783             (if (and (file-readable-p file) (mail-file-babyl-p file))
1784                 (rmail-output file 1)
1785               (let ((mail-use-rfc822 t))
1786                 (rmail-output file 1 t t))))))
1787       (kill-buffer (current-buffer)))))
1788
1789 (defun message-cleanup-headers ()
1790   "Do various automatic cleanups of the headers."
1791   ;; Remove empty lines in the header.
1792   (save-restriction
1793     (message-narrow-to-headers)
1794     (while (re-search-forward "^[ \t]*\n" nil t)
1795       (replace-match "" t t)))
1796
1797   ;; Correct Newsgroups and Followup-To headers: change sequence of
1798   ;; spaces to comma and eliminate spaces around commas.  Eliminate
1799   ;; embedded line breaks.
1800   (goto-char (point-min))
1801   (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
1802     (save-restriction
1803       (narrow-to-region
1804        (point)
1805        (if (re-search-forward "^[^ \t]" nil t)
1806            (match-beginning 0)
1807          (forward-line 1)
1808          (point)))
1809       (goto-char (point-min))
1810       (while (re-search-forward "\n[ \t]+" nil t)
1811         (replace-match " " t t))        ;No line breaks (too confusing)
1812       (goto-char (point-min))
1813       (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
1814         (replace-match "," t t))
1815       (goto-char (point-min))
1816       ;; Remove trailing commas.
1817       (when (re-search-forward ",+$" nil t)
1818         (replace-match "" t t)))))
1819
1820 (defun message-make-date ()
1821   "Make a valid data header."
1822   (let ((now (current-time)))
1823     (timezone-make-date-arpa-standard 
1824      (current-time-string now) (current-time-zone now))))
1825
1826 (defun message-make-message-id ()
1827   "Make a unique Message-ID."
1828   (concat "<" (message-unique-id) 
1829           (let ((psubject (save-excursion (message-fetch-field "subject"))))
1830             (if (and message-reply-headers
1831                      (mail-header-references message-reply-headers)
1832                      (mail-header-subject message-reply-headers)
1833                      psubject
1834                      (mail-header-subject message-reply-headers)
1835                      (not (string= 
1836                            (message-strip-subject-re
1837                             (mail-header-subject message-reply-headers))
1838                            (message-strip-subject-re psubject))))
1839                 "_-_" ""))
1840           "@" (message-make-fqdn) ">"))
1841
1842 (defvar message-unique-id-char nil)
1843
1844 ;; If you ever change this function, make sure the new version
1845 ;; cannot generate IDs that the old version could.
1846 ;; You might for example insert a "." somewhere (not next to another dot
1847 ;; or string boundary), or modify the "fsf" string.
1848 (defun message-unique-id ()
1849   ;; Don't use microseconds from (current-time), they may be unsupported.
1850   ;; Instead we use this randomly inited counter.
1851   (setq message-unique-id-char
1852         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
1853            ;; (current-time) returns 16-bit ints,
1854            ;; and 2^16*25 just fits into 4 digits i base 36.
1855            (* 25 25)))
1856   (let ((tm (current-time)))
1857     (concat
1858      (if (memq system-type '(ms-dos emx vax-vms))
1859          (let ((user (downcase (user-login-name))))
1860            (while (string-match "[^a-z0-9_]" user)
1861              (aset user (match-beginning 0) ?_))
1862            user)
1863        (message-number-base36 (user-uid) -1))
1864      (message-number-base36 (+ (car   tm) 
1865                                (lsh (% message-unique-id-char 25) 16)) 4)
1866      (message-number-base36 (+ (nth 1 tm)
1867                                (lsh (/ message-unique-id-char 25) 16)) 4)
1868      ;; Append the newsreader name, because while the generated
1869      ;; ID is unique to this newsreader, other newsreaders might
1870      ;; otherwise generate the same ID via another algorithm.
1871      ".fsf")))
1872
1873 (defun message-number-base36 (num len)
1874   (if (if (< len 0) (<= num 0) (= len 0))
1875       ""
1876     (concat (message-number-base36 (/ num 36) (1- len))
1877             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
1878                                   (% num 36))))))
1879
1880 (defun message-make-organization ()
1881   "Make an Organization header."
1882   (let* ((organization 
1883           (or (getenv "ORGANIZATION")
1884               (when message-user-organization
1885                 (if (message-functionp message-user-organization)
1886                     (funcall message-user-organization)
1887                   message-user-organization)))))
1888     (save-excursion
1889       (message-set-work-buffer)
1890       (cond ((stringp organization)
1891              (insert organization))
1892             ((and (eq t organization)
1893                   message-user-organization-file
1894                   (file-exists-p message-user-organization-file))
1895              (insert-file-contents message-user-organization-file)))
1896       (goto-char (point-min))
1897       (while (re-search-forward "[\t\n]+" nil t)
1898         (replace-match "" t t))
1899       (unless (zerop (buffer-size))
1900         (buffer-string)))))
1901
1902 (defun message-make-lines ()
1903   "Count the number of lines and return numeric string."
1904   (save-excursion
1905     (save-restriction
1906       (widen)
1907       (goto-char (point-min))
1908       (re-search-forward 
1909        (concat "^" (regexp-quote mail-header-separator) "$"))
1910       (forward-line 1)
1911       (int-to-string (count-lines (point) (point-max))))))
1912
1913 (defun message-make-in-reply-to ()
1914   "Return the In-Reply-To header for this message."
1915   (when message-reply-headers
1916     (let ((from (mail-header-from message-reply-headers))
1917           (date (mail-header-date message-reply-headers)))
1918       (when from
1919         (let ((stop-pos 
1920                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
1921           (concat (if stop-pos (substring from 0 stop-pos) from)
1922                   "'s message of " 
1923                   (if (or (not date) (string= date ""))
1924                       "(unknown date)" date)))))))
1925
1926 (defun message-make-distribution ()
1927   "Make a Distribution header."
1928   (let ((orig-distribution (message-fetch-reply-field "distribution")))
1929     (cond ((message-functionp message-distribution-function)
1930            (funcall message-distribution-function))
1931           (t orig-distribution))))
1932
1933 (defun message-make-expires ()
1934   "Return an Expires header based on `message-expires'."
1935   (let ((current (current-time))
1936         (future (* 1.0 message-expires 60 60 24)))
1937     ;; Add the future to current.
1938     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
1939     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
1940     ;; Return the date in the future in UT.
1941     (timezone-make-date-arpa-standard 
1942      (current-time-string current) (current-time-zone current) '(0 "UT"))))
1943
1944 (defun message-make-path ()
1945   "Return uucp path."
1946   (let ((login-name (user-login-name)))
1947     (cond ((null message-user-path)
1948            (concat (system-name) "!" login-name))
1949           ((stringp message-user-path)
1950            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
1951            (concat message-user-path "!" login-name))
1952           (t login-name))))
1953
1954 (defun message-make-from ()
1955   "Make a From header."
1956   (let* ((login (message-make-address))
1957          (fullname 
1958           (or (and (boundp 'user-full-name)
1959                    user-full-name)
1960               (user-full-name))))
1961     (when (string= fullname "&")
1962       (setq fullname (user-login-name)))
1963     (save-excursion
1964       (message-set-work-buffer)
1965       (cond 
1966        ((or (null message-from-style)
1967             (equal fullname ""))
1968         (insert login))
1969        ((or (eq message-from-style 'angles)
1970             (and (not (eq message-from-style 'parens))
1971                  ;; Use angles if no quoting is needed, or if parens would
1972                  ;; need quoting too.
1973                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
1974                      (let ((tmp (concat fullname nil)))
1975                        (while (string-match "([^()]*)" tmp)
1976                          (aset tmp (match-beginning 0) ?-)
1977                          (aset tmp (1- (match-end 0)) ?-))
1978                        (string-match "[\\()]" tmp)))))
1979         (insert fullname)
1980         (goto-char (point-min))
1981         ;; Look for a character that cannot appear unquoted
1982         ;; according to RFC 822.
1983         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
1984           ;; Quote fullname, escaping specials.
1985           (goto-char (point-min))
1986           (insert "\"")
1987           (while (re-search-forward "[\"\\]" nil 1)
1988             (replace-match "\\\\\\&" t))
1989           (insert "\""))
1990         (insert " <" login ">"))
1991        (t                               ; 'parens or default
1992         (insert login " (")
1993         (let ((fullname-start (point)))
1994           (insert fullname)
1995           (goto-char fullname-start)
1996           ;; RFC 822 says \ and nonmatching parentheses
1997           ;; must be escaped in comments.
1998           ;; Escape every instance of ()\ ...
1999           (while (re-search-forward "[()\\]" nil 1)
2000             (replace-match "\\\\\\&" t))
2001           ;; ... then undo escaping of matching parentheses,
2002           ;; including matching nested parentheses.
2003           (goto-char fullname-start)
2004           (while (re-search-forward 
2005                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
2006                     nil 1)
2007             (replace-match "\\1(\\3)" t)
2008             (goto-char fullname-start)))
2009         (insert ")")))
2010       (buffer-string))))
2011
2012 (defun message-make-sender ()
2013   "Return the \"real\" user address.
2014 This function tries to ignore all user modifications, and 
2015 give as trustworthy answer as possible."
2016   (concat (user-login-name) "@" (system-name)))
2017
2018 (defun message-make-address ()
2019   "Make the address of the user."
2020   (or (message-user-mail-address)
2021       (concat (user-login-name) "@" (message-make-domain))))
2022
2023 (defun message-user-mail-address ()
2024   "Return the pertinent part of `user-mail-address'."
2025   (when user-mail-address
2026     (nth 1 (mail-extract-address-components user-mail-address))))
2027
2028 (defun message-make-fqdn ()
2029   "Return user's fully qualified domain name."
2030   (let ((system-name (system-name))
2031         (user-mail (message-user-mail-address)))
2032     (cond 
2033      ((string-match "[^.]\\.[^.]" system-name)
2034       ;; `system-name' returned the right result.
2035       system-name)
2036      ;; Try `mail-host-address'.
2037      ((and (boundp 'mail-host-address)
2038            (stringp mail-host-address)
2039            (string-match "\\." mail-host-address))
2040       mail-host-address)
2041      ;; We try `user-mail-address' as a backup.
2042      ((and (string-match "\\." user-mail)
2043            (string-match "@\\(.*\\)\\'" user-mail))
2044       (match-string 1 user-mail))
2045      ;; Default to this bogus thing.
2046      (t
2047       (concat system-name ".i-have-a-misconfigured-system-so-shoot-me")))))
2048
2049 (defun message-make-host-name ()
2050   "Return the name of the host."
2051   (let ((fqdn (message-make-fqdn)))
2052     (string-match "^[^.]+\\." fqdn)
2053     (substring fqdn 0 (1- (match-end 0)))))
2054
2055 (defun message-make-domain ()
2056   "Return the domain name."
2057   (or mail-host-address
2058       (message-make-fqdn)))
2059
2060 (defun message-generate-headers (headers)
2061   "Prepare article HEADERS.
2062 Headers already prepared in the buffer are not modified."
2063   (save-restriction
2064     (message-narrow-to-headers)
2065     (let* ((Date (message-make-date))
2066            (Message-ID (message-make-message-id))
2067            (Organization (message-make-organization))
2068            (From (message-make-from))
2069            (Path (message-make-path))
2070            (Subject nil)
2071            (Newsgroups nil)
2072            (In-Reply-To (message-make-in-reply-to))
2073            (To nil)
2074            (Distribution (message-make-distribution))
2075            (Lines (message-make-lines))
2076            (X-Newsreader message-newsreader)
2077            (X-Mailer (and (not (message-fetch-field "X-Newsreader"))
2078                           message-mailer))
2079            (Expires (message-make-expires))
2080            (case-fold-search t)
2081            header value elem)
2082       ;; First we remove any old generated headers.
2083       (let ((headers message-deletable-headers))
2084         (while headers
2085           (goto-char (point-min))
2086           (and (re-search-forward 
2087                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2088                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
2089                (message-delete-line))
2090           (pop headers)))
2091       ;; Go through all the required headers and see if they are in the
2092       ;; articles already. If they are not, or are empty, they are
2093       ;; inserted automatically - except for Subject, Newsgroups and
2094       ;; Distribution. 
2095       (while headers
2096         (goto-char (point-min))
2097         (setq elem (pop headers))
2098         (if (consp elem)
2099             (if (eq (car elem) 'optional)
2100                 (setq header (cdr elem))
2101               (setq header (car elem)))
2102           (setq header elem))
2103         (when (or (not (re-search-forward 
2104                         (concat "^" (downcase (symbol-name header)) ":") 
2105                         nil t))
2106                   (progn
2107                     ;; The header was found. We insert a space after the
2108                     ;; colon, if there is none.
2109                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
2110                     ;; Find out whether the header is empty...
2111                     (looking-at "[ \t]*$")))
2112           ;; So we find out what value we should insert.
2113           (setq value
2114                 (cond 
2115                  ((and (consp elem) (eq (car elem) 'optional))
2116                   ;; This is an optional header.  If the cdr of this
2117                   ;; is something that is nil, then we do not insert
2118                   ;; this header.
2119                   (setq header (cdr elem))
2120                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
2121                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
2122                  ((consp elem)
2123                   ;; The element is a cons.  Either the cdr is a
2124                   ;; string to be inserted verbatim, or it is a
2125                   ;; function, and we insert the value returned from
2126                   ;; this function.
2127                   (or (and (stringp (cdr elem)) (cdr elem))
2128                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
2129                  ((and (boundp header) (symbol-value header))
2130                   ;; The element is a symbol.  We insert the value
2131                   ;; of this symbol, if any.
2132                   (symbol-value header))
2133                  (t
2134                   ;; We couldn't generate a value for this header,
2135                   ;; so we just ask the user.
2136                   (read-from-minibuffer
2137                    (format "Empty header for %s; enter value: " header)))))
2138           ;; Finally insert the header.
2139           (when (and value 
2140                      (not (equal value "")))
2141             (save-excursion
2142               (if (bolp)
2143                   (progn
2144                     ;; This header didn't exist, so we insert it.
2145                     (goto-char (point-max))
2146                     (insert (symbol-name header) ": " value "\n")
2147                     (forward-line -1))
2148                 ;; The value of this header was empty, so we clear
2149                 ;; totally and insert the new value.
2150                 (delete-region (point) (message-point-at-eol))
2151                 (insert value))
2152               ;; Add the deletable property to the headers that require it.
2153               (and (memq header message-deletable-headers)
2154                    (progn (beginning-of-line) (looking-at "[^:]+: "))
2155                    (add-text-properties 
2156                     (point) (match-end 0)
2157                     '(message-deletable t face italic) (current-buffer)))))))
2158       ;; Insert new Sender if the From is strange. 
2159       (let ((from (message-fetch-field "from"))
2160             (sender (message-fetch-field "sender"))
2161             (secure-sender (message-make-sender)))
2162         (when (and from 
2163                    (not (message-check-element 'sender))
2164                    (not (string=
2165                          (downcase
2166                           (cadr (mail-extract-address-components from)))
2167                          (downcase secure-sender)))
2168                    (or (null sender)
2169                        (not 
2170                         (string=
2171                          (downcase
2172                           (cadr (mail-extract-address-components sender)))
2173                          (downcase secure-sender)))))
2174           (goto-char (point-min))    
2175           ;; Rename any old Sender headers to Original-Sender.
2176           (when (re-search-forward "^Sender:" nil t)
2177             (beginning-of-line)
2178             (insert "Original-")
2179             (beginning-of-line))
2180           (insert "Sender: " secure-sender "\n"))))))
2181
2182 (defun message-insert-courtesy-copy ()
2183   "Insert a courtesy message in mail copies of combined messages."
2184   (save-excursion
2185     (save-restriction
2186       (message-narrow-to-headers)
2187       (let ((newsgroups (message-fetch-field "newsgroups")))
2188         (when newsgroups
2189           (goto-char (point-max))
2190           (insert "Posted-To: " newsgroups "\n"))))
2191     (forward-line 1)
2192     (insert message-courtesy-message)))
2193     
2194 ;;;
2195 ;;; Setting up a message buffer
2196 ;;;
2197
2198 (defun message-fill-address (header value)
2199   (save-restriction
2200     (narrow-to-region (point) (point))
2201     (insert (capitalize (symbol-name header))
2202             ": "
2203             (if (consp value) (car value) value)
2204             "\n")
2205     (narrow-to-region (point-min) (1- (point-max)))
2206     (let (quoted last)
2207       (goto-char (point-min))
2208       (while (not (eobp))
2209         (skip-chars-forward "^,\"" (point-max))
2210         (if (or (= (following-char) ?,)
2211                 (eobp))
2212             (when (not quoted)
2213               (if (and (> (current-column) 78)
2214                        last)
2215                   (progn
2216                     (save-excursion
2217                       (goto-char last)
2218                       (insert "\n\t"))
2219                     (setq last (1+ (point))))
2220                 (setq last (1+ (point)))))
2221           (setq quoted (not quoted)))
2222         (unless (eobp)
2223           (forward-char 1))))
2224     (goto-char (point-max))
2225     (widen)
2226     (forward-line 1)))
2227
2228 (defun message-fill-header (header value)
2229   (let ((begin (point))
2230         (fill-column 78)
2231         (fill-prefix "\t"))
2232     (insert (capitalize (symbol-name header))
2233             ": "
2234             (if (consp value) (car value) value)
2235             "\n")
2236     (save-restriction
2237       (narrow-to-region begin (point))
2238       (fill-region-as-paragraph begin (point))
2239       ;; Tapdance around looong Message-IDs.
2240       (forward-line -1)
2241       (when (looking-at "[ \t]*$")
2242         (message-delete-line))
2243       (goto-char begin)
2244       (re-search-forward ":" nil t)
2245       (when (looking-at "\n[ \t]+")
2246         (replace-match " " t t))
2247       (goto-char (point-max)))))
2248
2249 (defun message-position-point ()
2250   "Move point to where the user probably wants to find it."
2251   (message-narrow-to-headers)
2252   (cond 
2253    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
2254     (search-backward ":" )
2255     (widen)
2256     (forward-char 1)
2257     (if (= (following-char) ? )
2258         (forward-char 1)
2259       (insert " ")))
2260    (t
2261     (goto-char (point-max))
2262     (widen)
2263     (forward-line 1)
2264     (unless (looking-at "$")
2265       (forward-line 2)))
2266    (sit-for 0)))
2267
2268 (defun message-buffer-name (type &optional to group)
2269   "Return a new (unique) buffer name based on TYPE and TO."
2270   (cond
2271    ;; Check whether `message-generate-new-buffers' is a function, 
2272    ;; and if so, call it.
2273    ((message-functionp message-generate-new-buffers)
2274     (funcall message-generate-new-buffers type to group))
2275    ;; Generate a new buffer name The Message Way.
2276    (message-generate-new-buffers
2277     (generate-new-buffer-name
2278      (concat "*" type
2279              (if to
2280                  (concat " to "
2281                          (or (car (mail-extract-address-components to))
2282                              to) "")
2283                "")
2284              (if (and group (not (string= group ""))) (concat " on " group) "")
2285              "*")))
2286    ;; Use standard name.
2287    (t
2288     (format "*%s message*" type))))
2289
2290 (defun message-pop-to-buffer (name)
2291   "Pop to buffer NAME, and warn if it already exists and is modified."
2292   (let ((buffer (get-buffer name)))
2293     (if (and buffer
2294              (buffer-name buffer))
2295         (progn
2296           (set-buffer (pop-to-buffer buffer))
2297           (when (and (buffer-modified-p)
2298                      (not (y-or-n-p
2299                            "Message already being composed; erase? ")))
2300             (error "Message being composed")))
2301       (set-buffer (pop-to-buffer name))))
2302   (erase-buffer)
2303   (message-mode))
2304
2305 (defun message-do-send-housekeeping ()
2306   "Kill old message buffers."
2307   ;; We might have sent this buffer already.  Delete it from the
2308   ;; list of buffers.
2309   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
2310   (while (and message-max-buffers
2311               (>= (length message-buffer-list) message-max-buffers))
2312     ;; Kill the oldest buffer -- unless it has been changed.
2313     (let ((buffer (pop message-buffer-list)))
2314       (when (and (buffer-name buffer)
2315                  (not (buffer-modified-p buffer)))
2316         (kill-buffer buffer))))
2317   ;; Rename the buffer.
2318   (if message-send-rename-function
2319       (funcall message-send-rename-function)
2320     (when (string-match "\\`\\*" (buffer-name))
2321       (rename-buffer 
2322        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
2323   ;; Push the current buffer onto the list.
2324   (when message-max-buffers
2325     (setq message-buffer-list 
2326           (nconc message-buffer-list (list (current-buffer))))))
2327
2328 (defvar mc-modes-alist)
2329 (defun message-setup (headers &optional replybuffer actions)
2330   (when (and (boundp 'mc-modes-alist)
2331              (not (assq 'message-mode mc-modes-alist)))
2332     (push '(message-mode (encrypt . mc-encrypt-message)
2333                          (sign . mc-sign-message))
2334           mc-modes-alist))
2335   (when actions
2336     (setq message-send-actions actions))
2337   (setq message-reply-buffer replybuffer)
2338   (goto-char (point-min))
2339   ;; Insert all the headers.
2340   (mail-header-format 
2341    (let ((h headers)
2342          (alist message-header-format-alist))
2343      (while h
2344        (unless (assq (caar h) message-header-format-alist)
2345          (push (list (caar h)) alist))
2346        (pop h))
2347      alist)
2348    headers)
2349   (delete-region (point) (progn (forward-line -1) (point)))
2350   (when message-default-headers
2351     (insert message-default-headers))
2352   (put-text-property
2353    (point)
2354    (progn
2355      (insert mail-header-separator "\n")
2356      (1- (point)))
2357    'read-only nil)
2358   (forward-line -1)
2359   (when (message-news-p)
2360     (when message-default-news-headers
2361       (insert message-default-news-headers))
2362     (when message-generate-headers-first
2363       (message-generate-headers
2364        (delq 'Lines
2365              (delq 'Subject
2366                    (copy-sequence message-required-news-headers))))))
2367   (when (message-mail-p)
2368     (when message-default-mail-headers
2369       (insert message-default-mail-headers))
2370     (when message-generate-headers-first
2371       (message-generate-headers
2372        (delq 'Lines
2373              (delq 'Subject
2374                    (copy-sequence message-required-mail-headers))))))
2375   (run-hooks 'message-signature-setup-hook)
2376   (message-insert-signature)
2377   (message-set-auto-save-file-name)
2378   (save-restriction
2379     (message-narrow-to-headers)
2380     (run-hooks 'message-header-setup-hook))
2381   (set-buffer-modified-p nil)
2382   (run-hooks 'message-setup-hook)
2383   (message-position-point)
2384   (undo-boundary))
2385
2386 (defun message-set-auto-save-file-name ()
2387   "Associate the message buffer with a file in the drafts directory."
2388   (when message-autosave-directory
2389     (unless (file-exists-p message-autosave-directory)
2390       (make-directory message-autosave-directory t))
2391     (let ((name (make-temp-name
2392                  (concat (file-name-as-directory message-autosave-directory)
2393                          "msg."))))
2394       (setq buffer-auto-save-file-name
2395             (save-excursion
2396               (prog1
2397                   (progn
2398                     (set-buffer (get-buffer-create " *draft tmp*"))
2399                     (setq buffer-file-name name)
2400                     (make-auto-save-file-name))
2401                 (kill-buffer (current-buffer)))))
2402       (clear-visited-file-modtime))))
2403
2404 \f
2405
2406 ;;;
2407 ;;; Commands for interfacing with message
2408 ;;;
2409
2410 ;;;###autoload
2411 (defun message-mail (&optional to subject)
2412   "Start editing a mail message to be sent."
2413   (interactive)
2414   (message-pop-to-buffer (message-buffer-name "mail" to))
2415   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
2416
2417 ;;;###autoload
2418 (defun message-news (&optional newsgroups subject)
2419   "Start editing a news article to be sent."
2420   (interactive)
2421   (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
2422   (message-setup `((Newsgroups . ,(or newsgroups "")) 
2423                    (Subject . ,(or subject "")))))
2424
2425 ;;;###autoload
2426 (defun message-reply (&optional to-address wide ignore-reply-to)
2427   "Start editing a reply to the article in the current buffer."
2428   (interactive)
2429   (let ((cur (current-buffer))
2430         from subject date reply-to to cc
2431         references message-id follow-to 
2432         (inhibit-point-motion-hooks t)
2433         mct never-mct gnus-warning)
2434     (save-restriction
2435       (narrow-to-region
2436        (goto-char (point-min))
2437        (if (search-forward "\n\n" nil t)
2438            (1- (point))
2439          (point-max)))
2440       ;; Allow customizations to have their say.
2441       (if (not wide)
2442           ;; This is a regular reply.
2443           (if (message-functionp message-reply-to-function)
2444               (setq follow-to (funcall message-reply-to-function)))
2445         ;; This is a followup.
2446         (if (message-functionp message-wide-reply-to-function)
2447             (save-excursion
2448               (setq follow-to
2449                     (funcall message-wide-reply-to-function)))))
2450       ;; Find all relevant headers we need.
2451       (setq from (message-fetch-field "from")
2452             date (message-fetch-field "date") 
2453             subject (or (message-fetch-field "subject") "none")
2454             to (message-fetch-field "to")
2455             cc (message-fetch-field "cc")
2456             mct (message-fetch-field "mail-copies-to")
2457             reply-to (unless ignore-reply-to (message-fetch-field "reply-to"))
2458             references (message-fetch-field "references")
2459             message-id (message-fetch-field "message-id"))
2460       ;; Remove any (buggy) Re:'s that are present and make a
2461       ;; proper one.
2462       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
2463         (setq subject (substring subject (match-end 0))))
2464       (setq subject (concat "Re: " subject))
2465
2466       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
2467                  (string-match "<[^>]+>" gnus-warning))
2468         (setq message-id (match-string 0 gnus-warning)))
2469             
2470       ;; Handle special values of Mail-Copies-To.
2471       (when mct
2472         (cond ((equal (downcase mct) "never")
2473                (setq never-mct t)
2474                (setq mct nil))
2475               ((equal (downcase mct) "always")
2476                (setq mct (or reply-to from)))))
2477
2478       (unless follow-to
2479         (if (or (not wide)
2480                 to-address)
2481             (setq follow-to (list (cons 'To (or to-address reply-to from))))
2482           (let (ccalist)
2483             (save-excursion
2484               (message-set-work-buffer)
2485               (unless never-mct
2486                 (insert (or reply-to from "")))
2487               (insert (if (bolp) "" ", ") (or to ""))
2488               (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
2489               (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
2490               ;; Remove addresses that match `rmail-dont-reply-to-names'. 
2491               (insert (prog1 (rmail-dont-reply-to (buffer-string))
2492                         (erase-buffer)))
2493               (goto-char (point-min))
2494               (setq ccalist
2495                     (mapcar
2496                      (lambda (addr)
2497                        (cons (mail-strip-quoted-names addr) addr))
2498                      (message-tokenize-header (buffer-string))))
2499               (let ((s ccalist))
2500                 (while s
2501                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
2502             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
2503             (when ccalist
2504               (push (cons 'Cc
2505                           (mapconcat (lambda (addr) (cdr addr)) ccalist ", "))
2506                     follow-to)))))
2507       (widen))
2508
2509     (message-pop-to-buffer (message-buffer-name
2510                             (if wide "wide reply" "reply") from
2511                             (if wide to-address nil)))
2512
2513     (setq message-reply-headers
2514           (vector 0 subject from date message-id references 0 0 ""))
2515
2516     (message-setup
2517      `((Subject . ,subject)
2518        ,@follow-to 
2519        ,@(if (or references message-id)
2520              `((References . ,(concat (or references "") (and references " ")
2521                                       (or message-id ""))))
2522            nil))
2523      cur)))
2524
2525 ;;;###autoload
2526 (defun message-wide-reply (&optional to-address)
2527   (interactive)
2528   (message-reply to-address t))
2529
2530 ;;;###autoload
2531 (defun message-followup ()
2532   (interactive)
2533   (let ((cur (current-buffer))
2534         from subject date reply-to mct
2535         references message-id follow-to 
2536         (inhibit-point-motion-hooks t)
2537         followup-to distribution newsgroups gnus-warning)
2538     (save-restriction
2539       (narrow-to-region
2540        (goto-char (point-min))
2541        (if (search-forward "\n\n" nil t)
2542            (1- (point))
2543          (point-max)))
2544       (when (message-functionp message-followup-to-function)
2545         (setq follow-to
2546               (funcall message-followup-to-function)))
2547       (setq from (message-fetch-field "from")
2548             date (message-fetch-field "date") 
2549             subject (or (message-fetch-field "subject") "none")
2550             references (message-fetch-field "references")
2551             message-id (message-fetch-field "message-id")
2552             followup-to (message-fetch-field "followup-to")
2553             newsgroups (message-fetch-field "newsgroups")
2554             reply-to (message-fetch-field "reply-to")
2555             distribution (message-fetch-field "distribution")
2556             mct (message-fetch-field "mail-copies-to"))
2557       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
2558                  (string-match "<[^>]+>" gnus-warning))
2559         (setq message-id (match-string 0 gnus-warning)))
2560       ;; Remove bogus distribution.
2561       (and (stringp distribution)
2562            (string-match "world" distribution)
2563            (setq distribution nil))
2564       ;; Remove any (buggy) Re:'s that are present and make a
2565       ;; proper one.
2566       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
2567         (setq subject (substring subject (match-end 0))))
2568       (setq subject (concat "Re: " subject))
2569       (widen))
2570
2571     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
2572
2573     (message-setup
2574      `((Subject . ,subject)
2575        ,@(cond 
2576           (follow-to follow-to)
2577           ((and followup-to message-use-followup-to)
2578            (list
2579             (cond 
2580              ((equal (downcase followup-to) "poster")
2581               (if (or (eq message-use-followup-to 'use)
2582                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
2583 You should normally obey the Followup-To: header.
2584
2585 `Followup-To: poster' sends your response via e-mail instead of news.
2586
2587 A typical situation where `Followup-To: poster' is used is when the poster
2588 does not read the newsgroup, so he wouldn't see any replies sent to it."))
2589                   (cons 'To (or reply-to from ""))
2590                 (cons 'Newsgroups newsgroups)))
2591              (t
2592               (if (or (equal followup-to newsgroups)
2593                       (not (eq message-use-followup-to 'ask))
2594                       (message-y-or-n-p
2595                        (concat "Obey Followup-To: " followup-to "? ") t "\
2596 You should normally obey the Followup-To: header.
2597
2598         `Followup-To: " followup-to "'
2599 directs your response to " (if (string-match "," followup-to)
2600                                "the specified newsgroups"
2601                              "that newsgroup only") ".
2602
2603 If a message is posted to several newsgroups, Followup-To is often
2604 used to direct the following discussion to one newsgroup only,
2605 because discussions that are spread over several newsgroup tend to
2606 be fragmented and very difficult to follow.
2607
2608 Also, some source/announcment newsgroups are not indented for discussion;
2609 responses here are directed to other newsgroups."))
2610                   (cons 'Newsgroups followup-to)
2611                 (cons 'Newsgroups newsgroups))))))
2612           (t
2613            `((Newsgroups . ,newsgroups))))
2614        ,@(and distribution (list (cons 'Distribution distribution)))
2615        (References . ,(concat (or references "") (and references " ")
2616                               (or message-id "")))
2617        ,@(when (and mct
2618                     (not (equal (downcase mct) "never")))
2619            (list (cons 'Cc (if (equal (downcase mct) "always")
2620                                (or reply-to from "")
2621                              mct)))))
2622
2623      cur)
2624
2625     (setq message-reply-headers
2626           (vector 0 subject from date message-id references 0 0 ""))))
2627
2628
2629 ;;;###autoload
2630 (defun message-cancel-news ()
2631   "Cancel an article you posted."
2632   (interactive)
2633   (unless (message-news-p)
2634     (error "This is not a news article; canceling is impossible"))
2635   (when (yes-or-no-p "Do you really want to cancel this article? ")
2636     (let (from newsgroups message-id distribution buf)
2637       (save-excursion
2638         ;; Get header info. from original article.
2639         (save-restriction
2640           (message-narrow-to-head)
2641           (setq from (message-fetch-field "from")
2642                 newsgroups (message-fetch-field "newsgroups")
2643                 message-id (message-fetch-field "message-id")
2644                 distribution (message-fetch-field "distribution")))
2645         ;; Make sure that this article was written by the user.
2646         (unless (string-equal
2647                  (downcase (cadr (mail-extract-address-components from)))
2648                  (downcase (message-make-address)))
2649           (error "This article is not yours"))
2650         ;; Make control message.
2651         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
2652         (buffer-disable-undo (current-buffer))
2653         (erase-buffer)
2654         (insert "Newsgroups: " newsgroups "\n"
2655                 "From: " (message-make-from) "\n"
2656                 "Subject: cmsg cancel " message-id "\n"
2657                 "Control: cancel " message-id "\n"
2658                 (if distribution
2659                     (concat "Distribution: " distribution "\n")
2660                   "")
2661                 mail-header-separator "\n"
2662                 "This is a cancel message from " from ".\n")
2663         (message "Canceling your article...")
2664         (let ((message-syntax-checks 'dont-check-for-anything-just-trust-me))
2665           (funcall message-send-news-function))
2666         (message "Canceling your article...done")
2667         (kill-buffer buf)))))
2668
2669 ;;;###autoload
2670 (defun message-supersede ()
2671   "Start composing a message to supersede the current message.
2672 This is done simply by taking the old article and adding a Supersedes
2673 header line with the old Message-ID."
2674   (interactive)
2675   (let ((cur (current-buffer)))
2676     ;; Check whether the user owns the article that is to be superseded. 
2677     (unless (string-equal
2678              (downcase (cadr (mail-extract-address-components
2679                               (message-fetch-field "from"))))
2680              (downcase (message-make-address)))
2681       (error "This article is not yours"))
2682     ;; Get a normal message buffer.
2683     (message-pop-to-buffer (message-buffer-name "supersede"))
2684     (insert-buffer-substring cur)
2685     (message-narrow-to-head)
2686     ;; Remove unwanted headers.
2687     (when message-ignored-supersedes-headers
2688       (message-remove-header message-ignored-supersedes-headers t))
2689     (goto-char (point-min))
2690     (if (not (re-search-forward "^Message-ID: " nil t))
2691         (error "No Message-ID in this article")
2692       (replace-match "Supersedes: " t t))
2693     (goto-char (point-max))
2694     (insert mail-header-separator)
2695     (widen)
2696     (forward-line 1)))
2697
2698 ;;;###autoload
2699 (defun message-recover ()
2700   "Reread contents of current buffer from its last auto-save file."
2701   (interactive)
2702   (let ((file-name (make-auto-save-file-name)))
2703     (cond ((save-window-excursion
2704              (if (not (eq system-type 'vax-vms))
2705                  (with-output-to-temp-buffer "*Directory*"
2706                    (buffer-disable-undo standard-output)
2707                    (let ((default-directory "/"))
2708                      (call-process
2709                       "ls" nil standard-output nil "-l" file-name))))
2710              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
2711            (let ((buffer-read-only nil))
2712              (erase-buffer)
2713              (insert-file-contents file-name nil)))
2714           (t (error "message-recover cancelled")))))
2715
2716 ;;; Forwarding messages.
2717
2718 (defun message-make-forward-subject ()
2719   "Return a Subject header suitable for the message in the current buffer."
2720   (concat "[" (or (message-fetch-field (if (message-news-p) "newsgroups" "from"))
2721                   "(nowhere)")
2722           "] " (or (message-fetch-field "Subject") "")))
2723
2724 ;;;###autoload
2725 (defun message-forward (&optional news)
2726   "Forward the current message via mail.  
2727 Optional NEWS will use news to forward instead of mail."
2728   (interactive "P")
2729   (let ((cur (current-buffer))
2730         (subject (message-make-forward-subject)))
2731     (if news (message-news nil subject) (message-mail nil subject))
2732     ;; Put point where we want it before inserting the forwarded
2733     ;; message. 
2734     (if message-signature-before-forwarded-message
2735         (goto-char (point-max))
2736       (message-goto-body))
2737     ;; Make sure we're at the start of the line.
2738     (unless (eolp)
2739       (insert "\n"))
2740     ;; Narrow to the area we are to insert.
2741     (narrow-to-region (point) (point))
2742     ;; Insert the separators and the forwarded buffer.
2743     (insert message-forward-start-separator)
2744     (insert-buffer-substring cur)
2745     (goto-char (point-max))
2746     (insert message-forward-end-separator)
2747     (set-text-properties (point-min) (point-max) nil)
2748     ;; Remove all unwanted headers.
2749     (goto-char (point-min))
2750     (forward-line 1)
2751     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
2752                                   (1- (point))
2753                                 (point)))
2754     (goto-char (point-min))
2755     (message-remove-header message-included-forward-headers t nil t)
2756     (widen)
2757     (message-position-point)))
2758
2759 ;;;###autoload
2760 (defun message-resend (address)
2761   "Resend the current article to ADDRESS."
2762   (interactive "sResend message to: ")
2763   (save-excursion
2764     (let ((cur (current-buffer))
2765           beg)
2766       ;; We first set up a normal mail buffer.
2767       (set-buffer (get-buffer-create " *message resend*"))
2768       (buffer-disable-undo (current-buffer))
2769       (erase-buffer)
2770       (message-setup `((To . ,address)))
2771       ;; Insert our usual headers.
2772       (message-generate-headers '(From Date To))
2773       (message-narrow-to-headers)
2774       ;; Rename them all to "Resent-*".
2775       (while (re-search-forward "^[A-Za-z]" nil t)
2776         (forward-char -1)
2777         (insert "Resent-"))
2778       (widen)
2779       (forward-line)
2780       (delete-region (point) (point-max))
2781       (setq beg (point))
2782       ;; Insert the message to be resent.
2783       (insert-buffer-substring cur)
2784       (goto-char (point-min))
2785       (search-forward "\n\n")
2786       (forward-char -1)
2787       (save-restriction
2788         (narrow-to-region beg (point))
2789         (message-remove-header message-ignored-resent-headers t)
2790         (goto-char (point-max)))
2791       (insert mail-header-separator)
2792       ;; Rename all old ("Also-")Resent headers.
2793       (while (re-search-backward "^\\(Also-\\)?Resent-" beg t)
2794         (beginning-of-line)
2795         (insert "Also-"))
2796       ;; Send it.
2797       (message-send-mail)
2798       (kill-buffer (current-buffer)))))
2799
2800 ;;;###autoload
2801 (defun message-bounce ()
2802   "Re-mail the current message.
2803 This only makes sense if the current message is a bounce message than
2804 contains some mail you have written which has been bounced back to
2805 you."
2806   (interactive)
2807   (let ((cur (current-buffer))
2808         boundary)
2809     (message-pop-to-buffer (message-buffer-name "bounce"))
2810     (insert-buffer-substring cur)
2811     (undo-boundary)
2812     (message-narrow-to-head)
2813     (if (and (message-fetch-field "Mime-Version")
2814              (setq boundary (message-fetch-field "Content-Type")))
2815         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
2816             (setq boundary (concat (match-string 1 boundary) " *\n"
2817                                    "Content-Type: message/rfc822"))
2818           (setq boundary nil)))
2819     (widen)
2820     (goto-char (point-min))
2821     (search-forward "\n\n" nil t)
2822     (or (and boundary
2823              (re-search-forward boundary nil t)
2824              (forward-line 2))
2825         (and (re-search-forward message-unsent-separator nil t)
2826              (forward-line 1))
2827         (and (search-forward "\n\n" nil t)
2828              (re-search-forward "^Return-Path:.*\n" nil t)))
2829     ;; We remove everything before the bounced mail.
2830     (delete-region 
2831      (point-min)
2832      (if (re-search-forward "^[^ \n\t]+:" nil t)
2833          (match-beginning 0)
2834        (point)))
2835     (save-restriction
2836       (message-narrow-to-head)
2837       (message-remove-header message-ignored-bounced-headers t)
2838       (goto-char (point-max))
2839       (insert mail-header-separator))
2840     (message-position-point)))
2841
2842 ;;;
2843 ;;; Interactive entry points for new message buffers.
2844 ;;;
2845
2846 ;;;###autoload
2847 (defun message-mail-other-window (&optional to subject)
2848   "Like `message-mail' command, but display mail buffer in another window."
2849   (interactive)
2850   (let ((pop-up-windows t)
2851         (special-display-buffer-names nil)
2852         (special-display-regexps nil)
2853         (same-window-buffer-names nil)
2854         (same-window-regexps nil))
2855     (message-pop-to-buffer (message-buffer-name "mail" to)))
2856   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
2857
2858 ;;;###autoload
2859 (defun message-mail-other-frame (&optional to subject)
2860   "Like `message-mail' command, but display mail buffer in another frame."
2861   (interactive)
2862   (let ((pop-up-frames t)
2863         (special-display-buffer-names nil)
2864         (special-display-regexps nil)
2865         (same-window-buffer-names nil)
2866         (same-window-regexps nil))
2867     (message-pop-to-buffer (message-buffer-name "mail" to)))
2868   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
2869
2870 ;;;###autoload
2871 (defun message-news-other-window (&optional newsgroups subject)
2872   "Start editing a news article to be sent."
2873   (interactive)
2874   (let ((pop-up-windows t)
2875         (special-display-buffer-names nil)
2876         (special-display-regexps nil)
2877         (same-window-buffer-names nil)
2878         (same-window-regexps nil))
2879     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
2880   (message-setup `((Newsgroups . ,(or newsgroups "")) 
2881                    (Subject . ,(or subject "")))))
2882
2883 ;;;###autoload
2884 (defun message-news-other-frame (&optional newsgroups subject)
2885   "Start editing a news article to be sent."
2886   (interactive)
2887   (let ((pop-up-frames t)
2888         (special-display-buffer-names nil)
2889         (special-display-regexps nil)
2890         (same-window-buffer-names nil)
2891         (same-window-regexps nil))
2892     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
2893   (message-setup `((Newsgroups . ,(or newsgroups "")) 
2894                    (Subject . ,(or subject "")))))
2895
2896 ;;; underline.el
2897
2898 ;; This code should be moved to underline.el (from which it is stolen). 
2899
2900 ;;;###autoload
2901 (defun bold-region (start end)
2902   "Bold all nonblank characters in the region.
2903 Works by overstriking characters.
2904 Called from program, takes two arguments START and END
2905 which specify the range to operate on."
2906   (interactive "r")
2907   (save-excursion
2908    (let ((end1 (make-marker)))
2909      (move-marker end1 (max start end))
2910      (goto-char (min start end))
2911      (while (< (point) end1)
2912        (or (looking-at "[_\^@- ]")
2913            (insert (following-char) "\b"))
2914        (forward-char 1)))))
2915
2916 ;;;###autoload
2917 (defun unbold-region (start end)
2918   "Remove all boldness (overstruck characters) in the region.
2919 Called from program, takes two arguments START and END
2920 which specify the range to operate on."
2921   (interactive "r")
2922   (save-excursion
2923    (let ((end1 (make-marker)))
2924      (move-marker end1 (max start end))
2925      (goto-char (min start end)) 
2926      (while (re-search-forward "\b" end1 t)
2927        (if (eq (following-char) (char-after (- (point) 2)))
2928            (delete-char -2))))))
2929
2930 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
2931
2932 ;; Support for toolbar
2933 (when (string-match "XEmacs\\|Lucid" emacs-version)
2934   (require 'messagexmas))
2935
2936 ;;; Group name completion.
2937
2938 (defvar message-newgroups-header-regexp
2939   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\):"
2940   "Regexp that match headers that lists groups.")
2941
2942 (defun message-tab ()
2943   "Expand group names in Newsgroups and Followup-To headers.
2944 Do a `tab-to-tab-stop' if not in those headers."
2945   (interactive)
2946   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
2947         (mail-abbrev-in-expansion-header-p))
2948       (message-expand-group)
2949     (tab-to-tab-stop)))
2950
2951 (defvar gnus-active-hashtb)
2952 (defun message-expand-group ()
2953   (let* ((b (save-excursion (skip-chars-backward "^, :\t\n") (point)))
2954          (completion-ignore-case t)
2955          (string (buffer-substring b (point)))
2956          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
2957          (completions (all-completions string hashtb))
2958          (cur (current-buffer))
2959          comp)
2960     (delete-region b (point))
2961     (cond 
2962      ((= (length completions) 1)
2963       (if (string= (car completions) string)
2964           (progn
2965             (insert string)
2966             (message "Only matching group"))
2967         (insert (car completions))))
2968      ((and (setq comp (try-completion string hashtb))
2969            (not (string= comp string)))
2970       (insert comp))
2971      (t
2972       (insert string)
2973       (if (not comp)
2974           (message "No matching groups")
2975         (pop-to-buffer "*Completions*")
2976         (buffer-disable-undo (current-buffer))
2977         (let ((buffer-read-only nil))
2978           (erase-buffer)
2979           (let ((standard-output (current-buffer)))
2980             (display-completion-list (sort completions 'string<)))
2981           (goto-char (point-min))
2982           (pop-to-buffer cur)))))))
2983
2984 ;;; Help stuff.
2985
2986 (defmacro message-y-or-n-p (question show &rest text)
2987   "Ask QUESTION, displaying the rest of the arguments in a temp. buffer if SHOW"
2988   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
2989
2990 (defun message-talkative-question (ask question show &rest text)
2991   "Call FUNCTION with argument QUESTION, displaying the rest of the arguments in a temporary buffer if SHOW.  
2992 The following arguments may contain lists of values."
2993   (if (and show
2994            (setq text (message-flatten-list text)))
2995       (save-window-excursion
2996         (save-excursion
2997           (with-output-to-temp-buffer " *MESSAGE information message*"
2998             (set-buffer " *MESSAGE information message*")
2999             (mapcar 'princ text)
3000             (goto-char (point-min))))
3001         (funcall ask question))
3002     (funcall ask question)))
3003
3004 (defun message-flatten-list (&rest list)
3005   (message-flatten-list-1 list))
3006
3007 (defun message-flatten-list-1 (list)
3008   (cond ((consp list) 
3009          (apply 'append (mapcar 'message-flatten-list-1 list)))
3010         (list
3011          (list list))))
3012
3013 (run-hooks 'message-load-hook)
3014
3015 (provide 'message)
3016
3017 ;;; message.el ends here