(message-dont-send): Use `message-delete-frame'.
[elisp/gnus.git-] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2 ;; Copyright (C) 1996,97,98 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;;         MORIOKA Tomohiko <morioka@jaist.ac.jp>
6 ;;         Shuhei KOBAYASHI <shuhei-k@jaist.ac.jp>
7 ;;         Keiichi Suzuki <kei-suzu@mail.wbs.ne.jp>
8 ;; Keywords: mail, news, MIME
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26
27 ;;; Commentary:
28
29 ;; This mode provides mail-sending facilities from within Emacs.  It
30 ;; consists mainly of large chunks of code from the sendmail.el,
31 ;; gnus-msg.el and rnewspost.el files.
32
33 ;;; Code:
34
35 (eval-when-compile
36   (require 'cl)
37   (require 'smtp)
38   )
39
40 (require 'mailheader)
41 (require 'nnheader)
42 (require 'timezone)
43 (require 'easymenu)
44 (require 'custom)
45 (if (string-match "XEmacs\\|Lucid" emacs-version)
46     (require 'mail-abbrevs)
47   (require 'mailabbrev))
48 (require 'mime-edit)
49
50 (defgroup message '((user-mail-address custom-variable)
51                     (user-full-name custom-variable))
52   "Mail and news message composing."
53   :link '(custom-manual "(message)Top")
54   :group 'mail
55   :group 'news)
56
57 (put 'user-mail-address 'custom-type 'string)
58 (put 'user-full-name 'custom-type 'string)
59
60 (defgroup message-various nil
61   "Various Message Variables"
62   :link '(custom-manual "(message)Various Message Variables")
63   :group 'message)
64
65 (defgroup message-buffers nil
66   "Message Buffers"
67   :link '(custom-manual "(message)Message Buffers")
68   :group 'message)
69
70 (defgroup message-sending nil
71   "Message Sending"
72   :link '(custom-manual "(message)Sending Variables")
73   :group 'message)
74
75 (defgroup message-interface nil
76   "Message Interface"
77   :link '(custom-manual "(message)Interface")
78   :group 'message)
79
80 (defgroup message-forwarding nil
81   "Message Forwarding"
82   :link '(custom-manual "(message)Forwarding")
83   :group 'message-interface)
84
85 (defgroup message-insertion nil
86   "Message Insertion"
87   :link '(custom-manual "(message)Insertion")
88   :group 'message)
89
90 (defgroup message-headers nil
91   "Message Headers"
92   :link '(custom-manual "(message)Message Headers")
93   :group 'message)
94
95 (defgroup message-news nil
96   "Composing News Messages"
97   :group 'message)
98
99 (defgroup message-mail nil
100   "Composing Mail Messages"
101   :group 'message)
102
103 (defgroup message-faces nil
104   "Faces used for message composing."
105   :group 'message
106   :group 'faces)
107
108 (defgroup message-frames nil
109   "Message frames"
110   :group 'message)
111
112 (defcustom message-directory "~/Mail/"
113   "*Directory from which all other mail file variables are derived."
114   :group 'message-various
115   :type 'directory)
116
117 (defcustom message-max-buffers 10
118   "*How many buffers to keep before starting to kill them off."
119   :group 'message-buffers
120   :type 'integer)
121
122 (defcustom message-send-rename-function nil
123   "Function called to rename the buffer after sending it."
124   :group 'message-buffers
125   :type 'function)
126
127 (defcustom message-fcc-handler-function 'message-output
128   "*A function called to save outgoing articles.
129 This function will be called with the name of the file to store the
130 article in.  The default function is `message-output' which saves in Unix
131 mailbox format."
132   :type '(radio (function-item message-output)
133                 (function :tag "Other"))
134   :group 'message-sending)
135
136 (defcustom message-encode-function 'message-maybe-encode
137   "*A function called to encode messages."
138   :group 'message-sending
139   :type 'function)
140
141 (defcustom message-8bit-encoding-list '(8bit binary)
142   "*8bit encoding type in Content-Transfer-Encoding field."
143   :group 'message-sending
144   :type '(repeat (symbol :tag "Type")))
145
146 (defcustom message-courtesy-message
147   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
148   "*This is inserted at the start of a mailed copy of a posted message.
149 If the string contains the format spec \"%s\", the Newsgroups
150 the article has been posted to will be inserted there.
151 If this variable is nil, no such courtesy message will be added."
152   :group 'message-sending
153   :type 'string)
154
155 (defcustom message-ignored-bounced-headers "^\\(Received\\|Return-Path\\):"
156   "*Regexp that matches headers to be removed in resent bounced mail."
157   :group 'message-interface
158   :type 'regexp)
159
160 (defcustom message-bounce-setup-function 'message-bounce-setup-for-mime-edit
161   "Function to setup a re-sending bounced message."
162   :group 'message-sending
163   :type 'function)
164
165 ;;;###autoload
166 (defcustom message-from-style 'default
167   "*Specifies how \"From\" headers look.
168
169 If `nil', they contain just the return address like:
170         king@grassland.com
171 If `parens', they look like:
172         king@grassland.com (Elvis Parsley)
173 If `angles', they look like:
174         Elvis Parsley <king@grassland.com>
175
176 Otherwise, most addresses look like `angles', but they look like
177 `parens' if `angles' would need quoting and `parens' would not."
178   :type '(choice (const :tag "simple" nil)
179                  (const parens)
180                  (const angles)
181                  (const default))
182   :group 'message-headers)
183
184 (defcustom message-syntax-checks nil
185   ; Guess this one shouldn't be easy to customize...
186   "*Controls what syntax checks should not be performed on outgoing posts.
187 To disable checking of long signatures, for instance, add
188  `(signature . disabled)' to this list.
189
190 Don't touch this variable unless you really know what you're doing.
191
192 Checks include subject-cmsg multiple-headers sendsys message-id from
193 long-lines control-chars size new-text redirected-followup signature
194 approved sender empty empty-headers message-id from subject
195 shorten-followup-to existing-newsgroups buffer-file-name unchanged."
196   :group 'message-news)
197
198 (defcustom message-required-news-headers
199   '(From Newsgroups Subject Date Message-ID
200          (optional . Organization) Lines
201          (optional . User-Agent))
202   "*Headers to be generated or prompted for when posting an article.
203 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
204 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
205 User-Agent are optional.  If don't you want message to insert some
206 header, remove it from this list."
207   :group 'message-news
208   :group 'message-headers
209   :type '(repeat sexp))
210
211 (defcustom message-required-mail-headers
212   '(From Subject Date (optional . In-Reply-To) Message-ID Lines
213          (optional . User-Agent))
214   "*Headers to be generated or prompted for when mailing a message.
215 RFC822 required that From, Date, To, Subject and Message-ID be
216 included.  Organization, Lines and User-Agent are optional."
217   :group 'message-mail
218   :group 'message-headers
219   :type '(repeat sexp))
220
221 (defcustom message-deletable-headers '(Message-ID Date Lines)
222   "Headers to be deleted if they already exist and were generated by message previously."
223   :group 'message-headers
224   :type 'sexp)
225
226 (defcustom message-ignored-news-headers
227   "^NNTP-Posting-Host:\\|^Xref:\\|^[BGF]cc:\\|^Resent-Fcc:"
228   "*Regexp of headers to be removed unconditionally before posting."
229   :group 'message-news
230   :group 'message-headers
231   :type 'regexp)
232
233 (defcustom message-ignored-mail-headers "^[GF]cc:\\|^Resent-Fcc:\\|^Xref:"
234   "*Regexp of headers to be removed unconditionally before mailing."
235   :group 'message-mail
236   :group 'message-headers
237   :type 'regexp)
238
239 (defcustom message-ignored-supersedes-headers "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|^X-Trace:\\|^X-Complaints-To:\\|Return-Path:\\|^Supersedes:\\|^X-Trace:\\|^X-Complaints-To:"
240   "*Header lines matching this regexp will be deleted before posting.
241 It's best to delete old Path and Date headers before posting to avoid
242 any confusion."
243   :group 'message-interface
244   :type 'regexp)
245
246 (defcustom message-subject-re-regexp "^[ \t]*\\([Rr][Ee]:[ \t]*\\)*[ \t]*"
247   "*Regexp matching \"Re: \" in the subject line."
248   :group 'message-various
249   :type 'regexp)
250
251 ;;;###autoload
252 (defcustom message-signature-separator "^-- *$"
253   "Regexp matching the signature separator."
254   :type 'regexp
255   :group 'message-various)
256
257 (defcustom message-elide-elipsis "\n[...]\n\n"
258   "*The string which is inserted for elided text."
259   :type 'string
260   :group 'message-various)
261
262 (defcustom message-interactive nil
263   "Non-nil means when sending a message wait for and display errors.
264 nil means let mailer mail back a message to report errors."
265   :group 'message-sending
266   :group 'message-mail
267   :type 'boolean)
268
269 (defcustom message-generate-new-buffers t
270   "*Non-nil means that a new message buffer will be created whenever `message-setup' is called.
271 If this is a function, call that function with three parameters:  The type,
272 the to address and the group name.  (Any of these may be nil.)  The function
273 should return the new buffer name."
274   :group 'message-buffers
275   :type '(choice (const :tag "off" nil)
276                  (const :tag "on" t)
277                  (function fun)))
278
279 (defcustom message-kill-buffer-on-exit nil
280   "*Non-nil means that the message buffer will be killed after sending a message."
281   :group 'message-buffers
282   :type 'boolean)
283
284 (defcustom message-kill-buffer-query-function 'yes-or-no-p
285   "*A function called to query the user whether to kill buffer anyway or not.
286 If it is t, the buffer will be killed peremptorily."
287   :type '(radio (function-item yes-or-no-p)
288                 (function-item y-or-n-p)
289                 (function-item nnheader-Y-or-n-p)
290                 (function :tag "Other" t))
291   :group 'message-buffers)
292
293 (defvar gnus-local-organization)
294 (defcustom message-user-organization
295   (or (and (boundp 'gnus-local-organization)
296            (stringp gnus-local-organization)
297            gnus-local-organization)
298       (getenv "ORGANIZATION")
299       t)
300   "*String to be used as an Organization header.
301 If t, use `message-user-organization-file'."
302   :group 'message-headers
303   :type '(choice string
304                  (const :tag "consult file" t)))
305
306 ;;;###autoload
307 (defcustom message-user-organization-file "/usr/lib/news/organization"
308   "*Local news organization file."
309   :type 'file
310   :group 'message-headers)
311
312 (defcustom message-forward-start-separator
313   (concat (mime-make-tag "message" "rfc822") "\n")
314   "*Delimiter inserted before forwarded messages."
315   :group 'message-forwarding
316   :type 'string)
317
318 (defcustom message-forward-end-separator
319   (concat (mime-make-tag "text" "plain") "\n")
320   "*Delimiter inserted after forwarded messages."
321   :group 'message-forwarding
322   :type 'string)
323
324 (defcustom message-signature-before-forwarded-message t
325   "*If non-nil, put the signature before any included forwarded message."
326   :group 'message-forwarding
327   :type 'boolean)
328
329 (defcustom message-included-forward-headers
330   "^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:\\|^Content-Transfer-Encoding:\\|^Content-Type:\\|^MIME-Version:"
331   "*Regexp matching headers to be included in forwarded messages."
332   :group 'message-forwarding
333   :type 'regexp)
334
335 (defcustom message-make-forward-subject-function 
336   'message-forward-subject-author-subject
337  "*A list of functions that are called to generate a subject header for forwarded messages.
338 The subject generated by the previous function is passed into each
339 successive function.
340
341 The provided functions are:
342
343 * message-forward-subject-author-subject (Source of article (author or
344       newsgroup)), in brackets followed by the subject
345 * message-forward-subject-fwd (Subject of article with 'Fwd:' prepended
346       to it."
347  :group 'message-forwarding
348  :type '(radio (function-item message-forward-subject-author-subject)
349                (function-item message-forward-subject-fwd)))
350
351 (defcustom message-wash-forwarded-subjects nil
352   "*If non-nil, try to remove as much old cruft as possible from the subject of messages before generating the new subject of a forward."
353   :group 'message-forwarding
354   :type 'boolean)
355
356 (defcustom message-ignored-resent-headers "^Return-receipt"
357   "*All headers that match this regexp will be deleted when resending a message."
358   :group 'message-interface
359   :type 'regexp)
360
361 (defcustom message-ignored-cited-headers "."
362   "*Delete these headers from the messages you yank."
363   :group 'message-insertion
364   :type 'regexp)
365
366 (defcustom message-cancel-message "I am canceling my own article."
367   "Message to be inserted in the cancel message."
368   :group 'message-interface
369   :type 'string)
370
371 ;; Useful to set in site-init.el
372 ;;;###autoload
373 (defcustom message-send-mail-function 'message-send-mail-with-sendmail
374   "Function to call to send the current buffer as mail.
375 The headers should be delimited by a line whose contents match the
376 variable `mail-header-separator'.
377
378 Legal values include `message-send-mail-with-sendmail' (the default),
379 `message-send-mail-with-mh', `message-send-mail-with-qmail' and
380 `message-send-mail-with-smtp'."
381   :type '(radio (function-item message-send-mail-with-sendmail)
382                 (function-item message-send-mail-with-mh)
383                 (function-item message-send-mail-with-qmail)
384                 (function-item message-send-mail-with-smtp)
385                 (function :tag "Other"))
386   :group 'message-sending
387   :group 'message-mail)
388
389 ;; 1997-09-29 by MORIOKA Tomohiko
390 (defcustom message-send-news-function 'message-send-news-with-gnus
391   "Function to call to send the current buffer as news.
392 The headers should be delimited by a line whose contents match the
393 variable `mail-header-separator'."
394   :group 'message-sending
395   :group 'message-news
396   :type 'function)
397
398 (defcustom message-reply-to-function nil
399   "Function that should return a list of headers.
400 This function should pick out addresses from the To, Cc, and From headers
401 and respond with new To and Cc headers."
402   :group 'message-interface
403   :type 'function)
404
405 (defcustom message-wide-reply-to-function nil
406   "Function that should return a list of headers.
407 This function should pick out addresses from the To, Cc, and From headers
408 and respond with new To and Cc headers."
409   :group 'message-interface
410   :type 'function)
411
412 (defcustom message-followup-to-function nil
413   "Function that should return a list of headers.
414 This function should pick out addresses from the To, Cc, and From headers
415 and respond with new To and Cc headers."
416   :group 'message-interface
417   :type 'function)
418
419 (defcustom message-use-followup-to 'ask
420   "*Specifies what to do with Followup-To header.
421 If nil, always ignore the header.  If it is t, use its value, but
422 query before using the \"poster\" value.  If it is the symbol `ask',
423 always query the user whether to use the value.  If it is the symbol
424 `use', always use the value."
425   :group 'message-interface
426   :type '(choice (const :tag "ignore" nil)
427                  (const use)
428                  (const ask)))
429
430 ;; stuff relating to broken sendmail in MMDF
431 (defcustom message-sendmail-f-is-evil nil
432   "*Non-nil means that \"-f username\" should not be added to the sendmail
433 command line, because it is even more evil than leaving it out."
434   :group 'message-sending
435   :type 'boolean)
436
437 ;; qmail-related stuff
438 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
439   "Location of the qmail-inject program."
440   :group 'message-sending
441   :type 'file)
442
443 (defcustom message-qmail-inject-args nil
444   "Arguments passed to qmail-inject programs.
445 This should be a list of strings, one string for each argument.
446
447 For e.g., if you wish to set the envelope sender address so that bounces
448 go to the right place or to deal with listserv's usage of that address, you
449 might set this variable to '(\"-f\" \"you@some.where\")."
450   :group 'message-sending
451   :type '(repeat string))
452
453 (defvar gnus-post-method)
454 (defvar gnus-select-method)
455 (defcustom message-post-method
456   (cond ((and (boundp 'gnus-post-method)
457               (listp gnus-post-method)
458               gnus-post-method)
459          gnus-post-method)
460         ((boundp 'gnus-select-method)
461          gnus-select-method)
462         (t '(nnspool "")))
463   "*Method used to post news.
464 Note that when posting from inside Gnus, for instance, this
465 variable isn't used."
466   :group 'message-news
467   :group 'message-sending
468   ;; This should be the `gnus-select-method' widget, but that might
469   ;; create a dependence to `gnus.el'.
470   :type 'sexp)
471
472 (defcustom message-generate-headers-first nil
473   "*If non-nil, generate all possible headers before composing."
474   :group 'message-headers
475   :type 'boolean)
476
477 (defcustom message-setup-hook
478   '(message-maybe-setup-default-charset turn-on-mime-edit)
479   "Normal hook, run each time a new outgoing message is initialized.
480 The function `message-setup' runs this hook."
481   :group 'message-various
482   :type 'hook)
483
484 (defcustom message-signature-setup-hook nil
485   "Normal hook, run each time a new outgoing message is initialized.
486 It is run after the headers have been inserted and before
487 the signature is inserted."
488   :group 'message-various
489   :type 'hook)
490
491 (defcustom message-bounce-setup-hook nil
492   "Normal hook, run each time a a re-sending bounced message is initialized.
493 The function `message-bounce' runs this hook."
494   :group 'message-various
495   :type 'hook)
496
497 (defcustom message-mode-hook nil
498   "Hook run in message mode buffers."
499   :group 'message-various
500   :type 'hook)
501
502 (defcustom message-header-hook '(eword-encode-header)
503   "Hook run in a message mode buffer narrowed to the headers."
504   :group 'message-various
505   :type 'hook)
506
507 (defcustom message-header-setup-hook nil
508   "Hook called narrowed to the headers when setting up a message buffer."
509   :group 'message-various
510   :type 'hook)
511
512 ;;;###autoload
513 (defcustom message-citation-line-function 'message-insert-citation-line
514   "*Function called to insert the \"Whomever writes:\" line."
515   :type 'function
516   :group 'message-insertion)
517
518 ;;;###autoload
519 (defcustom message-yank-prefix "> "
520   "*Prefix inserted on the lines of yanked messages.
521 nil means use indentation."
522   :type 'string
523   :group 'message-insertion)
524
525 (defcustom message-indentation-spaces 3
526   "*Number of spaces to insert at the beginning of each cited line.
527 Used by `message-yank-original' via `message-yank-cite'."
528   :group 'message-insertion
529   :type 'integer)
530
531 ;;;###autoload
532 (defcustom message-cite-function 'message-cite-original
533   "*Function for citing an original message.
534 Predefined functions include `message-cite-original' and
535 `message-cite-original-without-signature'.
536 Note that `message-cite-original' uses `mail-citation-hook' if that is non-nil."
537   :type '(radio (function-item message-cite-original)
538                 (function-item sc-cite-original)
539                 (function :tag "Other"))
540   :group 'message-insertion)
541
542 ;;;###autoload
543 (defcustom message-indent-citation-function 'message-indent-citation
544   "*Function for modifying a citation just inserted in the mail buffer.
545 This can also be a list of functions.  Each function can find the
546 citation between (point) and (mark t).  And each function should leave
547 point and mark around the citation text as modified."
548   :type 'function
549   :group 'message-insertion)
550
551 (defvar message-abbrevs-loaded nil)
552
553 ;;;###autoload
554 (defcustom message-signature t
555   "*String to be inserted at the end of the message buffer.
556 If t, the `message-signature-file' file will be inserted instead.
557 If a function, the result from the function will be used instead.
558 If a form, the result from the form will be used instead."
559   :type 'sexp
560   :group 'message-insertion)
561
562 ;;;###autoload
563 (defcustom message-signature-file "~/.signature"
564   "*File containing the text inserted at end of message buffer."
565   :type 'file
566   :group 'message-insertion)
567
568 (defcustom message-distribution-function nil
569   "*Function called to return a Distribution header."
570   :group 'message-news
571   :group 'message-headers
572   :type 'function)
573
574 (defcustom message-expires 14
575   "Number of days before your article expires."
576   :group 'message-news
577   :group 'message-headers
578   :link '(custom-manual "(message)News Headers")
579   :type 'integer)
580
581 (defcustom message-user-path nil
582   "If nil, use the NNTP server name in the Path header.
583 If stringp, use this; if non-nil, use no host name (user name only)."
584   :group 'message-news
585   :group 'message-headers
586   :link '(custom-manual "(message)News Headers")
587   :type '(choice (const :tag "nntp" nil)
588                  (string :tag "name")
589                  (sexp :tag "none" :format "%t" t)))
590
591 (defvar message-reply-buffer nil)
592 (defvar message-reply-headers nil)
593 (defvar message-newsreader nil)
594 (defvar message-mailer nil)
595 (defvar message-sent-message-via nil)
596 (defvar message-checksum nil)
597 (defvar message-send-actions nil
598   "A list of actions to be performed upon successful sending of a message.")
599 (defvar message-exit-actions nil
600   "A list of actions to be performed upon exiting after sending a message.")
601 (defvar message-kill-actions nil
602   "A list of actions to be performed before killing a message buffer.")
603 (defvar message-postpone-actions nil
604   "A list of actions to be performed after postponing a message.")
605 (defvar message-original-frame nil)
606 (defvar message-parameter-alist nil)
607 (defvar message-startup-parameter-alist nil)
608
609 (define-widget 'message-header-lines 'text
610   "All header lines must be LFD terminated."
611   :format "%t:%n%v"
612   :valid-regexp "^\\'"
613   :error "All header lines must be newline terminated")
614
615 (defcustom message-default-headers ""
616   "*A string containing header lines to be inserted in outgoing messages.
617 It is inserted before you edit the message, so you can edit or delete
618 these lines."
619   :group 'message-headers
620   :type 'message-header-lines)
621
622 (defcustom message-default-mail-headers ""
623   "*A string of header lines to be inserted in outgoing mails."
624   :group 'message-headers
625   :group 'message-mail
626   :type 'message-header-lines)
627
628 (defcustom message-default-news-headers ""
629   "*A string of header lines to be inserted in outgoing news
630 articles."
631   :group 'message-headers
632   :group 'message-news
633   :type 'message-header-lines)
634
635 ;; Note: could use /usr/ucb/mail instead of sendmail;
636 ;; options -t, and -v if not interactive.
637 (defcustom message-mailer-swallows-blank-line
638   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)"
639                          system-configuration)
640            (file-readable-p "/etc/sendmail.cf")
641            (let ((buffer (get-buffer-create " *temp*")))
642              (unwind-protect
643                  (save-excursion
644                    (set-buffer buffer)
645                    (insert-file-contents "/etc/sendmail.cf")
646                    (goto-char (point-min))
647                    (let ((case-fold-search nil))
648                      (re-search-forward "^OR\\>" nil t)))
649                (kill-buffer buffer))))
650       ;; According to RFC822, "The field-name must be composed of printable
651       ;; ASCII characters (i. e., characters that have decimal values between
652       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
653       ;; space, or colon.
654       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
655   "*Set this non-nil if the system's mailer runs the header and body together.
656 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
657 The value should be an expression to test whether the problem will
658 actually occur."
659   :group 'message-sending
660   :type 'sexp)
661
662 ;;; XXX: This symbol is overloaded!  See below.
663 (defvar message-user-agent nil
664   "String of the form of PRODUCT/VERSION.  Used for User-Agent header field.")
665
666 ;; Ignore errors in case this is used in Emacs 19.
667 ;; Don't use ignore-errors because this is copied into loaddefs.el.
668 ;;;###autoload
669 (condition-case nil
670     (define-mail-user-agent 'message-user-agent
671       'message-mail 'message-send-and-exit
672       'message-kill-buffer 'message-send-hook)
673   (error nil))
674
675 (defvar message-mh-deletable-headers '(Message-ID Date Lines Sender)
676   "If non-nil, delete the deletable headers before feeding to mh.")
677
678 (defvar message-send-method-alist
679   '((news message-news-p message-send-via-news)
680     (mail message-mail-p message-send-via-mail))
681   "Alist of ways to send outgoing messages.
682 Each element has the form
683
684   \(TYPE PREDICATE FUNCTION)
685
686 where TYPE is a symbol that names the method; PREDICATE is a function
687 called without any parameters to determine whether the message is
688 a message of type TYPE; and FUNCTION is a function to be called if
689 PREDICATE returns non-nil.  FUNCTION is called with one parameter --
690 the prefix.")
691
692 (defvar message-mail-alias-type 'abbrev
693   "*What alias expansion type to use in Message buffers.
694 The default is `abbrev', which uses mailabbrev.  nil switches
695 mail aliases off.")
696
697 (defcustom message-autosave-directory
698   (nnheader-concat message-directory "drafts/")
699   "*Directory where Message autosaves buffers if Gnus isn't running.
700 If nil, Message won't autosave."
701   :group 'message-buffers
702   :type 'directory)
703
704 ;;; Internal variables.
705 ;;; Well, not really internal.
706
707 (defvar message-mode-syntax-table
708   (let ((table (copy-syntax-table text-mode-syntax-table)))
709     (modify-syntax-entry ?% ". " table)
710     table)
711   "Syntax table used while in Message mode.")
712
713 (defvar message-mode-abbrev-table text-mode-abbrev-table
714   "Abbrev table used in Message mode buffers.
715 Defaults to `text-mode-abbrev-table'.")
716 (defgroup message-headers nil
717   "Message headers."
718   :link '(custom-manual "(message)Variables")
719   :group 'message)
720
721 (defface message-header-to-face
722   '((((class color)
723       (background dark))
724      (:foreground "green2" :bold t))
725     (((class color)
726       (background light))
727      (:foreground "MidnightBlue" :bold t))
728     (t
729      (:bold t :italic t)))
730   "Face used for displaying From headers."
731   :group 'message-faces)
732
733 (defface message-header-cc-face
734   '((((class color)
735       (background dark))
736      (:foreground "green4" :bold t))
737     (((class color)
738       (background light))
739      (:foreground "MidnightBlue"))
740     (t
741      (:bold t)))
742   "Face used for displaying Cc headers."
743   :group 'message-faces)
744
745 (defface message-header-subject-face
746   '((((class color)
747       (background dark))
748      (:foreground "green3"))
749     (((class color)
750       (background light))
751      (:foreground "navy blue" :bold t))
752     (t
753      (:bold t)))
754   "Face used for displaying subject headers."
755   :group 'message-faces)
756
757 (defface message-header-newsgroups-face
758   '((((class color)
759       (background dark))
760      (:foreground "yellow" :bold t :italic t))
761     (((class color)
762       (background light))
763      (:foreground "blue4" :bold t :italic t))
764     (t
765      (:bold t :italic t)))
766   "Face used for displaying newsgroups headers."
767   :group 'message-faces)
768
769 (defface message-header-other-face
770   '((((class color)
771       (background dark))
772      (:foreground "#b00000"))
773     (((class color)
774       (background light))
775      (:foreground "steel blue"))
776     (t
777      (:bold t :italic t)))
778   "Face used for displaying newsgroups headers."
779   :group 'message-faces)
780
781 (defface message-header-name-face
782   '((((class color)
783       (background dark))
784      (:foreground "DarkGreen"))
785     (((class color)
786       (background light))
787      (:foreground "cornflower blue"))
788     (t
789      (:bold t)))
790   "Face used for displaying header names."
791   :group 'message-faces)
792
793 (defface message-header-xheader-face
794   '((((class color)
795       (background dark))
796      (:foreground "blue"))
797     (((class color)
798       (background light))
799      (:foreground "blue"))
800     (t
801      (:bold t)))
802   "Face used for displaying X-Header headers."
803   :group 'message-faces)
804
805 (defface message-separator-face
806   '((((class color)
807       (background dark))
808      (:foreground "blue3"))
809     (((class color)
810       (background light))
811      (:foreground "brown"))
812     (t
813      (:bold t)))
814   "Face used for displaying the separator."
815   :group 'message-faces)
816
817 (defface message-cited-text-face
818   '((((class color)
819       (background dark))
820      (:foreground "red"))
821     (((class color)
822       (background light))
823      (:foreground "red"))
824     (t
825      (:bold t)))
826   "Face used for displaying cited text names."
827   :group 'message-faces)
828
829 (defvar message-font-lock-keywords
830   (let* ((cite-prefix "A-Za-z")
831          (cite-suffix (concat cite-prefix "0-9_.@-"))
832          (content "[ \t]*\\(.+\\(\n[ \t].*\\)*\\)"))
833     `((,(concat "^\\([Tt]o:\\)" content)
834        (1 'message-header-name-face)
835        (2 'message-header-to-face nil t))
836       (,(concat "^\\(^[GBF]?[Cc][Cc]:\\|^[Rr]eply-[Tt]o:\\)" content)
837        (1 'message-header-name-face)
838        (2 'message-header-cc-face nil t))
839       (,(concat "^\\([Ss]ubject:\\)" content)
840        (1 'message-header-name-face)
841        (2 'message-header-subject-face nil t))
842       (,(concat "^\\([Nn]ewsgroups:\\|Followup-[Tt]o:\\)" content)
843        (1 'message-header-name-face)
844        (2 'message-header-newsgroups-face nil t))
845       (,(concat "^\\([A-Z][^: \n\t]+:\\)" content)
846        (1 'message-header-name-face)
847        (2 'message-header-other-face nil t))
848       (,(concat "^\\(X-[A-Za-z0-9-]+\\|In-Reply-To\\):" content)
849        (1 'message-header-name-face)
850        (2 'message-header-name-face))
851       ,@(if (and mail-header-separator
852                  (not (equal mail-header-separator "")))
853             `((,(concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
854                1 'message-separator-face))
855           nil)
856       (,(concat "^[ \t]*"
857                 "\\([" cite-prefix "]+[" cite-suffix "]*\\)?"
858                 "[:>|}].*")
859        (0 'message-cited-text-face))))
860   "Additional expressions to highlight in Message mode.")
861
862 ;; XEmacs does it like this.  For Emacs, we have to set the
863 ;; `font-lock-defaults' buffer-local variable.
864 (put 'message-mode 'font-lock-defaults '(message-font-lock-keywords t))
865
866 (defvar message-face-alist
867   '((bold . bold-region)
868     (underline . underline-region)
869     (default . (lambda (b e)
870                  (unbold-region b e)
871                  (ununderline-region b e))))
872   "Alist of mail and news faces for facemenu.
873 The cdr of ech entry is a function for applying the face to a region.")
874
875 (defcustom message-send-hook nil
876   "Hook run before sending messages."
877   :group 'message-various
878   :options '(ispell-message)
879   :type 'hook)
880
881 (defcustom message-send-mail-hook nil
882   "Hook run before sending mail messages."
883   :group 'message-various
884   :type 'hook)
885
886 (defcustom message-send-news-hook nil
887   "Hook run before sending news messages."
888   :group 'message-various
889   :type 'hook)
890
891 (defcustom message-sent-hook nil
892   "Hook run after sending messages."
893   :group 'message-various
894   :type 'hook)
895
896 (defcustom message-use-multi-frames nil
897   "Make new frame when sending messages."
898   :group 'message-frames
899   :type 'boolean)
900
901 (defcustom message-delete-frame-on-exit nil
902   "Delete frame after sending messages."
903   :group 'message-frames
904   :type '(choice (const :tag "off" nil)
905                  (const :tag "always" t)
906                  (const :tag "ask" ask)))
907
908 (defvar message-send-coding-system 'binary
909   "Coding system to encode outgoing mail.")
910
911 ;;; Internal variables.
912
913 (defvar message-buffer-list nil)
914 (defvar message-this-is-news nil)
915 (defvar message-this-is-mail nil)
916 (defvar message-draft-article nil)
917
918 ;; Byte-compiler warning
919 (defvar gnus-active-hashtb)
920 (defvar gnus-read-active-file)
921
922 ;;; Regexp matching the delimiter of messages in UNIX mail format
923 ;;; (UNIX From lines), minus the initial ^.  It should be a copy
924 ;;; of rmail.el's rmail-unix-mail-delimiter.
925 (defvar message-unix-mail-delimiter
926   (let ((time-zone-regexp
927          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
928                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
929                  "\\|"
930                  "\\) *")))
931     (concat
932      "From "
933
934      ;; Many things can happen to an RFC 822 mailbox before it is put into
935      ;; a `From' line.  The leading phrase can be stripped, e.g.
936      ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
937      ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
938      ;; can be removed, e.g.
939      ;;         From: joe@y.z (Joe      K
940      ;;                 User)
941      ;; can yield `From joe@y.z (Joe    K Fri Mar 22 08:11:15 1996', and
942      ;;         From: Joe User
943      ;;                 <joe@y.z>
944      ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
945      ;; The mailbox can be removed or be replaced by white space, e.g.
946      ;;         From: "Joe User"{space}{tab}
947      ;;                 <joe@y.z>
948      ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
949      ;; where {space} and {tab} represent the Ascii space and tab characters.
950      ;; We want to match the results of any of these manglings.
951      ;; The following regexp rejects names whose first characters are
952      ;; obviously bogus, but after that anything goes.
953      "\\([^\0-\b\n-\r\^?].*\\)? "
954
955      ;; The time the message was sent.
956      "\\([^\0-\r \^?]+\\) +"                            ; day of the week
957      "\\([^\0-\r \^?]+\\) +"                            ; month
958      "\\([0-3]?[0-9]\\) +"                              ; day of month
959      "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *"  ; time of day
960
961      ;; Perhaps a time zone, specified by an abbreviation, or by a
962      ;; numeric offset.
963      time-zone-regexp
964
965      ;; The year.
966      " \\([0-9][0-9]+\\) *"
967
968      ;; On some systems the time zone can appear after the year, too.
969      time-zone-regexp
970
971      ;; Old uucp cruft.
972      "\\(remote from .*\\)?"
973
974      "\n"))
975   "Regexp matching the delimiter of messages in UNIX mail format.")
976
977 (defvar message-unsent-separator
978   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
979           "^ *---+ +Returned message +---+ *$\\|"
980           "^Start of returned message$\\|"
981           "^ *---+ +Original message +---+ *$\\|"
982           "^ *--+ +begin message +--+ *$\\|"
983           "^ *---+ +Original message follows +---+ *$\\|"
984           "^|? *---+ +Message text follows: +---+ *|?$")
985   "A regexp that matches the separator before the text of a failed message.")
986
987 (defvar message-header-format-alist
988   `((Newsgroups)
989     (To . message-fill-address)
990     (Cc . message-fill-address)
991     (Subject)
992     (In-Reply-To)
993     (Fcc)
994     (Bcc)
995     (Date)
996     (Organization)
997     (Distribution)
998     (Lines)
999     (Expires)
1000     (Message-ID)
1001     (References . message-fill-references)
1002     (User-Agent))
1003   "Alist used for formatting headers.")
1004
1005 (eval-and-compile
1006   (autoload 'message-setup-toolbar "messagexmas")
1007   (autoload 'mh-new-draft-name "mh-comp")
1008   (autoload 'mh-send-letter "mh-comp")
1009   (autoload 'gnus-point-at-eol "gnus-util")
1010   (autoload 'gnus-point-at-bol "gnus-util")
1011   (autoload 'gnus-output-to-mail "gnus-util")
1012   (autoload 'gnus-output-to-rmail "gnus-util")
1013   (autoload 'mail-abbrev-in-expansion-header-p "mailabbrev")
1014   (autoload 'nndraft-request-associate-buffer "nndraft")
1015   (autoload 'nndraft-request-expire-articles "nndraft")
1016   (autoload 'gnus-open-server "gnus-int")
1017   (autoload 'gnus-request-post "gnus-int")
1018   (autoload 'gnus-copy-article-buffer "gnus-msg")
1019   (autoload 'gnus-alive-p "gnus-util")
1020   (autoload 'rmail-output "rmail"))
1021
1022 \f
1023
1024 ;;;
1025 ;;; Utility functions.
1026 ;;;
1027
1028 (defmacro message-y-or-n-p (question show &rest text)
1029   "Ask QUESTION, displaying the rest of the arguments in a temp. buffer if SHOW"
1030   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1031
1032 ;; Delete the current line (and the next N lines.);
1033 (defmacro message-delete-line (&optional n)
1034   `(delete-region (progn (beginning-of-line) (point))
1035                   (progn (forward-line ,(or n 1)) (point))))
1036
1037 (defun message-tokenize-header (header &optional separator)
1038   "Split HEADER into a list of header elements.
1039 \",\" is used as the separator."
1040   (if (not header)
1041       nil
1042     (let ((regexp (format "[%s]+" (or separator ",")))
1043           (beg 1)
1044           (first t)
1045           quoted elems paren)
1046       (save-excursion
1047         (message-set-work-buffer)
1048         (insert header)
1049         (goto-char (point-min))
1050         (while (not (eobp))
1051           (if first
1052               (setq first nil)
1053             (forward-char 1))
1054           (cond ((and (> (point) beg)
1055                       (or (eobp)
1056                           (and (looking-at regexp)
1057                                (not quoted)
1058                                (not paren))))
1059                  (push (buffer-substring beg (point)) elems)
1060                  (setq beg (match-end 0)))
1061                 ((= (following-char) ?\")
1062                  (setq quoted (not quoted)))
1063                 ((and (= (following-char) ?\()
1064                       (not quoted))
1065                  (setq paren t))
1066                 ((and (= (following-char) ?\))
1067                       (not quoted))
1068                  (setq paren nil))))
1069         (nreverse elems)))))
1070
1071 (defun message-mail-file-mbox-p (file)
1072   "Say whether FILE looks like a Unix mbox file."
1073   (when (and (file-exists-p file)
1074              (file-readable-p file)
1075              (file-regular-p file))
1076     (nnheader-temp-write nil
1077       (nnheader-insert-file-contents file)
1078       (goto-char (point-min))
1079       (looking-at message-unix-mail-delimiter))))
1080
1081 (defun message-fetch-field (header &optional not-all)
1082   "The same as `mail-fetch-field', only remove all newlines."
1083   (let* ((inhibit-point-motion-hooks t)
1084          (value (mail-fetch-field header nil (not not-all))))
1085     (when value
1086       (nnheader-replace-chars-in-string value ?\n ? ))))
1087
1088 (defun message-add-header (&rest headers)
1089   "Add the HEADERS to the message header, skipping those already present."
1090   (while headers
1091     (let (hclean)
1092       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1093         (error "Invalid header `%s'" (car headers)))
1094       (setq hclean (match-string 1 (car headers)))
1095     (save-restriction
1096       (message-narrow-to-headers)
1097       (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1098         (insert (car headers) ?\n))))
1099     (setq headers (cdr headers))))
1100
1101 (defun message-fetch-reply-field (header)
1102   "Fetch FIELD from the message we're replying to."
1103   (let ((buffer (message-get-reply-buffer)))
1104     (when (and buffer
1105                (buffer-name buffer))
1106       (save-excursion
1107         (set-buffer buffer)
1108       (message-fetch-field header)))))
1109
1110 (defun message-set-work-buffer ()
1111   (if (get-buffer " *message work*")
1112       (progn
1113         (set-buffer " *message work*")
1114         (erase-buffer))
1115     (set-buffer (get-buffer-create " *message work*"))
1116     (kill-all-local-variables)
1117     (buffer-disable-undo (current-buffer))))
1118
1119 (defun message-functionp (form)
1120   "Return non-nil if FORM is funcallable."
1121   (or (and (symbolp form) (fboundp form))
1122       (and (listp form) (eq (car form) 'lambda))
1123       (byte-code-function-p form)))
1124
1125 (defun message-strip-subject-re (subject)
1126   "Remove \"Re:\" from subject lines."
1127   (if (string-match message-subject-re-regexp subject)
1128       (substring subject (match-end 0))
1129     subject))
1130
1131 (defun message-remove-header (header &optional is-regexp first reverse)
1132   "Remove HEADER in the narrowed buffer.
1133 If REGEXP, HEADER is a regular expression.
1134 If FIRST, only remove the first instance of the header.
1135 Return the number of headers removed."
1136   (goto-char (point-min))
1137   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1138         (number 0)
1139         (case-fold-search t)
1140         last)
1141     (while (and (not (eobp))
1142                 (not last))
1143       (if (if reverse
1144               (not (looking-at regexp))
1145             (looking-at regexp))
1146           (progn
1147             (incf number)
1148             (when first
1149               (setq last t))
1150             (delete-region
1151              (point)
1152              ;; There might be a continuation header, so we have to search
1153              ;; until we find a new non-continuation line.
1154              (progn
1155                (forward-line 1)
1156                (if (re-search-forward "^[^ \t]" nil t)
1157                    (goto-char (match-beginning 0))
1158                  (point-max)))))
1159         (forward-line 1)
1160         (if (re-search-forward "^[^ \t]" nil t)
1161             (goto-char (match-beginning 0))
1162           (point-max))))
1163     number))
1164
1165 (defun message-narrow-to-headers ()
1166   "Narrow the buffer to the head of the message."
1167   (widen)
1168   (narrow-to-region
1169    (goto-char (point-min))
1170    (if (re-search-forward
1171         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1172        (match-beginning 0)
1173      (point-max)))
1174   (goto-char (point-min)))
1175
1176 (defun message-narrow-to-head ()
1177   "Narrow the buffer to the head of the message."
1178   (widen)
1179   (narrow-to-region
1180    (goto-char (point-min))
1181    (if (search-forward "\n\n" nil 1)
1182        (1- (point))
1183      (point-max)))
1184   (goto-char (point-min)))
1185
1186 (defun message-news-p ()
1187   "Say whether the current buffer contains a news message."
1188   (and (not message-this-is-mail)
1189        (or message-this-is-news
1190            (save-excursion
1191              (save-restriction
1192                (message-narrow-to-headers)
1193                (and (message-fetch-field "newsgroups")
1194                     (not (message-fetch-field "posted-to"))))))))
1195
1196 (defun message-mail-p ()
1197   "Say whether the current buffer contains a mail message."
1198   (and (not message-this-is-news)
1199        (or message-this-is-mail
1200            (save-excursion
1201              (save-restriction
1202                (message-narrow-to-headers)
1203                (or (message-fetch-field "to")
1204                    (message-fetch-field "cc")
1205                    (message-fetch-field "bcc")))))))
1206
1207 (defun message-next-header ()
1208   "Go to the beginning of the next header."
1209   (beginning-of-line)
1210   (or (eobp) (forward-char 1))
1211   (not (if (re-search-forward "^[^ \t]" nil t)
1212            (beginning-of-line)
1213          (goto-char (point-max)))))
1214
1215 (defun message-sort-headers-1 ()
1216   "Sort the buffer as headers using `message-rank' text props."
1217   (goto-char (point-min))
1218   (sort-subr
1219    nil 'message-next-header
1220    (lambda ()
1221      (message-next-header)
1222      (unless (bobp)
1223        (forward-char -1)))
1224    (lambda ()
1225      (or (get-text-property (point) 'message-rank)
1226          10000))))
1227
1228 (defun message-sort-headers ()
1229   "Sort the headers of the current message according to `message-header-format-alist'."
1230   (interactive)
1231   (save-excursion
1232     (save-restriction
1233       (let ((max (1+ (length message-header-format-alist)))
1234             rank)
1235         (message-narrow-to-headers)
1236         (while (re-search-forward "^[^ \n]+:" nil t)
1237           (put-text-property
1238            (match-beginning 0) (1+ (match-beginning 0))
1239            'message-rank
1240            (if (setq rank (length (memq (assq (intern (buffer-substring
1241                                                        (match-beginning 0)
1242                                                        (1- (match-end 0))))
1243                                               message-header-format-alist)
1244                                         message-header-format-alist)))
1245                (- max rank)
1246              (1+ max)))))
1247       (message-sort-headers-1))))
1248
1249 (defun message-eval-parameter (parameter)
1250   (condition-case ()
1251       (if (symbolp parameter)
1252           (if (functionp parameter)
1253               (funcall parameter)
1254             (eval parameter))
1255         parameter)
1256     (error nil)))
1257
1258 (defun message-get-reply-buffer ()
1259   (message-eval-parameter message-reply-buffer))
1260
1261 (defun message-get-original-reply-buffer ()
1262   (message-eval-parameter
1263    (cdr (assq 'original-buffer message-parameter-alist))))
1264 \f
1265
1266 ;;;
1267 ;;; Message mode
1268 ;;;
1269
1270 ;;; Set up keymap.
1271
1272 (defvar message-mode-map nil)
1273
1274 (unless message-mode-map
1275   (setq message-mode-map (copy-keymap text-mode-map))
1276   (define-key message-mode-map "\C-c?" 'describe-mode)
1277
1278   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1279   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1280   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1281   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1282   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1283   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1284   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1285   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1286   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1287   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1288   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1289   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1290   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1291
1292   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1293   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1294
1295   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1296   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1297   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1298   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1299   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1300   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1301
1302   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1303   (define-key message-mode-map "\C-c\C-s" 'message-send)
1304   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1305   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1306
1307   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1308   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1309   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1310   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1311
1312   (define-key message-mode-map "\t" 'message-tab)
1313
1314   (define-key message-mode-map "\C-x\C-s" 'message-save-drafts)
1315   (define-key message-mode-map "\C-xk" 'message-kill-buffer))
1316
1317 (easy-menu-define
1318  message-mode-menu message-mode-map "Message Menu."
1319  '("Message"
1320    ["Sort Headers" message-sort-headers t]
1321    ["Yank Original" message-yank-original t]
1322    ["Fill Yanked Message" message-fill-yanked-message t]
1323    ["Insert Signature" message-insert-signature t]
1324    ["Caesar (rot13) Message" message-caesar-buffer-body t]
1325    ["Caesar (rot13) Region" message-caesar-region (mark t)]
1326    ["Elide Region" message-elide-region (mark t)]
1327    ["Delete Outside Region" message-delete-not-region (mark t)]
1328    ["Kill To Signature" message-kill-to-signature t]
1329    ["Newline and Reformat" message-newline-and-reformat t]
1330    ["Rename buffer" message-rename-buffer t]
1331    ["Spellcheck" ispell-message t]
1332    "----"
1333    ["Send Message" message-send-and-exit t]
1334    ["Abort Message" message-dont-send t]
1335    ["Kill Message" message-kill-buffer t]))
1336
1337 (easy-menu-define
1338  message-mode-field-menu message-mode-map ""
1339  '("Field"
1340    ["Fetch To" message-insert-to t]
1341    ["Fetch Newsgroups" message-insert-newsgroups t]
1342    "----"
1343    ["To" message-goto-to t]
1344    ["Subject" message-goto-subject t]
1345    ["Cc" message-goto-cc t]
1346    ["Reply-To" message-goto-reply-to t]
1347    ["Summary" message-goto-summary t]
1348    ["Keywords" message-goto-keywords t]
1349    ["Newsgroups" message-goto-newsgroups t]
1350    ["Followup-To" message-goto-followup-to t]
1351    ["Distribution" message-goto-distribution t]
1352    ["Body" message-goto-body t]
1353    ["Signature" message-goto-signature t]))
1354
1355 (defvar facemenu-add-face-function)
1356 (defvar facemenu-remove-face-function)
1357
1358 ;;;###autoload
1359 (defun message-mode ()
1360   "Major mode for editing mail and news to be sent.
1361 Like Text Mode but with these additional commands:
1362 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
1363 C-c C-f  move to a header field (and create it if there isn't):
1364          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1365          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1366          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1367          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1368          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1369          C-c C-f C-f  move to Followup-To
1370 C-c C-t  message-insert-to (add a To header to a news followup)
1371 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
1372 C-c C-b  message-goto-body (move to beginning of message text).
1373 C-c C-i  message-goto-signature (move to the beginning of the signature).
1374 C-c C-w  message-insert-signature (insert `message-signature-file' file).
1375 C-c C-y  message-yank-original (insert current message, if any).
1376 C-c C-q  message-fill-yanked-message (fill what was yanked).
1377 C-c C-e  message-elide-region (elide the text between point and mark).
1378 C-c C-z  message-kill-to-signature (kill the text up to the signature).
1379 C-c C-r  message-caesar-buffer-body (rot13 the message body)."
1380   (interactive)
1381   (kill-all-local-variables)
1382   (make-local-variable 'message-reply-buffer)
1383   (setq message-reply-buffer nil)
1384   (make-local-variable 'message-send-actions) 
1385   (make-local-variable 'message-exit-actions) 
1386   (make-local-variable 'message-kill-actions)
1387   (make-local-variable 'message-postpone-actions)
1388   (make-local-variable 'message-draft-article)
1389   (make-local-hook 'kill-buffer-hook)
1390   (set-syntax-table message-mode-syntax-table)
1391   (use-local-map message-mode-map)
1392   (setq local-abbrev-table message-mode-abbrev-table)
1393   (setq major-mode 'message-mode)
1394   (setq mode-name "Message")
1395   (setq buffer-offer-save t)
1396   (make-local-variable 'facemenu-add-face-function)
1397   (make-local-variable 'facemenu-remove-face-function)
1398   (setq facemenu-add-face-function
1399         (lambda (face end)
1400           (let ((face-fun (cdr (assq face message-face-alist))))
1401             (if face-fun
1402                 (funcall face-fun (point) end)
1403               (error "Face %s not configured for %s mode" face mode-name)))
1404           "")
1405         facemenu-remove-face-function t)
1406   (make-local-variable 'paragraph-separate)
1407   (make-local-variable 'paragraph-start)
1408   ;; `-- ' precedes the signature.  `-----' appears at the start of the
1409   ;; lines that delimit forwarded messages.
1410   ;; Lines containing just >= 3 dashes, perhaps after whitespace,
1411   ;; are also sometimes used and should be separators.
1412   (setq paragraph-start
1413         (concat (regexp-quote mail-header-separator)
1414                 "$\\|[ \t]*[a-z0-9A-Z]*>+[ \t]*$\\|[ \t]*$\\|"
1415                 "-- $\\|---+$\\|"
1416                 page-delimiter
1417                 ;;!!! Uhm... shurely this can't be right?
1418                 "[> " (regexp-quote message-yank-prefix) "]+$"))
1419   (setq paragraph-separate paragraph-start)
1420   (make-local-variable 'message-reply-headers)
1421   (setq message-reply-headers nil)
1422   (make-local-variable 'message-user-agent)
1423   (make-local-variable 'message-post-method)
1424   (make-local-variable 'message-sent-message-via)
1425   (setq message-sent-message-via nil)
1426   (make-local-variable 'message-checksum)
1427   (setq message-checksum nil)
1428   (make-local-variable 'message-parameter-alist)
1429   (setq message-parameter-alist
1430         (copy-sequence message-startup-parameter-alist))
1431   ;;(when (fboundp 'mail-hist-define-keys)
1432   ;;  (mail-hist-define-keys))
1433   (when (string-match "XEmacs\\|Lucid" emacs-version)
1434     (message-setup-toolbar))
1435   (easy-menu-add message-mode-menu message-mode-map)
1436   (easy-menu-add message-mode-field-menu message-mode-map)
1437   ;; Allow mail alias things.
1438   (when (eq message-mail-alias-type 'abbrev)
1439     (if (fboundp 'mail-abbrevs-setup)
1440         (mail-abbrevs-setup)
1441       (mail-aliases-setup)))
1442   (message-set-auto-save-file-name)
1443   (unless (string-match "XEmacs" emacs-version)
1444     (set (make-local-variable 'font-lock-defaults)
1445          '(message-font-lock-keywords t)))
1446   (make-local-variable 'adaptive-fill-regexp)
1447   (setq adaptive-fill-regexp
1448         (concat "[ \t]*[-a-z0-9A-Z]*>+[ \t]*\\|" adaptive-fill-regexp))
1449   (unless (boundp 'adaptive-fill-first-line-regexp)
1450     (setq adaptive-fill-first-line-regexp nil))
1451   (make-local-variable 'adaptive-fill-first-line-regexp)
1452   (setq adaptive-fill-first-line-regexp
1453         (concat "[ \t]*[-a-z0-9A-Z]*>+[ \t]*\\|"
1454                 adaptive-fill-first-line-regexp))
1455   (run-hooks 'text-mode-hook 'message-mode-hook))
1456
1457 \f
1458
1459 ;;;
1460 ;;; Message mode commands
1461 ;;;
1462
1463 ;;; Movement commands
1464
1465 (defun message-goto-to ()
1466   "Move point to the To header."
1467   (interactive)
1468   (message-position-on-field "To"))
1469
1470 (defun message-goto-subject ()
1471   "Move point to the Subject header."
1472   (interactive)
1473   (message-position-on-field "Subject"))
1474
1475 (defun message-goto-cc ()
1476   "Move point to the Cc header."
1477   (interactive)
1478   (message-position-on-field "Cc" "To"))
1479
1480 (defun message-goto-bcc ()
1481   "Move point to the Bcc  header."
1482   (interactive)
1483   (message-position-on-field "Bcc" "Cc" "To"))
1484
1485 (defun message-goto-fcc ()
1486   "Move point to the Fcc header."
1487   (interactive)
1488   (message-position-on-field "Fcc" "To" "Newsgroups"))
1489
1490 (defun message-goto-reply-to ()
1491   "Move point to the Reply-To header."
1492   (interactive)
1493   (message-position-on-field "Reply-To" "Subject"))
1494
1495 (defun message-goto-newsgroups ()
1496   "Move point to the Newsgroups header."
1497   (interactive)
1498   (message-position-on-field "Newsgroups"))
1499
1500 (defun message-goto-distribution ()
1501   "Move point to the Distribution header."
1502   (interactive)
1503   (message-position-on-field "Distribution"))
1504
1505 (defun message-goto-followup-to ()
1506   "Move point to the Followup-To header."
1507   (interactive)
1508   (message-position-on-field "Followup-To" "Newsgroups"))
1509
1510 (defun message-goto-keywords ()
1511   "Move point to the Keywords header."
1512   (interactive)
1513   (message-position-on-field "Keywords" "Subject"))
1514
1515 (defun message-goto-summary ()
1516   "Move point to the Summary header."
1517   (interactive)
1518   (message-position-on-field "Summary" "Subject"))
1519
1520 (defun message-goto-body ()
1521   "Move point to the beginning of the message body."
1522   (interactive)
1523   (if (looking-at "[ \t]*\n") (expand-abbrev))
1524   (goto-char (point-min))
1525   (search-forward (concat "\n" mail-header-separator "\n") nil t))
1526
1527 (defun message-goto-eoh ()
1528   "Move point to the end of the headers."
1529   (interactive)
1530   (message-goto-body)
1531   (forward-line -2))
1532
1533 (defun message-goto-signature ()
1534   "Move point to the beginning of the message signature.
1535 If there is no signature in the article, go to the end and
1536 return nil."
1537   (interactive)
1538   (goto-char (point-min))
1539   (if (re-search-forward message-signature-separator nil t)
1540       (forward-line 1)
1541     (goto-char (point-max))
1542     nil))
1543
1544 \f
1545
1546 (defun message-insert-to (&optional force)
1547   "Insert a To header that points to the author of the article being replied to.
1548 If the original author requested not to be sent mail, the function signals
1549 an error.
1550 With the prefix argument FORCE, insert the header anyway."
1551   (interactive "P")
1552   (let ((co (message-fetch-reply-field "mail-copies-to")))
1553     (when (and (null force)
1554                co
1555                (equal (downcase co) "never"))
1556       (error "The user has requested not to have copies sent via mail")))
1557   (when (and (message-position-on-field "To")
1558              (mail-fetch-field "to")
1559              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1560     (insert ", "))
1561   (insert (or (message-fetch-reply-field "reply-to")
1562               (message-fetch-reply-field "from") "")))
1563
1564 (defun message-insert-newsgroups ()
1565   "Insert the Newsgroups header from the article being replied to."
1566   (interactive)
1567   (when (and (message-position-on-field "Newsgroups")
1568              (mail-fetch-field "newsgroups")
1569              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1570     (insert ","))
1571   (insert (or (message-fetch-reply-field "newsgroups") "")))
1572
1573 \f
1574
1575 ;;; Various commands
1576
1577 (defun message-delete-not-region (beg end)
1578   "Delete everything in the body of the current message that is outside of the region."
1579   (interactive "r")
1580   (save-excursion
1581     (goto-char end)
1582     (delete-region (point) (if (not (message-goto-signature))
1583                                (point)
1584                              (forward-line -2)
1585                              (point)))
1586     (insert "\n")
1587     (goto-char beg)
1588     (delete-region beg (progn (message-goto-body)
1589                               (forward-line 2)
1590                               (point))))
1591   (when (message-goto-signature)
1592     (forward-line -2)))
1593
1594 (defun message-kill-to-signature ()
1595   "Deletes all text up to the signature."
1596   (interactive)
1597   (let ((point (point)))
1598     (message-goto-signature)
1599     (unless (eobp)
1600       (forward-line -2))
1601     (kill-region point (point))
1602     (unless (bolp)
1603       (insert "\n"))))
1604
1605 (defun message-newline-and-reformat ()
1606   "Insert four newlines, and then reformat if inside quoted text."
1607   (interactive)
1608   (let ((point (point))
1609         quoted)
1610     (save-excursion
1611       (beginning-of-line)
1612       (setq quoted (looking-at (regexp-quote message-yank-prefix))))
1613     (insert "\n\n\n\n")
1614     (when quoted
1615       (insert message-yank-prefix))
1616     (fill-paragraph nil)
1617     (goto-char point)
1618     (forward-line 2)))
1619
1620 (defun message-insert-signature (&optional force)
1621   "Insert a signature.  See documentation for the `message-signature' variable."
1622   (interactive (list 0))
1623   (let* ((signature
1624           (cond
1625            ((and (null message-signature)
1626                  (eq force 0))
1627             (save-excursion
1628               (goto-char (point-max))
1629               (not (re-search-backward
1630                     message-signature-separator nil t))))
1631            ((and (null message-signature)
1632                  force)
1633             t)
1634            ((message-functionp message-signature)
1635             (funcall message-signature))
1636            ((listp message-signature)
1637             (eval message-signature))
1638            (t message-signature)))
1639          (signature
1640           (cond ((stringp signature)
1641                  signature)
1642                 ((and (eq t signature)
1643                       message-signature-file
1644                       (file-exists-p message-signature-file))
1645                  signature))))
1646     (when signature
1647       (goto-char (point-max))
1648       ;; Insert the signature.
1649       (unless (bolp)
1650         (insert "\n"))
1651       (insert "\n-- \n")
1652       (if (eq signature t)
1653           (insert-file-contents message-signature-file)
1654         (insert signature))
1655       (goto-char (point-max))
1656       (or (bolp) (insert "\n")))))
1657
1658 (defun message-elide-region (b e)
1659   "Elide the text between point and mark.
1660 An ellipsis (from `message-elide-elipsis') will be inserted where the
1661 text was killed."
1662   (interactive "r")
1663   (kill-region b e)
1664   (unless (bolp)
1665     (insert "\n"))
1666   (insert message-elide-elipsis))
1667
1668 (defvar message-caesar-translation-table nil)
1669
1670 (defun message-caesar-region (b e &optional n)
1671   "Caesar rotation of region by N, default 13, for decrypting netnews."
1672   (interactive
1673    (list
1674     (min (point) (or (mark t) (point)))
1675     (max (point) (or (mark t) (point)))
1676     (when current-prefix-arg
1677       (prefix-numeric-value current-prefix-arg))))
1678
1679   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1680   (unless (or (zerop n)                 ; no action needed for a rot of 0
1681               (= b e))                  ; no region to rotate
1682     ;; We build the table, if necessary.
1683     (when (or (not message-caesar-translation-table)
1684               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1685         (setq message-caesar-translation-table
1686               (message-make-caesar-translation-table n)))
1687     ;; Then we translate the region.  Do it this way to retain
1688     ;; text properties.
1689     (while (< b e)
1690       (subst-char-in-region
1691        b (1+ b) (char-after b)
1692        (aref message-caesar-translation-table (char-after b)))
1693       (incf b))))
1694
1695 (defun message-make-caesar-translation-table (n)
1696   "Create a rot table with offset N."
1697   (let ((i -1)
1698         (table (make-string 256 0)))
1699     (while (< (incf i) 256)
1700       (aset table i i))
1701     (concat
1702      (substring table 0 ?A)
1703      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1704      (substring table ?A (+ ?A n))
1705      (substring table (+ ?A 26) ?a)
1706      (substring table (+ ?a n) (+ ?a n (- 26 n)))
1707      (substring table ?a (+ ?a n))
1708      (substring table (+ ?a 26) 255))))
1709
1710 (defun message-caesar-buffer-body (&optional rotnum)
1711   "Caesar rotates all letters in the current buffer by 13 places.
1712 Used to encode/decode possiblyun offensive messages (commonly in net.jokes).
1713 With prefix arg, specifies the number of places to rotate each letter forward.
1714 Mail and USENET news headers are not rotated."
1715   (interactive (if current-prefix-arg
1716                    (list (prefix-numeric-value current-prefix-arg))
1717                  (list nil)))
1718   (save-excursion
1719     (save-restriction
1720       (when (message-goto-body)
1721         (narrow-to-region (point) (point-max)))
1722       (message-caesar-region (point-min) (point-max) rotnum))))
1723
1724 (defun message-pipe-buffer-body (program)
1725   "Pipe the message body in the current buffer through PROGRAM."
1726   (save-excursion
1727     (save-restriction
1728       (when (message-goto-body)
1729         (narrow-to-region (point) (point-max)))
1730       (let ((body (buffer-substring (point-min) (point-max))))
1731         (unless (equal 0 (call-process-region
1732                            (point-min) (point-max) program t t))
1733             (insert body)
1734             (message "%s failed." program))))))
1735
1736 (defun message-rename-buffer (&optional enter-string)
1737   "Rename the *message* buffer to \"*message* RECIPIENT\".
1738 If the function is run with a prefix, it will ask for a new buffer
1739 name, rather than giving an automatic name."
1740   (interactive "Pbuffer name: ")
1741   (save-excursion
1742     (save-restriction
1743       (goto-char (point-min))
1744       (narrow-to-region (point)
1745                         (search-forward mail-header-separator nil 'end))
1746       (let* ((mail-to (or
1747                        (if (message-news-p) (message-fetch-field "Newsgroups")
1748                          (message-fetch-field "To"))
1749                        ""))
1750              (mail-trimmed-to
1751               (if (string-match "," mail-to)
1752                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1753                 mail-to))
1754              (name-default (concat "*message* " mail-trimmed-to))
1755              (name (if enter-string
1756                        (read-string "New buffer name: " name-default)
1757                      name-default)))
1758         (rename-buffer name t)))))
1759
1760 (defun message-fill-yanked-message (&optional justifyp)
1761   "Fill the paragraphs of a message yanked into this one.
1762 Numeric argument means justify as well."
1763   (interactive "P")
1764   (save-excursion
1765     (goto-char (point-min))
1766     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1767     (let ((fill-prefix message-yank-prefix))
1768       (fill-individual-paragraphs (point) (point-max) justifyp t))))
1769
1770 (defun message-indent-citation ()
1771   "Modify text just inserted from a message to be cited.
1772 The inserted text should be the region.
1773 When this function returns, the region is again around the modified text.
1774
1775 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1776 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1777   (let ((start (point)))
1778     ;; Remove unwanted headers.
1779     (when message-ignored-cited-headers
1780       (let (all-removed)
1781         (save-restriction
1782           (narrow-to-region
1783            (goto-char start)
1784            (if (search-forward "\n\n" nil t)
1785                (1- (point))
1786              (point)))
1787           (message-remove-header message-ignored-cited-headers t)
1788           (when (= (point-min) (point-max))
1789             (setq all-removed t))
1790           (goto-char (point-max)))
1791         (if all-removed
1792             (goto-char start)
1793           (forward-line 1))))
1794     ;; Delete blank lines at the start of the buffer.
1795     (while (and (point-min)
1796                 (eolp)
1797                 (not (eobp)))
1798       (message-delete-line))
1799     ;; Delete blank lines at the end of the buffer.
1800     (goto-char (point-max))
1801     (unless (eolp)
1802       (insert "\n"))
1803     (while (and (zerop (forward-line -1))
1804                 (looking-at "$"))
1805       (message-delete-line))
1806     ;; Do the indentation.
1807     (if (null message-yank-prefix)
1808         (indent-rigidly start (mark t) message-indentation-spaces)
1809       (save-excursion
1810         (goto-char start)
1811         (while (< (point) (mark t))
1812           (insert message-yank-prefix)
1813           (forward-line 1))))
1814     (goto-char start)))
1815
1816 (defvar gnus-article-copy)
1817 (defun message-yank-original (&optional arg)
1818   "Insert the message being replied to, if any.
1819 Puts point before the text and mark after.
1820 Normally indents each nonblank line ARG spaces (default 3).  However,
1821 if `message-yank-prefix' is non-nil, insert that prefix on each line.
1822
1823 This function uses `message-cite-function' to do the actual citing.
1824
1825 Just \\[universal-argument] as argument means don't indent, insert no
1826 prefix, and don't delete any headers."
1827   (interactive "P")
1828   (let ((modified (buffer-modified-p))
1829         (buffer (message-get-reply-buffer)))
1830     (when (and buffer
1831                message-cite-function)
1832       (delete-windows-on buffer t)
1833       (insert-buffer buffer)
1834       (funcall message-cite-function)
1835       (message-exchange-point-and-mark)
1836       (unless (bolp)
1837         (insert ?\n))
1838       (unless modified
1839         (setq message-checksum (message-checksum))))))
1840
1841 (defun message-cite-original-without-signature ()
1842   "Cite function in the standard Message manner."
1843   (let ((start (point))
1844         (end (mark t))
1845         (functions
1846          (when message-indent-citation-function
1847            (if (listp message-indent-citation-function)
1848                message-indent-citation-function
1849              (list message-indent-citation-function)))))
1850     (goto-char end)
1851     (when (re-search-backward "^-- $" start t)
1852       ;; Also peel off any blank lines before the signature.
1853       (forward-line -1)
1854       (while (looking-at "^[ \t]*$")
1855         (forward-line -1))
1856       (forward-line 1)
1857       (delete-region (point) end))
1858     (goto-char start)
1859     (while functions
1860       (funcall (pop functions)))
1861     (when message-citation-line-function
1862       (unless (bolp)
1863         (insert "\n"))
1864       (funcall message-citation-line-function))))
1865
1866 (defvar mail-citation-hook) ;Compiler directive
1867 (defun message-cite-original ()
1868   "Cite function in the standard Message manner."
1869   (if (and (boundp 'mail-citation-hook)
1870            mail-citation-hook)
1871       (run-hooks 'mail-citation-hook)
1872     (let ((start (point))
1873           (functions
1874            (when message-indent-citation-function
1875              (if (listp message-indent-citation-function)
1876                  message-indent-citation-function
1877                (list message-indent-citation-function)))))
1878       (goto-char start)
1879       (while functions
1880         (funcall (pop functions)))
1881       (when message-citation-line-function
1882         (unless (bolp)
1883           (insert "\n"))
1884         (funcall message-citation-line-function)))))
1885
1886 (defun message-insert-citation-line ()
1887   "Function that inserts a simple citation line."
1888   (when message-reply-headers
1889     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
1890
1891 (defun message-position-on-field (header &rest afters)
1892   (let ((case-fold-search t))
1893     (save-restriction
1894       (narrow-to-region
1895        (goto-char (point-min))
1896        (progn
1897          (re-search-forward
1898           (concat "^" (regexp-quote mail-header-separator) "$"))
1899          (match-beginning 0)))
1900       (goto-char (point-min))
1901       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
1902           (progn
1903             (re-search-forward "^[^ \t]" nil 'move)
1904             (beginning-of-line)
1905             (skip-chars-backward "\n")
1906             t)
1907         (while (and afters
1908                     (not (re-search-forward
1909                           (concat "^" (regexp-quote (car afters)) ":")
1910                           nil t)))
1911           (pop afters))
1912         (when afters
1913           (re-search-forward "^[^ \t]" nil 'move)
1914           (beginning-of-line))
1915         (insert header ": \n")
1916         (forward-char -1)
1917         nil))))
1918
1919 (defun message-remove-signature ()
1920   "Remove the signature from the text between point and mark.
1921 The text will also be indented the normal way."
1922   (save-excursion
1923     (let ((start (point))
1924           mark)
1925       (if (not (re-search-forward message-signature-separator (mark t) t))
1926           ;; No signature here, so we just indent the cited text.
1927           (message-indent-citation)
1928         ;; Find the last non-empty line.
1929         (forward-line -1)
1930         (while (looking-at "[ \t]*$")
1931           (forward-line -1))
1932         (forward-line 1)
1933         (setq mark (set-marker (make-marker) (point)))
1934         (goto-char start)
1935         (message-indent-citation)
1936         ;; Enable undoing the deletion.
1937         (undo-boundary)
1938         (delete-region mark (mark t))
1939         (set-marker mark nil)))))
1940
1941 \f
1942
1943 ;;;
1944 ;;; Sending messages
1945 ;;;
1946
1947 ;; Avoid byte-compile warning.
1948 (defvar message-encoding-buffer nil)
1949 (defvar message-edit-buffer nil)
1950 (defvar message-mime-mode nil)
1951
1952 (defun message-send-and-exit (&optional arg)
1953   "Send message like `message-send', then, if no errors, exit from mail buffer."
1954   (interactive "P")
1955   (let ((buf (current-buffer))
1956         (actions message-exit-actions)
1957         (frame (selected-frame))
1958         (org-frame message-original-frame))
1959     (when (and (message-send arg)
1960                (buffer-name buf))
1961       (if message-kill-buffer-on-exit
1962           (kill-buffer buf)
1963         (bury-buffer buf)
1964         (when (eq buf (current-buffer))
1965           (message-bury buf)))
1966       (message-do-actions actions)
1967       (message-delete-frame frame org-frame)
1968       t)))
1969
1970 (defun message-dont-send ()
1971   "Don't send the message you have been editing."
1972   (interactive)
1973   (set-buffer-modified-p t)
1974   (save-buffer)
1975   (let ((actions message-postpone-actions)
1976         (frame (selected-frame))
1977         (org-frame message-original-frame))
1978     (message-bury (current-buffer))
1979     (message-do-actions actions)
1980     (message-delete-frame frame org-frame)))
1981
1982 (defun message-kill-buffer ()
1983   "Kill the current buffer."
1984   (interactive)
1985   (when (or (not (buffer-modified-p))
1986             (eq t message-kill-buffer-query-function)
1987             (funcall message-kill-buffer-query-function
1988                      "The buffer modified; kill anyway? "))
1989     (let ((actions message-kill-actions)
1990           (frame (selected-frame))
1991           (org-frame message-original-frame))
1992       (setq buffer-file-name nil)
1993       (kill-buffer (current-buffer))
1994       (message-do-actions actions)
1995       (message-delete-frame frame org-frame)))
1996   (message ""))
1997
1998 (defun message-delete-frame (frame org-frame)
1999   "Delete frame for editing message."
2000   (when (and (or (and (featurep 'xemacs)
2001                       (not (eq 'tty (device-type))))
2002                  window-system
2003                  (>= emacs-major-version 20))
2004              (or (and (eq message-delete-frame-on-exit t)
2005                       (select-frame frame)
2006                       (or (eq frame org-frame)
2007                           (prog1
2008                               (y-or-n-p "Delete this frame?")
2009                             (message ""))))
2010                  (and (eq message-delete-frame-on-exit 'ask)
2011                       (select-frame frame)
2012                       (prog1
2013                           (y-or-n-p "Delete this frame?")
2014                         (message "")))))
2015     (delete-frame frame)))
2016
2017 (defun message-bury (buffer)
2018   "Bury this mail buffer."
2019   (let ((newbuf (other-buffer buffer)))
2020     (bury-buffer buffer)
2021     (if (and (fboundp 'frame-parameters)
2022              (cdr (assq 'dedicated (frame-parameters)))
2023              (not (null (delq (selected-frame) (visible-frame-list)))))
2024         (delete-frame (selected-frame))
2025       (switch-to-buffer newbuf))))
2026
2027 (defun message-send (&optional arg)
2028   "Send the message in the current buffer.
2029 If `message-interactive' is non-nil, wait for success indication
2030 or error messages, and inform user.
2031 Otherwise any failure is reported in a message back to
2032 the user from the mailer."
2033   (interactive "P")
2034   ;; Disabled test.
2035   (when (or (buffer-modified-p)
2036             (message-check-element 'unchanged)
2037             (y-or-n-p "No changes in the buffer; really send? "))
2038     ;; Make it possible to undo the coming changes.
2039     (undo-boundary)
2040     (let ((inhibit-read-only t))
2041       (put-text-property (point-min) (point-max) 'read-only nil))
2042     (run-hooks 'message-send-hook)
2043     (message "Sending...")
2044     (let ((message-encoding-buffer
2045            (message-generate-new-buffer-clone-locals " message encoding"))
2046           (message-edit-buffer (current-buffer))
2047           (message-mime-mode mime-edit-mode-flag)
2048           (alist message-send-method-alist)
2049           (success t)
2050           elem sent)
2051       (save-excursion
2052         (set-buffer message-encoding-buffer)
2053         (erase-buffer)
2054         (insert-buffer message-edit-buffer)
2055         (funcall message-encode-function)
2056         (message-fix-before-sending)
2057         (while (and success
2058                     (setq elem (pop alist)))
2059           (when (and (or (not (funcall (cadr elem)))
2060                          (and (or (not (memq (car elem)
2061                                              message-sent-message-via))
2062                                   (y-or-n-p
2063                                    (format
2064                                     "Already sent message via %s; resend? "
2065                                     (car elem))))
2066                               (setq success (funcall (caddr elem) arg)))))
2067             (setq sent t))))
2068       (when (and success sent)
2069         (message-do-fcc)
2070         ;;(when (fboundp 'mail-hist-put-headers-into-history)
2071         ;; (mail-hist-put-headers-into-history))
2072         (run-hooks 'message-sent-hook)
2073         (message "Sending...done")
2074         ;; Mark the buffer as unmodified and delete autosave.
2075         (set-buffer-modified-p nil)
2076         (delete-auto-save-file-if-necessary t)
2077         (message-disassociate-draft)
2078         ;; Delete other mail buffers and stuff.
2079         (message-do-send-housekeeping)
2080         (message-do-actions message-send-actions)
2081         ;; Return success.
2082         t))))
2083
2084 (defun message-send-via-mail (arg)
2085   "Send the current message via mail."
2086   (message-send-mail arg))
2087
2088 (defun message-send-via-news (arg)
2089   "Send the current message via news."
2090   (message-send-news arg))
2091
2092 (defun message-fix-before-sending ()
2093   "Do various things to make the message nice before sending it."
2094   ;; Make sure there's a newline at the end of the message.
2095   (goto-char (point-max))
2096   (unless (bolp)
2097     (insert "\n"))
2098   ;; Make all invisible text visible.
2099   ;;(when (text-property-any (point-min) (point-max) 'invisible t)
2100   ;;  (put-text-property (point-min) (point-max) 'invisible nil)
2101   ;;  (unless (yes-or-no-p "Invisible text found and made visible; continue posting?")
2102   ;;    (error "Invisible text found and made visible")))
2103   )
2104
2105 (defun message-add-action (action &rest types)
2106   "Add ACTION to be performed when doing an exit of type TYPES."
2107   (let (var)
2108     (while types
2109       (set (setq var (intern (format "message-%s-actions" (pop types))))
2110            (nconc (symbol-value var) (list action))))))
2111
2112 (defun message-do-actions (actions)
2113   "Perform all actions in ACTIONS."
2114   ;; Now perform actions on successful sending.
2115   (while actions
2116     (ignore-errors
2117       (cond
2118        ;; A simple function.
2119        ((message-functionp (car actions))
2120         (funcall (car actions)))
2121        ;; Something to be evaled.
2122        (t
2123         (eval (car actions)))))
2124     (pop actions)))
2125
2126 (defun message-send-mail (&optional arg)
2127   (require 'mail-utils)
2128   (let ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2129         (case-fold-search nil)
2130         (news (message-news-p)))
2131     (save-restriction
2132       (message-narrow-to-headers)
2133       ;; Insert some headers.
2134       (let ((message-deletable-headers
2135              (if news nil message-deletable-headers)))
2136         (message-generate-headers message-required-mail-headers))
2137       ;; Let the user do all of the above.
2138       (run-hooks 'message-header-hook))
2139     (if (not (message-check-mail-syntax))
2140         (progn
2141           (message "")
2142           ;;(message "Posting not performed")
2143           nil)
2144       (unwind-protect
2145           (save-excursion
2146             (set-buffer tembuf)
2147             (erase-buffer)
2148             (insert-buffer message-encoding-buffer)
2149             ;; Remove some headers.
2150             (save-restriction
2151               (message-narrow-to-headers)
2152               (message-remove-header message-ignored-mail-headers t))
2153             (goto-char (point-max))
2154             ;; require one newline at the end.
2155             (or (= (preceding-char) ?\n)
2156                 (insert ?\n))
2157             (when (and news
2158                        (or (message-fetch-field "cc")
2159                            (message-fetch-field "to")))
2160               (message-insert-courtesy-copy))
2161             (mime-edit-maybe-split-and-send
2162              (function
2163               (lambda ()
2164                 (interactive)
2165                 (funcall message-send-mail-function)
2166                 )))
2167             (funcall message-send-mail-function))
2168         (kill-buffer tembuf))
2169       (set-buffer message-edit-buffer)
2170       (push 'mail message-sent-message-via))))
2171
2172 (defun message-send-mail-with-sendmail ()
2173   "Send off the prepared buffer with sendmail."
2174   (let ((errbuf (if message-interactive
2175                     (generate-new-buffer " sendmail errors")
2176                   0))
2177         resend-to-addresses delimline)
2178     (let ((case-fold-search t))
2179       (save-restriction
2180         (message-narrow-to-headers)
2181         (setq resend-to-addresses (message-fetch-field "resent-to")))
2182       ;; Change header-delimiter to be what sendmail expects.
2183       (goto-char (point-min))
2184       (re-search-forward
2185        (concat "^" (regexp-quote mail-header-separator) "\n"))
2186       (replace-match "\n")
2187       (backward-char 1)
2188       (setq delimline (point-marker))
2189       (run-hooks 'message-send-mail-hook)
2190       ;; Insert an extra newline if we need it to work around
2191       ;; Sun's bug that swallows newlines.
2192       (goto-char (1+ delimline))
2193       (when (eval message-mailer-swallows-blank-line)
2194         (newline))
2195       (when message-interactive
2196         (save-excursion
2197           (set-buffer errbuf)
2198           (erase-buffer))))
2199     (let ((default-directory "/")
2200           (coding-system-for-write message-send-coding-system))
2201       (apply 'call-process-region
2202              (append (list (point-min) (point-max)
2203                            (if (boundp 'sendmail-program)
2204                                sendmail-program
2205                              "/usr/lib/sendmail")
2206                            nil errbuf nil "-oi")
2207                      ;; Always specify who from,
2208                      ;; since some systems have broken sendmails.
2209                      ;; But some systems are more broken with -f, so
2210                      ;; we'll let users override this.
2211                      (if (null message-sendmail-f-is-evil)
2212                          (list "-f" (user-login-name)))
2213                      ;; These mean "report errors by mail"
2214                      ;; and "deliver in background".
2215                      (if (null message-interactive) '("-oem" "-odb"))
2216                      ;; Get the addresses from the message
2217                      ;; unless this is a resend.
2218                      ;; We must not do that for a resend
2219                      ;; because we would find the original addresses.
2220                      ;; For a resend, include the specific addresses.
2221                      (if resend-to-addresses
2222                          (list resend-to-addresses)
2223                        '("-t")))))
2224     (when message-interactive
2225       (save-excursion
2226         (set-buffer errbuf)
2227         (goto-char (point-min))
2228         (while (re-search-forward "\n\n* *" nil t)
2229           (replace-match "; "))
2230         (if (not (zerop (buffer-size)))
2231             (error "Sending...failed to %s"
2232                    (buffer-substring (point-min) (point-max)))))
2233       (when (bufferp errbuf)
2234         (kill-buffer errbuf)))))
2235
2236 (defun message-send-mail-with-qmail ()
2237   "Pass the prepared message buffer to qmail-inject.
2238 Refer to the documentation for the variable `message-send-mail-function'
2239 to find out how to use this."
2240   ;; replace the header delimiter with a blank line
2241   (goto-char (point-min))
2242   (re-search-forward
2243    (concat "^" (regexp-quote mail-header-separator) "\n"))
2244   (replace-match "\n")
2245   (run-hooks 'message-send-mail-hook)
2246   ;; send the message
2247   (case
2248       (let ((coding-system-for-write message-send-coding-system))
2249         (apply
2250          'call-process-region 1 (point-max) message-qmail-inject-program
2251          nil nil nil
2252          ;; qmail-inject's default behaviour is to look for addresses on the
2253          ;; command line; if there're none, it scans the headers.
2254          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2255          ;;
2256          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2257          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2258          ;; message from stdin.
2259          ;;
2260          ;; qmail also has the advantage of not having been raped by
2261          ;; various vendors, so we don't have to allow for that, either --
2262          ;; compare this with message-send-mail-with-sendmail and weep
2263          ;; for sendmail's lost innocence.
2264          ;;
2265          ;; all this is way cool coz it lets us keep the arguments entirely
2266          ;; free for -inject-arguments -- a big win for the user and for us
2267          ;; since we don't have to play that double-guessing game and the user
2268          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2269          message-qmail-inject-args))
2270     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2271     ;; we have to look at the retval instead
2272     (0 nil)
2273     (1   (error "qmail-inject reported permanent failure"))
2274     (111 (error "qmail-inject reported transient failure"))
2275     ;; should never happen
2276     (t   (error "qmail-inject reported unknown failure"))))
2277
2278 (defun message-send-mail-with-mh ()
2279   "Send the prepared message buffer with mh."
2280   (let ((mh-previous-window-config nil)
2281         (name (mh-new-draft-name)))
2282     (setq buffer-file-name name)
2283     ;; MH wants to generate these headers itself.
2284     (when message-mh-deletable-headers
2285       (let ((headers message-mh-deletable-headers))
2286         (while headers
2287           (goto-char (point-min))
2288           (and (re-search-forward
2289                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2290                (message-delete-line))
2291           (pop headers))))
2292     (run-hooks 'message-send-mail-hook)
2293     ;; Pass it on to mh.
2294     (mh-send-letter)))
2295
2296 (defun message-send-mail-with-smtp ()
2297   "Send the prepared message buffer with SMTP."
2298   (require 'smtp)
2299   (let ((errbuf (if mail-interactive
2300                     (generate-new-buffer " smtp errors")
2301                   0))
2302         (case-fold-search nil)
2303         resend-to-addresses
2304         delimline)
2305     (unwind-protect
2306         (save-excursion
2307           (goto-char (point-max))
2308           ;; require one newline at the end.
2309           (or (= (preceding-char) ?\n)
2310               (insert ?\n))
2311           ;; Change header-delimiter to be what sendmail expects.
2312           (goto-char (point-min))
2313           (re-search-forward
2314            (concat "^" (regexp-quote mail-header-separator) "\n"))
2315           (replace-match "\n")
2316           (backward-char 1)
2317           (setq delimline (point-marker))
2318           (run-hooks 'message-send-mail-hook)
2319           ;; (sendmail-synch-aliases)
2320           ;; (if mail-aliases
2321           ;;     (expand-mail-aliases (point-min) delimline))
2322           (goto-char (point-min))
2323           ;; ignore any blank lines in the header
2324           (while (and (re-search-forward "\n\n\n*" delimline t)
2325                       (< (point) delimline))
2326             (replace-match "\n"))
2327           (let ((case-fold-search t))
2328             (goto-char (point-min))
2329             (goto-char (point-min))
2330             (while (re-search-forward "^Resent-to:" delimline t)
2331               (setq resend-to-addresses
2332                     (save-restriction
2333                       (narrow-to-region (point)
2334                                         (save-excursion
2335                                           (end-of-line)
2336                                           (point)))
2337                       (append (mail-parse-comma-list)
2338                               resend-to-addresses))))
2339 ;;; Apparently this causes a duplicate Sender.
2340 ;;;         ;; If the From is different than current user, insert Sender.
2341 ;;;         (goto-char (point-min))
2342 ;;;         (and (re-search-forward "^From:"  delimline t)
2343 ;;;              (progn
2344 ;;;                (require 'mail-utils)
2345 ;;;                (not (string-equal
2346 ;;;                      (mail-strip-quoted-names
2347 ;;;                       (save-restriction
2348 ;;;                         (narrow-to-region (point-min) delimline)
2349 ;;;                         (mail-fetch-field "From")))
2350 ;;;                      (user-login-name))))
2351 ;;;              (progn
2352 ;;;                (forward-line 1)
2353 ;;;                (insert "Sender: " (user-login-name) "\n")))
2354             ;; Don't send out a blank subject line
2355             (goto-char (point-min))
2356             (if (re-search-forward "^Subject:[ \t]*\n" delimline t)
2357                 (replace-match ""))
2358             ;; Put the "From:" field in unless for some odd reason
2359             ;; they put one in themselves.
2360             (goto-char (point-min))
2361             (if (not (re-search-forward "^From:" delimline t))
2362                 (let* ((login user-mail-address)
2363                        (fullname (user-full-name)))
2364                   (cond ((eq mail-from-style 'angles)
2365                          (insert "From: " fullname)
2366                          (let ((fullname-start (+ (point-min) 6))
2367                                (fullname-end (point-marker)))
2368                            (goto-char fullname-start)
2369                            ;; Look for a character that cannot appear unquoted
2370                            ;; according to RFC 822.
2371                            (if (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]"
2372                                                   fullname-end 1)
2373                                (progn
2374                                  ;; Quote fullname, escaping specials.
2375                                  (goto-char fullname-start)
2376                                  (insert "\"")
2377                                  (while (re-search-forward "[\"\\]"
2378                                                            fullname-end 1)
2379                                    (replace-match "\\\\\\&" t))
2380                                  (insert "\""))))
2381                          (insert " <" login ">\n"))
2382                         ((eq mail-from-style 'parens)
2383                          (insert "From: " login " (")
2384                          (let ((fullname-start (point)))
2385                            (insert fullname)
2386                            (let ((fullname-end (point-marker)))
2387                              (goto-char fullname-start)
2388                              ;; RFC 822 says \ and nonmatching parentheses
2389                              ;; must be escaped in comments.
2390                              ;; Escape every instance of ()\ ...
2391                              (while (re-search-forward "[()\\]" fullname-end 1)
2392                                (replace-match "\\\\\\&" t))
2393                              ;; ... then undo escaping of matching parentheses,
2394                              ;; including matching nested parentheses.
2395                              (goto-char fullname-start)
2396                              (while (re-search-forward 
2397                                      "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
2398                                      fullname-end 1)
2399                                (replace-match "\\1(\\3)" t)
2400                                (goto-char fullname-start))))
2401                          (insert ")\n"))
2402                         ((null mail-from-style)
2403                          (insert "From: " login "\n")))))
2404             ;; Insert an extra newline if we need it to work around
2405             ;; Sun's bug that swallows newlines.
2406             (goto-char (1+ delimline))
2407             (if (eval mail-mailer-swallows-blank-line)
2408                 (newline))
2409             ;; Find and handle any FCC fields.
2410             (goto-char (point-min))
2411             (if (re-search-forward "^FCC:" delimline t)
2412                 (mail-do-fcc delimline))
2413             (if mail-interactive
2414                 (save-excursion
2415                   (set-buffer errbuf)
2416                   (erase-buffer))))
2417           ;;
2418           ;;
2419           ;;
2420           (let ((recipient-address-list
2421                  (or resend-to-addresses
2422                      (smtp-deduce-address-list (current-buffer)
2423                                                (point-min) delimline))))
2424             (smtp-do-bcc delimline)
2425             
2426             (if recipient-address-list
2427                 (if (not (smtp-via-smtp recipient-address-list
2428                                         (current-buffer)))
2429                     (error "Sending failed; SMTP protocol error"))
2430               (error "Sending failed; no recipients"))
2431             ))
2432       (if (bufferp errbuf)
2433           (kill-buffer errbuf)))))
2434
2435 (defun message-send-news (&optional arg)
2436   (let ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2437         (case-fold-search nil)
2438         (method (if (message-functionp message-post-method)
2439                     (funcall message-post-method arg)
2440                   message-post-method))
2441         (message-syntax-checks
2442          (if arg
2443              (cons '(existing-newsgroups . disabled)
2444                    message-syntax-checks)
2445            message-syntax-checks))
2446         result)
2447     (save-restriction
2448       (message-narrow-to-headers)
2449       ;; Insert some headers.
2450       (message-generate-headers message-required-news-headers)
2451       ;; Let the user do all of the above.
2452       (run-hooks 'message-header-hook))
2453     (message-cleanup-headers)
2454     (if (not (message-check-news-syntax))
2455         (progn
2456           ;;(message "Posting not performed")
2457           nil)
2458       (unwind-protect
2459           (save-excursion
2460             (set-buffer tembuf)
2461             (buffer-disable-undo (current-buffer))
2462             (erase-buffer)
2463             (insert-buffer message-encoding-buffer)
2464             ;; Remove some headers.
2465             (save-restriction
2466               (message-narrow-to-headers)
2467               ;; Remove some headers.
2468               (message-remove-header message-ignored-news-headers t))
2469             (goto-char (point-max))
2470             ;; require one newline at the end.
2471             (or (= (preceding-char) ?\n)
2472                 (insert ?\n))
2473             (mime-edit-maybe-split-and-send
2474              (function
2475               (lambda ()
2476                 (interactive)
2477                 (save-restriction
2478                   (std11-narrow-to-header mail-header-separator)
2479                   (goto-char (point-min))
2480                   (when (re-search-forward "^Message-Id:" nil t)
2481                     (delete-region (match-end 0)(std11-field-end))
2482                     (insert (concat " " (message-make-message-id)))
2483                     ))
2484                 (funcall message-send-news-function method)
2485                 )))
2486             (setq result (funcall message-send-news-function method)))
2487         (kill-buffer tembuf))
2488       (set-buffer message-edit-buffer)
2489       (if result
2490           (push 'news message-sent-message-via)
2491         (message "Couldn't send message via news: %s"
2492                  (nnheader-get-report (car method)))
2493         nil))))
2494
2495 ;; 1997-09-29 by MORIOKA Tomohiko
2496 (defun message-send-news-with-gnus (method)
2497   (let ((case-fold-search t))
2498     ;; Remove the delimiter.
2499     (goto-char (point-min))
2500     (re-search-forward
2501      (concat "^" (regexp-quote mail-header-separator) "\n"))
2502     (replace-match "\n")
2503     (backward-char 1)
2504     (run-hooks 'message-send-news-hook)
2505     ;;(require (car method))
2506     ;;(funcall (intern (format "%s-open-server" (car method)))
2507     ;;(cadr method) (cddr method))
2508     ;;(setq result
2509     ;;    (funcall (intern (format "%s-request-post" (car method)))
2510     ;;             (cadr method)))
2511     (gnus-open-server method)
2512     (gnus-request-post method)
2513     ))
2514
2515 ;;;
2516 ;;; Header generation & syntax checking.
2517 ;;;
2518
2519 (defmacro message-check (type &rest forms)
2520   "Eval FORMS if TYPE is to be checked."
2521   `(or (message-check-element ,type)
2522        (save-excursion
2523          ,@forms)))
2524
2525 (put 'message-check 'lisp-indent-function 1)
2526 (put 'message-check 'edebug-form-spec '(form body))
2527
2528 (defun message-check-element (type)
2529   "Returns non-nil if this type is not to be checked."
2530   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2531       t
2532     (let ((able (assq type message-syntax-checks)))
2533       (and (consp able)
2534            (eq (cdr able) 'disabled)))))
2535
2536 (defun message-check-news-syntax ()
2537   "Check the syntax of the message."
2538   (save-excursion
2539     (save-restriction
2540       (widen)
2541       (and
2542        ;; We narrow to the headers and check them first.
2543        (save-excursion
2544          (save-restriction
2545            (message-narrow-to-headers)
2546            (message-check-news-header-syntax)))
2547        ;; Check the body.
2548        (save-excursion
2549          (set-buffer message-edit-buffer)
2550          (message-check-news-body-syntax))))))
2551
2552 (defun message-check-news-header-syntax ()
2553   (and
2554    ;; Check the Subject header.
2555    (message-check 'subject
2556      (let* ((case-fold-search t)
2557             (subject (message-fetch-field "subject")))
2558        (or
2559         (and subject
2560              (not (string-match "\\`[ \t]*\\'" subject)))
2561         (ignore
2562          (message
2563           "The subject field is empty or missing.  Posting is denied.")))))
2564    ;; Check for commands in Subject.
2565    (message-check 'subject-cmsg
2566      (if (string-match "^cmsg " (message-fetch-field "subject"))
2567          (y-or-n-p
2568           "The control code \"cmsg\" is in the subject.  Really post? ")
2569        t))
2570    ;; Check for multiple identical headers.
2571    (message-check 'multiple-headers
2572      (let (found)
2573        (while (and (not found)
2574                    (re-search-forward "^[^ \t:]+: " nil t))
2575          (save-excursion
2576            (or (re-search-forward
2577                 (concat "^"
2578                         (regexp-quote
2579                          (setq found
2580                                (buffer-substring
2581                                 (match-beginning 0) (- (match-end 0) 2))))
2582                         ":")
2583                 nil t)
2584                (setq found nil))))
2585        (if found
2586            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2587          t)))
2588    ;; Check for Version and Sendsys.
2589    (message-check 'sendsys
2590      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2591          (y-or-n-p
2592           (format "The article contains a %s command.  Really post? "
2593                   (buffer-substring (match-beginning 0)
2594                                     (1- (match-end 0)))))
2595        t))
2596    ;; See whether we can shorten Followup-To.
2597    (message-check 'shorten-followup-to
2598      (let ((newsgroups (message-fetch-field "newsgroups"))
2599            (followup-to (message-fetch-field "followup-to"))
2600            to)
2601        (when (and newsgroups
2602                   (string-match "," newsgroups)
2603                   (not followup-to)
2604                   (not
2605                    (zerop
2606                     (length
2607                      (setq to (completing-read
2608                                "Followups to: (default all groups) "
2609                                (mapcar (lambda (g) (list g))
2610                                        (cons "poster"
2611                                              (message-tokenize-header
2612                                               newsgroups)))))))))
2613          (goto-char (point-min))
2614          (insert "Followup-To: " to "\n"))
2615        t))
2616    ;; Check "Shoot me".
2617    (message-check 'shoot
2618      (if (re-search-forward
2619           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2620          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2621        t))
2622    ;; Check for Approved.
2623    (message-check 'approved
2624      (if (re-search-forward "^Approved:" nil t)
2625          (y-or-n-p "The article contains an Approved header.  Really post? ")
2626        t))
2627    ;; Check the Message-ID header.
2628    (message-check 'message-id
2629      (let* ((case-fold-search t)
2630             (message-id (message-fetch-field "message-id" t)))
2631        (or (not message-id)
2632            ;; Is there an @ in the ID?
2633            (and (string-match "@" message-id)
2634                 ;; Is there a dot in the ID?
2635                 (string-match "@[^.]*\\." message-id)
2636                 ;; Does the ID end with a dot?
2637                 (not (string-match "\\.>" message-id)))
2638            (y-or-n-p
2639             (format "The Message-ID looks strange: \"%s\".  Really post? "
2640                     message-id)))))
2641    ;; Check the Newsgroups & Followup-To headers.
2642    (message-check 'existing-newsgroups
2643      (let* ((case-fold-search t)
2644             (newsgroups (message-fetch-field "newsgroups"))
2645             (followup-to (message-fetch-field "followup-to"))
2646             (groups (message-tokenize-header
2647                      (if followup-to
2648                          (concat newsgroups "," followup-to)
2649                        newsgroups)))
2650             (hashtb (and (boundp 'gnus-active-hashtb)
2651                          gnus-active-hashtb))
2652             errors)
2653        (if (or (not hashtb)
2654                (not (boundp 'gnus-read-active-file))
2655                (not gnus-read-active-file)
2656                (eq gnus-read-active-file 'some))
2657            t
2658          (while groups
2659            (when (and (not (boundp (intern (car groups) hashtb)))
2660                       (not (equal (car groups) "poster")))
2661              (push (car groups) errors))
2662            (pop groups))
2663          (if (not errors)
2664              t
2665            (y-or-n-p
2666             (format
2667              "Really post to %s unknown group%s: %s "
2668              (if (= (length errors) 1) "this" "these")
2669              (if (= (length errors) 1) "" "s")
2670              (mapconcat 'identity errors ", ")))))))
2671    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2672    (message-check 'valid-newsgroups
2673      (let ((case-fold-search t)
2674            (headers '("Newsgroups" "Followup-To"))
2675            header error)
2676        (while (and headers (not error))
2677          (when (setq header (mail-fetch-field (car headers)))
2678            (if (or
2679                 (not
2680                  (string-match
2681                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2682                   header))
2683                 (memq
2684                  nil (mapcar
2685                       (lambda (g)
2686                         (not (string-match "\\.\\'\\|\\.\\." g)))
2687                       (message-tokenize-header header ","))))
2688                (setq error t)))
2689          (unless error
2690            (pop headers)))
2691        (if (not error)
2692            t
2693          (y-or-n-p
2694           (format "The %s header looks odd: \"%s\".  Really post? "
2695                   (car headers) header)))))
2696    (message-check 'repeated-newsgroups
2697      (let ((case-fold-search t)
2698            (headers '("Newsgroups" "Followup-To"))
2699            header error groups group)
2700        (while (and headers
2701                    (not error))
2702          (when (setq header (mail-fetch-field (pop headers)))
2703            (setq groups (message-tokenize-header header ","))
2704            (while (setq group (pop groups))
2705              (when (member group groups)
2706                (setq error group
2707                      groups nil)))))
2708        (if (not error)
2709            t
2710          (y-or-n-p
2711           (format "Group %s is repeated in headers.  Really post? " error)))))
2712    ;; Check the From header.
2713    (message-check 'from
2714      (let* ((case-fold-search t)
2715             (from (message-fetch-field "from"))
2716             (ad (nth 1 (mail-extract-address-components from))))
2717        (cond
2718         ((not from)
2719          (message "There is no From line.  Posting is denied.")
2720          nil)
2721         ((or (not (string-match "@[^\\.]*\\." ad)) ;larsi@ifi
2722              (string-match "\\.\\." ad) ;larsi@ifi..uio
2723              (string-match "@\\." ad)   ;larsi@.ifi.uio
2724              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2725              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2726              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2727          (message
2728           "Denied posting -- the From looks strange: \"%s\"." from)
2729          nil)
2730         (t t))))))
2731
2732 (defun message-check-news-body-syntax ()
2733   (and
2734    ;; Check for long lines.
2735    (message-check 'long-lines
2736      (goto-char (point-min))
2737      (re-search-forward
2738       (concat "^" (regexp-quote mail-header-separator) "$"))
2739      (while (and
2740              (progn
2741                (end-of-line)
2742                (< (current-column) 80))
2743              (zerop (forward-line 1))))
2744      (or (bolp)
2745          (eobp)
2746          (y-or-n-p
2747           "You have lines longer than 79 characters.  Really post? ")))
2748    ;; Check whether the article is empty.
2749    (message-check 'empty
2750      (goto-char (point-min))
2751      (re-search-forward
2752       (concat "^" (regexp-quote mail-header-separator) "$"))
2753      (forward-line 1)
2754      (let ((b (point)))
2755        (goto-char (point-max))
2756        (re-search-backward message-signature-separator nil t)
2757        (beginning-of-line)
2758        (or (re-search-backward "[^ \n\t]" b t)
2759            (y-or-n-p "Empty article.  Really post? "))))
2760    ;; Check for control characters.
2761    (message-check 'control-chars
2762      (if (re-search-forward "[\000-\007\013\015-\037\200-\237]" nil t)
2763          (y-or-n-p
2764           "The article contains control characters.  Really post? ")
2765        t))
2766    ;; Check 8bit characters.
2767    (message-check '8bit
2768      (message-check-8bit))
2769    ;; Check excessive size.
2770    (message-check 'size
2771      (if (> (buffer-size) 60000)
2772          (y-or-n-p
2773           (format "The article is %d octets long.  Really post? "
2774                   (buffer-size)))
2775        t))
2776    ;; Check whether any new text has been added.
2777    (message-check 'new-text
2778      (or
2779       (not message-checksum)
2780       (not (eq (message-checksum) message-checksum))
2781       (y-or-n-p
2782        "It looks like no new text has been added.  Really post? ")))
2783    ;; Check the length of the signature.
2784    (message-check 'signature
2785      (goto-char (point-max))
2786      (if (or (not (re-search-backward message-signature-separator nil t))
2787              (search-forward message-forward-end-separator nil t))
2788          t
2789        (if (> (count-lines (point) (point-max)) 5)
2790            (y-or-n-p
2791             (format
2792              "Your .sig is %d lines; it should be max 4.  Really post? "
2793              (1- (count-lines (point) (point-max)))))
2794          t)))))
2795
2796 (defun message-check-mail-syntax ()
2797   "Check the syntax of the message."
2798   (save-excursion
2799     (save-restriction
2800       (widen)
2801       (and
2802        ;; We narrow to the headers and check them first.
2803        (save-excursion
2804          (save-restriction
2805            (message-narrow-to-headers)
2806            (message-check-mail-header-syntax)))
2807        ;; Check the body.
2808        (save-excursion
2809          (set-buffer message-edit-buffer)
2810          (message-check-mail-body-syntax))))))
2811
2812 (defun message-check-mail-header-syntax ()
2813   t)
2814
2815 (defun message-check-mail-body-syntax ()
2816   (and
2817    ;; Check 8bit characters.
2818    (message-check '8bit
2819      (message-check-8bit)
2820      )))
2821
2822 (defun message-check-8bit ()
2823   "Check the article contains 8bit characters."
2824   (save-excursion
2825     (set-buffer message-encoding-buffer)
2826     (message-narrow-to-headers)
2827     (let* ((case-fold-search t)
2828            (field-value (message-fetch-field "content-transfer-encoding")))
2829       (if (and field-value
2830                (member (downcase field-value) message-8bit-encoding-list))
2831           t
2832         (widen)
2833         (set-buffer (get-buffer-create " message syntax"))
2834         (erase-buffer)
2835         (goto-char (point-min))
2836         (set-buffer-multibyte nil)
2837         (insert-buffer message-encoding-buffer)
2838         (goto-char (point-min))
2839         (if (re-search-forward "[^\x00-\x7f]" nil t)
2840             (y-or-n-p
2841              "The article contains 8bit characters.  Really post? ")
2842           t)))))
2843
2844 (defun message-checksum ()
2845   "Return a \"checksum\" for the current buffer."
2846   (let ((sum 0))
2847     (save-excursion
2848       (goto-char (point-min))
2849       (re-search-forward
2850        (concat "^" (regexp-quote mail-header-separator) "$"))
2851       (while (not (eobp))
2852         (when (not (looking-at "[ \t\n]"))
2853           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
2854                             (following-char))))
2855         (forward-char 1)))
2856     sum))
2857
2858 (defun message-do-fcc ()
2859   "Process Fcc headers in the current buffer."
2860   (let ((case-fold-search t)
2861         (coding-system-for-write 'raw-text)
2862         list file)
2863     (save-excursion
2864       (set-buffer (get-buffer-create " *message temp*"))
2865       (buffer-disable-undo (current-buffer))
2866       (erase-buffer)
2867       (insert-buffer-substring message-encoding-buffer)
2868       (save-restriction
2869         (message-narrow-to-headers)
2870         (while (setq file (message-fetch-field "fcc"))
2871           (push file list)
2872           (message-remove-header "fcc" nil t)))
2873       (goto-char (point-min))
2874       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
2875       (replace-match "" t t)
2876       ;; Process FCC operations.
2877       (while list
2878         (setq file (pop list))
2879         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
2880             ;; Pipe the article to the program in question.
2881             (call-process-region (point-min) (point-max) shell-file-name
2882                                  nil nil nil shell-command-switch
2883                                  (match-string 1 file))
2884           ;; Save the article.
2885           (setq file (expand-file-name file))
2886           (unless (file-exists-p (file-name-directory file))
2887             (make-directory (file-name-directory file) t))
2888           (if (and message-fcc-handler-function
2889                    (not (eq message-fcc-handler-function 'rmail-output)))
2890               (funcall message-fcc-handler-function file)
2891             (if (and (file-readable-p file) (mail-file-babyl-p file))
2892                 (rmail-output file 1 nil t)
2893               (let ((mail-use-rfc822 t))
2894                 (rmail-output file 1 t t))))))
2895
2896       (kill-buffer (current-buffer)))))
2897
2898 (defun message-output (filename)
2899   "Append this article to Unix/babyl mail file.."
2900   (if (and (file-readable-p filename)
2901            (mail-file-babyl-p filename))
2902       (gnus-output-to-rmail filename t)
2903     (gnus-output-to-mail filename t)))
2904
2905 (defun message-cleanup-headers ()
2906   "Do various automatic cleanups of the headers."
2907   ;; Remove empty lines in the header.
2908   (save-restriction
2909     (message-narrow-to-headers)
2910     ;; Remove blank lines.
2911     (while (re-search-forward "^[ \t]*\n" nil t)
2912       (replace-match "" t t))
2913
2914     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
2915     ;; spaces to comma and eliminate spaces around commas.  Eliminate
2916     ;; embedded line breaks.
2917     (goto-char (point-min))
2918     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2919       (save-restriction
2920         (narrow-to-region
2921          (point)
2922          (if (re-search-forward "^[^ \t]" nil t)
2923              (match-beginning 0)
2924            (forward-line 1)
2925            (point)))
2926         (goto-char (point-min))
2927         (while (re-search-forward "\n[ \t]+" nil t)
2928           (replace-match " " t t))      ;No line breaks (too confusing)
2929         (goto-char (point-min))
2930         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
2931           (replace-match "," t t))
2932         (goto-char (point-min))
2933         ;; Remove trailing commas.
2934         (when (re-search-forward ",+$" nil t)
2935           (replace-match "" t t))))))
2936
2937 (defun message-make-date ()
2938   "Make a valid data header."
2939   (let ((now (current-time)))
2940     (timezone-make-date-arpa-standard
2941      (current-time-string now) (current-time-zone now))))
2942
2943 (defun message-make-message-id ()
2944   "Make a unique Message-ID."
2945   (concat "<" (message-unique-id)
2946           (let ((psubject (save-excursion (message-fetch-field "subject")))
2947                 (psupersedes
2948                  (save-excursion (message-fetch-field "supersedes"))))
2949             (if (or
2950                  (and message-reply-headers
2951                       (mail-header-references message-reply-headers)
2952                       (mail-header-subject message-reply-headers)
2953                       psubject
2954                       (mail-header-subject message-reply-headers)
2955                       (not (string=
2956                             (message-strip-subject-re
2957                              (mail-header-subject message-reply-headers))
2958                             (message-strip-subject-re psubject))))
2959                  (and psupersedes
2960                       (string-match "_-_@" psupersedes)))
2961                 "_-_" ""))
2962           "@" (message-make-fqdn) ">"))
2963
2964 (defvar message-unique-id-char nil)
2965
2966 ;; If you ever change this function, make sure the new version
2967 ;; cannot generate IDs that the old version could.
2968 ;; You might for example insert a "." somewhere (not next to another dot
2969 ;; or string boundary), or modify the "fsf" string.
2970 (defun message-unique-id ()
2971   ;; Don't use microseconds from (current-time), they may be unsupported.
2972   ;; Instead we use this randomly inited counter.
2973   (setq message-unique-id-char
2974         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2975            ;; (current-time) returns 16-bit ints,
2976            ;; and 2^16*25 just fits into 4 digits i base 36.
2977            (* 25 25)))
2978   (let ((tm (current-time)))
2979     (concat
2980      (if (memq system-type '(ms-dos emx vax-vms))
2981          (let ((user (downcase (user-login-name))))
2982            (while (string-match "[^a-z0-9_]" user)
2983              (aset user (match-beginning 0) ?_))
2984            user)
2985        (message-number-base36 (user-uid) -1))
2986      (message-number-base36 (+ (car   tm)
2987                                (lsh (% message-unique-id-char 25) 16)) 4)
2988      (message-number-base36 (+ (nth 1 tm)
2989                                (lsh (/ message-unique-id-char 25) 16)) 4)
2990      ;; Append the newsreader name, because while the generated
2991      ;; ID is unique to this newsreader, other newsreaders might
2992      ;; otherwise generate the same ID via another algorithm.
2993      ".fsf")))
2994
2995 (defun message-number-base36 (num len)
2996   (if (if (< len 0)
2997           (<= num 0)
2998         (= len 0))
2999       ""
3000     (concat (message-number-base36 (/ num 36) (1- len))
3001             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
3002                                   (% num 36))))))
3003
3004 (defun message-make-organization ()
3005   "Make an Organization header."
3006   (let* ((organization
3007           (when message-user-organization
3008                 (if (message-functionp message-user-organization)
3009                     (funcall message-user-organization)
3010                   message-user-organization))))
3011     (save-excursion
3012       (message-set-work-buffer)
3013       (cond ((stringp organization)
3014              (insert organization))
3015             ((and (eq t organization)
3016                   message-user-organization-file
3017                   (file-exists-p message-user-organization-file))
3018              (insert-file-contents message-user-organization-file)))
3019       (goto-char (point-min))
3020       (while (re-search-forward "[\t\n]+" nil t)
3021         (replace-match "" t t))
3022       (unless (zerop (buffer-size))
3023         (buffer-string)))))
3024
3025 (defun message-make-lines ()
3026   "Count the number of lines and return numeric string."
3027   (save-excursion
3028     (save-restriction
3029       (widen)
3030       (goto-char (point-min))
3031       (re-search-forward
3032        (concat "^" (regexp-quote mail-header-separator) "$"))
3033       (forward-line 1)
3034       (int-to-string (count-lines (point) (point-max))))))
3035
3036 (defun message-make-in-reply-to ()
3037   "Return the In-Reply-To header for this message."
3038   (when message-reply-headers
3039     (let ((from (mail-header-from message-reply-headers))
3040           (date (mail-header-date message-reply-headers))
3041           (msg-id (mail-header-message-id message-reply-headers)))
3042       (when msg-id
3043         (concat msg-id
3044                 (when from
3045                   (let ((stop-pos
3046                          (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
3047                     (concat " ("
3048                             (if (and stop-pos
3049                                      (not (zerop stop-pos)))
3050                                 (substring from 0 stop-pos) from)
3051                             "'s message of \""
3052                             (if (or (not date) (string= date ""))
3053                                 "(unknown date)" date)
3054                             "\")"))))))))
3055
3056 (defun message-make-distribution ()
3057   "Make a Distribution header."
3058   (let ((orig-distribution (message-fetch-reply-field "distribution")))
3059     (cond ((message-functionp message-distribution-function)
3060            (funcall message-distribution-function))
3061           (t orig-distribution))))
3062
3063 (defun message-make-expires ()
3064   "Return an Expires header based on `message-expires'."
3065   (let ((current (current-time))
3066         (future (* 1.0 message-expires 60 60 24)))
3067     ;; Add the future to current.
3068     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
3069     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
3070     ;; Return the date in the future in UT.
3071     (timezone-make-date-arpa-standard
3072      (current-time-string current) (current-time-zone current) '(0 "UT"))))
3073
3074 (defun message-make-path ()
3075   "Return uucp path."
3076   (let ((login-name (user-login-name)))
3077     (cond ((null message-user-path)
3078            (concat (system-name) "!" login-name))
3079           ((stringp message-user-path)
3080            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
3081            (concat message-user-path "!" login-name))
3082           (t login-name))))
3083
3084 (defun message-make-from ()
3085   "Make a From header."
3086   (let* ((style message-from-style)
3087          (login (message-make-address))
3088          (fullname
3089           (or (and (boundp 'user-full-name)
3090                    user-full-name)
3091               (user-full-name))))
3092     (when (string= fullname "&")
3093       (setq fullname (user-login-name)))
3094     (save-excursion
3095       (message-set-work-buffer)
3096       (cond
3097        ((or (null style)
3098             (equal fullname ""))
3099         (insert login))
3100        ((or (eq style 'angles)
3101             (and (not (eq style 'parens))
3102                  ;; Use angles if no quoting is needed, or if parens would
3103                  ;; need quoting too.
3104                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
3105                      (let ((tmp (concat fullname nil)))
3106                        (while (string-match "([^()]*)" tmp)
3107                          (aset tmp (match-beginning 0) ?-)
3108                          (aset tmp (1- (match-end 0)) ?-))
3109                        (string-match "[\\()]" tmp)))))
3110         (insert fullname)
3111         (goto-char (point-min))
3112         ;; Look for a character that cannot appear unquoted
3113         ;; according to RFC 822.
3114         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
3115           ;; Quote fullname, escaping specials.
3116           (goto-char (point-min))
3117           (insert "\"")
3118           (while (re-search-forward "[\"\\]" nil 1)
3119             (replace-match "\\\\\\&" t))
3120           (insert "\""))
3121         (insert " <" login ">"))
3122        (t                               ; 'parens or default
3123         (insert login " (")
3124         (let ((fullname-start (point)))
3125           (insert fullname)
3126           (goto-char fullname-start)
3127           ;; RFC 822 says \ and nonmatching parentheses
3128           ;; must be escaped in comments.
3129           ;; Escape every instance of ()\ ...
3130           (while (re-search-forward "[()\\]" nil 1)
3131             (replace-match "\\\\\\&" t))
3132           ;; ... then undo escaping of matching parentheses,
3133           ;; including matching nested parentheses.
3134           (goto-char fullname-start)
3135           (while (re-search-forward
3136                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3137                   nil 1)
3138             (replace-match "\\1(\\3)" t)
3139             (goto-char fullname-start)))
3140         (insert ")")))
3141       (buffer-string))))
3142
3143 (defun message-make-sender ()
3144   "Return the \"real\" user address.
3145 This function tries to ignore all user modifications, and
3146 give as trustworthy answer as possible."
3147   (concat (user-login-name) "@" (system-name)))
3148
3149 (defun message-make-address ()
3150   "Make the address of the user."
3151   (or (message-user-mail-address)
3152       (concat (user-login-name) "@" (message-make-domain))))
3153
3154 (defun message-user-mail-address ()
3155   "Return the pertinent part of `user-mail-address'."
3156   (when user-mail-address
3157     (if (string-match " " user-mail-address)
3158         (nth 1 (mail-extract-address-components user-mail-address))
3159       user-mail-address)))
3160
3161 (defun message-make-fqdn ()
3162   "Return user's fully qualified domain name."
3163   (let ((system-name (system-name))
3164         (user-mail (message-user-mail-address)))
3165     (cond
3166      ((string-match "[^.]\\.[^.]" system-name)
3167       ;; `system-name' returned the right result.
3168       system-name)
3169      ;; Try `mail-host-address'.
3170      ((and (boundp 'mail-host-address)
3171            (stringp mail-host-address)
3172            (string-match "\\." mail-host-address))
3173       mail-host-address)
3174      ;; We try `user-mail-address' as a backup.
3175      ((and user-mail
3176            (string-match "\\." user-mail)
3177            (string-match "@\\(.*\\)\\'" user-mail))
3178       (match-string 1 user-mail))
3179      ;; Default to this bogus thing.
3180      (t
3181       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
3182
3183 (defun message-make-host-name ()
3184   "Return the name of the host."
3185   (let ((fqdn (message-make-fqdn)))
3186     (string-match "^[^.]+\\." fqdn)
3187     (substring fqdn 0 (1- (match-end 0)))))
3188
3189 (defun message-make-domain ()
3190   "Return the domain name."
3191   (or mail-host-address
3192       (message-make-fqdn)))
3193
3194 (defun message-make-user-agent ()
3195   "Return user-agent info."
3196   (if message-user-agent
3197       (save-excursion
3198         (goto-char (point-min))
3199         (let ((case-fold-search t)
3200               user-agent beg p end)
3201           (if (re-search-forward "^User-Agent:[ \t]*" nil t)
3202               (progn
3203                 (setq beg (match-beginning 0)
3204                       p (match-end 0)
3205                       end (std11-field-end)
3206                       user-agent (buffer-substring p end))
3207                 (delete-region beg (1+ end))
3208                 (concat message-user-agent " " user-agent)
3209                 )
3210             message-user-agent)))))
3211
3212 (defun message-generate-headers (headers)
3213   "Prepare article HEADERS.
3214 Headers already prepared in the buffer are not modified."
3215   (save-restriction
3216     (message-narrow-to-headers)
3217     (let* ((Date (message-make-date))
3218            (Message-ID (message-make-message-id))
3219            (Organization (message-make-organization))
3220            (From (message-make-from))
3221            (Path (message-make-path))
3222            (Subject nil)
3223            (Newsgroups nil)
3224            (In-Reply-To (message-make-in-reply-to))
3225            (To nil)
3226            (Distribution (message-make-distribution))
3227            (Lines (message-make-lines))
3228            (User-Agent (message-make-user-agent))
3229            (Expires (message-make-expires))
3230            (case-fold-search t)
3231            header value elem)
3232       ;; First we remove any old generated headers.
3233       (let ((headers message-deletable-headers))
3234         (unless (buffer-modified-p)
3235           (setq headers (delq 'Message-ID (copy-sequence headers))))
3236         (while headers
3237           (goto-char (point-min))
3238           (and (re-search-forward
3239                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3240                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3241                (message-delete-line))
3242           (pop headers)))
3243       ;; Go through all the required headers and see if they are in the
3244       ;; articles already.  If they are not, or are empty, they are
3245       ;; inserted automatically - except for Subject, Newsgroups and
3246       ;; Distribution.
3247       (while headers
3248         (goto-char (point-min))
3249         (setq elem (pop headers))
3250         (if (consp elem)
3251             (if (eq (car elem) 'optional)
3252                 (setq header (cdr elem))
3253               (setq header (car elem)))
3254           (setq header elem))
3255         (when (or (not (re-search-forward
3256                         (concat "^"
3257                                 (regexp-quote
3258                                  (downcase
3259                                   (if (stringp header)
3260                                       header
3261                                     (symbol-name header))))
3262                                 ":")
3263                         nil t))
3264                   (progn
3265                     ;; The header was found.  We insert a space after the
3266                     ;; colon, if there is none.
3267                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
3268                     ;; Find out whether the header is empty...
3269                     (looking-at "[ \t]*$")))
3270           ;; So we find out what value we should insert.
3271           (setq value
3272                 (cond
3273                  ((and (consp elem) (eq (car elem) 'optional))
3274                   ;; This is an optional header.  If the cdr of this
3275                   ;; is something that is nil, then we do not insert
3276                   ;; this header.
3277                   (setq header (cdr elem))
3278                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3279                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3280                  ((consp elem)
3281                   ;; The element is a cons.  Either the cdr is a
3282                   ;; string to be inserted verbatim, or it is a
3283                   ;; function, and we insert the value returned from
3284                   ;; this function.
3285                   (or (and (stringp (cdr elem)) (cdr elem))
3286                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3287                  ((and (boundp header) (symbol-value header))
3288                   ;; The element is a symbol.  We insert the value
3289                   ;; of this symbol, if any.
3290                   (symbol-value header))
3291                  (t
3292                   ;; We couldn't generate a value for this header,
3293                   ;; so we just ask the user.
3294                   (read-from-minibuffer
3295                    (format "Empty header for %s; enter value: " header)))))
3296           ;; Finally insert the header.
3297           (when (and value
3298                      (not (equal value "")))
3299             (save-excursion
3300               (if (bolp)
3301                   (progn
3302                     ;; This header didn't exist, so we insert it.
3303                     (goto-char (point-max))
3304                     (insert (if (stringp header) header (symbol-name header))
3305                             ": " value "\n")
3306                     (forward-line -1))
3307                 ;; The value of this header was empty, so we clear
3308                 ;; totally and insert the new value.
3309                 (delete-region (point) (gnus-point-at-eol))
3310                 (insert value))
3311               ;; Add the deletable property to the headers that require it.
3312               (and (memq header message-deletable-headers)
3313                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3314                    (add-text-properties
3315                     (point) (match-end 0)
3316                     '(message-deletable t face italic) (current-buffer)))))))
3317       ;; Insert new Sender if the From is strange.
3318       (let ((from (message-fetch-field "from"))
3319             (sender (message-fetch-field "sender"))
3320             (secure-sender (message-make-sender)))
3321         (when (and from
3322                    (not (message-check-element 'sender))
3323                    (not (string=
3324                          (downcase
3325                           (cadr (mail-extract-address-components from)))
3326                          (downcase secure-sender)))
3327                    (or (null sender)
3328                        (not
3329                         (string=
3330                          (downcase
3331                           (cadr (mail-extract-address-components sender)))
3332                          (downcase secure-sender)))))
3333           (goto-char (point-min))
3334           ;; Rename any old Sender headers to Original-Sender.
3335           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3336             (beginning-of-line)
3337             (insert "Original-")
3338             (beginning-of-line))
3339           (when (or (message-news-p)
3340                     (string-match "@.+\\.." secure-sender))
3341             (insert "Sender: " secure-sender "\n")))))))
3342
3343 (defun message-insert-courtesy-copy ()
3344   "Insert a courtesy message in mail copies of combined messages."
3345   (let (newsgroups)
3346     (save-excursion
3347       (save-restriction
3348         (message-narrow-to-headers)
3349         (when (setq newsgroups (message-fetch-field "newsgroups"))
3350           (goto-char (point-max))
3351           (insert "Posted-To: " newsgroups "\n")))
3352       (forward-line 1)
3353       (when message-courtesy-message
3354         (cond
3355          ((string-match "%s" message-courtesy-message)
3356           (insert (format message-courtesy-message newsgroups)))
3357          (t
3358           (insert message-courtesy-message)))))))
3359
3360 ;;;
3361 ;;; Setting up a message buffer
3362 ;;;
3363
3364 (defun message-fill-address (header value)
3365   (save-restriction
3366     (narrow-to-region (point) (point))
3367     (insert (capitalize (symbol-name header))
3368             ": "
3369             (if (consp value) (car value) value)
3370             "\n")
3371     (narrow-to-region (point-min) (1- (point-max)))
3372     (let (quoted last)
3373       (goto-char (point-min))
3374       (while (not (eobp))
3375         (skip-chars-forward "^,\"" (point-max))
3376         (if (or (= (following-char) ?,)
3377                 (eobp))
3378             (when (not quoted)
3379               (if (and (> (current-column) 78)
3380                        last)
3381                   (progn
3382                     (save-excursion
3383                       (goto-char last)
3384                       (insert "\n\t"))
3385                     (setq last (1+ (point))))
3386                 (setq last (1+ (point)))))
3387           (setq quoted (not quoted)))
3388         (unless (eobp)
3389           (forward-char 1))))
3390     (goto-char (point-max))
3391     (widen)
3392     (forward-line 1)))
3393
3394 (defun message-fill-references (header value)
3395   (insert (capitalize (symbol-name header))
3396           ": "
3397           (std11-fill-msg-id-list-string
3398            (if (consp value) (car value) value))
3399           "\n"))
3400
3401 (defun message-fill-header (header value)
3402   (let ((begin (point))
3403         (fill-column 990)
3404         (fill-prefix "\t"))
3405     (insert (capitalize (symbol-name header))
3406             ": "
3407             (if (consp value) (car value) value)
3408             "\n")
3409     (save-restriction
3410       (narrow-to-region begin (point))
3411       (fill-region-as-paragraph begin (point))
3412       ;; Tapdance around looong Message-IDs.
3413       (forward-line -1)
3414       (when (looking-at "[ \t]*$")
3415         (message-delete-line))
3416       (goto-char begin)
3417       (re-search-forward ":" nil t)
3418       (when (looking-at "\n[ \t]+")
3419         (replace-match " " t t))
3420       (goto-char (point-max)))))
3421
3422 (defun message-shorten-references (header references)
3423   "Limit REFERENCES to be shorter than 988 characters."
3424   (let ((max 988)
3425         (cut 4)
3426         refs)
3427     (nnheader-temp-write nil
3428       (insert references)
3429       (goto-char (point-min))
3430       (while (re-search-forward "<[^>]+>" nil t)
3431         (push (match-string 0) refs))
3432       (setq refs (nreverse refs))
3433       (while (> (length (mapconcat 'identity refs " ")) max)
3434         (when (< (length refs) (1+ cut))
3435           (decf cut))
3436         (setcdr (nthcdr cut refs) (cddr (nthcdr cut refs)))))
3437     (insert (capitalize (symbol-name header)) ": "
3438             (mapconcat 'identity refs " ") "\n")))
3439
3440 (defun message-position-point ()
3441   "Move point to where the user probably wants to find it."
3442   (message-narrow-to-headers)
3443   (cond
3444    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3445     (search-backward ":" )
3446     (widen)
3447     (forward-char 1)
3448     (if (= (following-char) ? )
3449         (forward-char 1)
3450       (insert " ")))
3451    (t
3452     (goto-char (point-max))
3453     (widen)
3454     (forward-line 1)
3455     (unless (looking-at "$")
3456       (forward-line 2)))
3457    (sit-for 0)))
3458
3459 (defun message-buffer-name (type &optional to group)
3460   "Return a new (unique) buffer name based on TYPE and TO."
3461   (cond
3462    ;; Check whether `message-generate-new-buffers' is a function,
3463    ;; and if so, call it.
3464    ((message-functionp message-generate-new-buffers)
3465     (funcall message-generate-new-buffers type to group))
3466    ;; Generate a new buffer name The Message Way.
3467    (message-generate-new-buffers
3468     (generate-new-buffer-name
3469      (concat "*" type
3470              (if to
3471                  (concat " to "
3472                          (or (car (mail-extract-address-components to))
3473                              to) "")
3474                "")
3475              (if (and group (not (string= group ""))) (concat " on " group) "")
3476              "*")))
3477    ;; Use standard name.
3478    (t
3479     (format "*%s message*" type))))
3480
3481 (defun message-pop-to-buffer (name)
3482   "Pop to buffer NAME, and warn if it already exists and is modified."
3483   (let ((pop-up-frames pop-up-frames)
3484         (special-display-buffer-names special-display-buffer-names)
3485         (special-display-regexps special-display-regexps)
3486         (same-window-buffer-names same-window-buffer-names)
3487         (same-window-regexps same-window-regexps)
3488         (buffer (get-buffer name))
3489         (cur (current-buffer)))
3490     (if (or (and (featurep 'xemacs)
3491                  (not (eq 'tty (device-type))))
3492             window-system
3493             (>= emacs-major-version 20))
3494         (when message-use-multi-frames
3495           (setq pop-up-frames t
3496                 special-display-buffer-names nil
3497                 special-display-regexps nil
3498                 same-window-buffer-names nil
3499                 same-window-regexps nil))
3500       (setq pop-up-frames nil))
3501     (if (and buffer
3502              (buffer-name buffer))
3503         (progn
3504           (set-buffer (pop-to-buffer buffer))
3505           (when (and (buffer-modified-p)
3506                      (not (y-or-n-p
3507                            "Message already being composed; erase? ")))
3508             (error "Message being composed")))
3509       (set-buffer (pop-to-buffer name)))
3510     (erase-buffer)
3511     (message-mode)
3512     (when pop-up-frames
3513       (make-local-variable 'message-original-frame)
3514       (setq message-original-frame (selected-frame)))))
3515
3516 (defun message-do-send-housekeeping ()
3517   "Kill old message buffers."
3518   ;; We might have sent this buffer already.  Delete it from the
3519   ;; list of buffers.
3520   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3521   (while (and message-max-buffers
3522               message-buffer-list
3523               (>= (length message-buffer-list) message-max-buffers))
3524     ;; Kill the oldest buffer -- unless it has been changed.
3525     (let ((buffer (pop message-buffer-list)))
3526       (when (and (buffer-name buffer)
3527                  (not (buffer-modified-p buffer)))
3528         (kill-buffer buffer))))
3529   ;; Rename the buffer.
3530   (if message-send-rename-function
3531       (funcall message-send-rename-function)
3532     (when (string-match "\\`\\*" (buffer-name))
3533       (rename-buffer
3534        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3535   ;; Push the current buffer onto the list.
3536   (when message-max-buffers
3537     (setq message-buffer-list
3538           (nconc message-buffer-list (list (current-buffer))))))
3539
3540 (defvar mc-modes-alist)
3541 (defun message-setup (headers &optional replybuffer actions)
3542   (when (and (boundp 'mc-modes-alist)
3543              (not (assq 'message-mode mc-modes-alist)))
3544     (push '(message-mode (encrypt . mc-encrypt-message)
3545                          (sign . mc-sign-message))
3546           mc-modes-alist))
3547   (when actions
3548     (setq message-send-actions actions))
3549   (setq message-reply-buffer
3550         (or (cdr (assq 'reply-buffer message-parameter-alist))
3551             replybuffer))
3552   (goto-char (point-min))
3553   ;; Insert all the headers.
3554   (mail-header-format
3555    (let ((h headers)
3556          (alist message-header-format-alist))
3557      (while h
3558        (unless (assq (caar h) message-header-format-alist)
3559          (push (list (caar h)) alist))
3560        (pop h))
3561      alist)
3562    headers)
3563   (delete-region (point) (progn (forward-line -1) (point)))
3564   (when message-default-headers
3565     (insert message-default-headers)
3566     (or (bolp) (insert ?\n)))
3567   (put-text-property
3568    (point)
3569    (progn
3570      (insert mail-header-separator "\n")
3571      (1- (point)))
3572    'read-only nil)
3573   (forward-line -1)
3574   (when (message-news-p)
3575     (when message-default-news-headers
3576       (insert message-default-news-headers)
3577       (or (bolp) (insert ?\n)))
3578     (when message-generate-headers-first
3579       (message-generate-headers
3580        (delq 'Lines
3581              (delq 'Subject
3582                    (copy-sequence message-required-news-headers))))))
3583   (when (message-mail-p)
3584     (when message-default-mail-headers
3585       (insert message-default-mail-headers)
3586       (or (bolp) (insert ?\n)))
3587     (when message-generate-headers-first
3588       (message-generate-headers
3589        (delq 'Lines
3590              (delq 'Subject
3591                    (copy-sequence message-required-mail-headers))))))
3592   (run-hooks 'message-signature-setup-hook)
3593   (message-insert-signature)
3594   (save-restriction
3595     (message-narrow-to-headers)
3596     (run-hooks 'message-header-setup-hook))
3597   (set-buffer-modified-p nil)
3598   (setq buffer-undo-list nil)
3599   (run-hooks 'message-setup-hook)
3600   (message-position-point)
3601   (undo-boundary))
3602
3603 (defun message-set-auto-save-file-name ()
3604   "Associate the message buffer with a file in the drafts directory."
3605   (when message-autosave-directory
3606     (if (gnus-alive-p)
3607         (setq message-draft-article
3608               (nndraft-request-associate-buffer "drafts"))
3609       (setq buffer-file-name (expand-file-name "*message*"
3610                                                message-autosave-directory))
3611       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
3612     (clear-visited-file-modtime)))
3613
3614 (defun message-disassociate-draft ()
3615   "Disassociate the message buffer from the drafts directory."
3616   (when message-draft-article
3617     (nndraft-request-expire-articles
3618      (list message-draft-article) "drafts" nil t)))
3619
3620 \f
3621
3622 ;;;
3623 ;;; Commands for interfacing with message
3624 ;;;
3625
3626 ;;;###autoload
3627 (defun message-mail (&optional to subject
3628                                other-headers continue switch-function
3629                                yank-action send-actions)
3630   "Start editing a mail message to be sent.
3631 OTHER-HEADERS is an alist of header/value pairs."
3632   (interactive)
3633   (let ((message-this-is-mail t))
3634     (message-pop-to-buffer (message-buffer-name "mail" to))
3635     (message-setup
3636      (nconc
3637       `((To . ,(or to "")) (Subject . ,(or subject "")))
3638       (when other-headers other-headers)))))
3639
3640 ;;;###autoload
3641 (defun message-news (&optional newsgroups subject)
3642   "Start editing a news article to be sent."
3643   (interactive)
3644   (let ((message-this-is-news t))
3645     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3646     (message-setup `((Newsgroups . ,(or newsgroups ""))
3647                      (Subject . ,(or subject ""))))))
3648
3649 ;;;###autoload
3650 (defun message-reply (&optional to-address wide)
3651   "Start editing a reply to the article in the current buffer."
3652   (interactive)
3653   (let ((cur (current-buffer))
3654         from subject date reply-to to cc
3655         references message-id follow-to
3656         (inhibit-point-motion-hooks t)
3657         mct never-mct gnus-warning)
3658     (save-restriction
3659       (message-narrow-to-head)
3660       ;; Allow customizations to have their say.
3661       (if (not wide)
3662           ;; This is a regular reply.
3663           (if (message-functionp message-reply-to-function)
3664               (setq follow-to (funcall message-reply-to-function)))
3665         ;; This is a followup.
3666         (if (message-functionp message-wide-reply-to-function)
3667             (save-excursion
3668               (setq follow-to
3669                     (funcall message-wide-reply-to-function)))))
3670       ;; Find all relevant headers we need.
3671       (setq from (message-fetch-field "from")
3672             date (message-fetch-field "date")
3673             subject (or (message-fetch-field "subject") "none")
3674             to (message-fetch-field "to")
3675             cc (message-fetch-field "cc")
3676             mct (message-fetch-field "mail-copies-to")
3677             reply-to (message-fetch-field "reply-to")
3678             references (message-fetch-field "references")
3679             message-id (message-fetch-field "message-id" t))
3680       ;; Remove any (buggy) Re:'s that are present and make a
3681       ;; proper one.
3682       (when (string-match message-subject-re-regexp subject)
3683         (setq subject (substring subject (match-end 0))))
3684       (setq subject (concat "Re: " subject))
3685
3686       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3687                  (string-match "<[^>]+>" gnus-warning))
3688         (setq message-id (match-string 0 gnus-warning)))
3689
3690       ;; Handle special values of Mail-Copies-To.
3691       (when mct
3692         (cond ((equal (downcase mct) "never")
3693                (setq never-mct t)
3694                (setq mct nil))
3695               ((equal (downcase mct) "always")
3696                (setq mct (or reply-to from)))))
3697
3698       (unless follow-to
3699         (if (or (not wide)
3700                 to-address)
3701             (progn
3702               (setq follow-to (list (cons 'To (or to-address reply-to from))))
3703               (when (and wide mct)
3704                 (push (cons 'Cc mct) follow-to)))
3705           (let (ccalist)
3706             (save-excursion
3707               (message-set-work-buffer)
3708               (unless never-mct
3709                 (insert (or reply-to from "")))
3710               (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3711               (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3712               (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
3713               (goto-char (point-min))
3714               (while (re-search-forward "[ \t]+" nil t)
3715                 (replace-match " " t t))
3716               ;; Remove addresses that match `rmail-dont-reply-to-names'.
3717               (insert (prog1 (rmail-dont-reply-to (buffer-string))
3718                         (erase-buffer)))
3719               (goto-char (point-min))
3720               ;; Perhaps Mail-Copies-To: never removed the only address?
3721               (when (eobp)
3722                 (insert (or reply-to from "")))
3723               (setq ccalist
3724                     (mapcar
3725                      (lambda (addr)
3726                        (cons (mail-strip-quoted-names addr) addr))
3727                      (message-tokenize-header (buffer-string))))
3728               (let ((s ccalist))
3729                 (while s
3730                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3731             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3732             (when ccalist
3733               (let ((ccs (cons 'Cc (mapconcat
3734                                     (lambda (addr) (cdr addr)) ccalist ", "))))
3735                 (when (string-match "^ +" (cdr ccs))
3736                   (setcdr ccs (substring (cdr ccs) (match-end 0))))
3737                 (push ccs follow-to))))))
3738       (widen))
3739
3740     (message-pop-to-buffer (message-buffer-name
3741                             (if wide "wide reply" "reply") from
3742                             (if wide to-address nil)))
3743
3744     (setq message-reply-headers
3745           (vector 0 subject from date message-id references 0 0 ""))
3746
3747     (message-setup
3748      `((Subject . ,subject)
3749        ,@follow-to
3750        ,@(if (or references message-id)
3751              `((References . ,(concat (or references "") (and references " ")
3752                                       (or message-id ""))))
3753            nil))
3754      cur)))
3755
3756 ;;;###autoload
3757 (defun message-wide-reply (&optional to-address)
3758   "Make a \"wide\" reply to the message in the current buffer."
3759   (interactive)
3760   (message-reply to-address t))
3761
3762 ;;;###autoload
3763 (defun message-followup (&optional to-newsgroups)
3764   "Follow up to the message in the current buffer.
3765 If TO-NEWSGROUPS, use that as the new Newsgroups line."
3766   (interactive)
3767   (let ((cur (current-buffer))
3768         from subject date reply-to mct
3769         references message-id follow-to
3770         (inhibit-point-motion-hooks t)
3771         (message-this-is-news t)
3772         followup-to distribution newsgroups gnus-warning posted-to)
3773     (save-restriction
3774       (narrow-to-region
3775        (goto-char (point-min))
3776        (if (search-forward "\n\n" nil t)
3777            (1- (point))
3778          (point-max)))
3779       (when (message-functionp message-followup-to-function)
3780         (setq follow-to
3781               (funcall message-followup-to-function)))
3782       (setq from (message-fetch-field "from")
3783             date (message-fetch-field "date")
3784             subject (or (message-fetch-field "subject") "none")
3785             references (message-fetch-field "references")
3786             message-id (message-fetch-field "message-id" t)
3787             followup-to (message-fetch-field "followup-to")
3788             newsgroups (message-fetch-field "newsgroups")
3789             posted-to (message-fetch-field "posted-to")
3790             reply-to (message-fetch-field "reply-to")
3791             distribution (message-fetch-field "distribution")
3792             mct (message-fetch-field "mail-copies-to"))
3793       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3794                  (string-match "<[^>]+>" gnus-warning))
3795         (setq message-id (match-string 0 gnus-warning)))
3796       ;; Remove bogus distribution.
3797       (when (and (stringp distribution)
3798                  (let ((case-fold-search t))
3799                    (string-match "world" distribution)))
3800         (setq distribution nil))
3801       ;; Remove any (buggy) Re:'s that are present and make a
3802       ;; proper one.
3803       (when (string-match message-subject-re-regexp subject)
3804         (setq subject (substring subject (match-end 0))))
3805       (setq subject (concat "Re: " subject))
3806       (widen))
3807
3808     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3809
3810     (message-setup
3811      `((Subject . ,subject)
3812        ,@(cond
3813           (to-newsgroups
3814            (list (cons 'Newsgroups to-newsgroups)))
3815           (follow-to follow-to)
3816           ((and followup-to message-use-followup-to)
3817            (list
3818             (cond
3819              ((equal (downcase followup-to) "poster")
3820               (if (or (eq message-use-followup-to 'use)
3821                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
3822 You should normally obey the Followup-To: header.
3823
3824 `Followup-To: poster' sends your response via e-mail instead of news.
3825
3826 A typical situation where `Followup-To: poster' is used is when the poster
3827 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3828                   (progn
3829                     (setq message-this-is-news nil)
3830                     (cons 'To (or reply-to from "")))
3831                 (cons 'Newsgroups newsgroups)))
3832              (t
3833               (if (or (equal followup-to newsgroups)
3834                       (not (eq message-use-followup-to 'ask))
3835                       (message-y-or-n-p
3836                        (concat "Obey Followup-To: " followup-to "? ") t "\
3837 You should normally obey the Followup-To: header.
3838
3839         `Followup-To: " followup-to "'
3840 directs your response to " (if (string-match "," followup-to)
3841                                "the specified newsgroups"
3842                              "that newsgroup only") ".
3843
3844 If a message is posted to several newsgroups, Followup-To is often
3845 used to direct the following discussion to one newsgroup only,
3846 because discussions that are spread over several newsgroup tend to
3847 be fragmented and very difficult to follow.
3848
3849 Also, some source/announcement newsgroups are not indented for discussion;
3850 responses here are directed to other newsgroups."))
3851                   (cons 'Newsgroups followup-to)
3852                 (cons 'Newsgroups newsgroups))))))
3853           (posted-to
3854            `((Newsgroups . ,posted-to)))
3855           (t
3856            `((Newsgroups . ,newsgroups))))
3857        ,@(and distribution (list (cons 'Distribution distribution)))
3858        ,@(if (or references message-id)
3859              `((References . ,(concat (or references "") (and references " ")
3860                                       (or message-id "")))))
3861        ,@(when (and mct
3862                     (not (equal (downcase mct) "never")))
3863            (list (cons 'Cc (if (equal (downcase mct) "always")
3864                                (or reply-to from "")
3865                              mct)))))
3866
3867      cur)
3868
3869     (setq message-reply-headers
3870           (vector 0 subject from date message-id references 0 0 ""))))
3871
3872
3873 ;;;###autoload
3874 (defun message-cancel-news ()
3875   "Cancel an article you posted."
3876   (interactive)
3877   (unless (message-news-p)
3878     (error "This is not a news article; canceling is impossible"))
3879   (when (yes-or-no-p "Do you really want to cancel this article? ")
3880     (let (from newsgroups message-id distribution buf sender)
3881       (save-excursion
3882         ;; Get header info. from original article.
3883         (save-restriction
3884           (message-narrow-to-head)
3885           (setq from (message-fetch-field "from")
3886                 sender (message-fetch-field "sender")
3887                 newsgroups (message-fetch-field "newsgroups")
3888                 message-id (message-fetch-field "message-id" t)
3889                 distribution (message-fetch-field "distribution")))
3890         ;; Make sure that this article was written by the user.
3891         (unless (or (and sender
3892                          (string-equal
3893                           (downcase sender)
3894                           (downcase (message-make-sender))))
3895                     (string-equal
3896                      (downcase (cadr (mail-extract-address-components from)))
3897                      (downcase (cadr (mail-extract-address-components
3898                                       (message-make-from))))))
3899           (error "This article is not yours"))
3900         ;; Make control message.
3901         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
3902         (buffer-disable-undo (current-buffer))
3903         (erase-buffer)
3904         (insert "Newsgroups: " newsgroups "\n"
3905                 "From: " (message-make-from) "\n"
3906                 "Subject: cmsg cancel " message-id "\n"
3907                 "Control: cancel " message-id "\n"
3908                 (if distribution
3909                     (concat "Distribution: " distribution "\n")
3910                   "")
3911                 mail-header-separator "\n"
3912                 message-cancel-message)
3913         (message "Canceling your article...")
3914         (if (let ((message-syntax-checks
3915                    'dont-check-for-anything-just-trust-me)
3916                   (message-encoding-buffer (current-buffer))
3917                   (message-edit-buffer (current-buffer)))
3918               (message-send-news))
3919             (message "Canceling your article...done"))
3920         (kill-buffer buf)))))
3921
3922 ;;;###autoload
3923 (defun message-supersede ()
3924   "Start composing a message to supersede the current message.
3925 This is done simply by taking the old article and adding a Supersedes
3926 header line with the old Message-ID."
3927   (interactive)
3928   (let ((cur (current-buffer))
3929         (sender (message-fetch-field "sender"))
3930         (from (message-fetch-field "from")))
3931     ;; Check whether the user owns the article that is to be superseded.
3932     (unless (or (and sender
3933                      (string-equal
3934                       (downcase sender)
3935                       (downcase (message-make-sender))))
3936                 (string-equal
3937                  (downcase (cadr (mail-extract-address-components from)))
3938                  (downcase (cadr (mail-extract-address-components
3939                                   (message-make-from))))))
3940       (error "This article is not yours"))
3941     ;; Get a normal message buffer.
3942     (message-pop-to-buffer (message-buffer-name "supersede"))
3943     (insert-buffer-substring cur)
3944     (message-narrow-to-head)
3945     ;; Remove unwanted headers.
3946     (when message-ignored-supersedes-headers
3947       (message-remove-header message-ignored-supersedes-headers t))
3948     (goto-char (point-min))
3949     (if (not (re-search-forward "^Message-ID: " nil t))
3950         (error "No Message-ID in this article")
3951       (replace-match "Supersedes: " t t))
3952     (goto-char (point-max))
3953     (insert mail-header-separator)
3954     (widen)
3955     (forward-line 1)))
3956
3957 ;;;###autoload
3958 (defun message-recover ()
3959   "Reread contents of current buffer from its last auto-save file."
3960   (interactive)
3961   (let ((file-name (make-auto-save-file-name)))
3962     (cond ((save-window-excursion
3963              (if (not (eq system-type 'vax-vms))
3964                  (with-output-to-temp-buffer "*Directory*"
3965                    (buffer-disable-undo standard-output)
3966                    (let ((default-directory "/"))
3967                      (call-process
3968                       "ls" nil standard-output nil "-l" file-name))))
3969              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3970            (let ((buffer-read-only nil))
3971              (erase-buffer)
3972              (insert-file-contents file-name nil)))
3973           (t (error "message-recover cancelled")))))
3974
3975 ;;; Washing Subject:
3976
3977 (defun message-wash-subject (subject)
3978   "Remove junk like \"Re:\", \"(fwd)\", etc. that was added to the subject by previous forwarders, replyers, etc."
3979   (nnheader-temp-write nil
3980     (insert-string subject)
3981     (goto-char (point-min))
3982     ;; strip Re/Fwd stuff off the beginning
3983     (while (re-search-forward
3984             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
3985       (replace-match ""))
3986
3987     ;; and gnus-style forwards [foo@bar.com] subject
3988     (goto-char (point-min))
3989     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
3990       (replace-match ""))
3991
3992     ;; and off the end
3993     (goto-char (point-max))
3994     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
3995       (replace-match ""))
3996
3997     ;; and finally, any whitespace that was left-over
3998     (goto-char (point-min))
3999     (while (re-search-forward "^[ \t]+" nil t)
4000       (replace-match ""))
4001     (goto-char (point-max))
4002     (while (re-search-backward "[ \t]+$" nil t)
4003       (replace-match ""))
4004
4005     (buffer-string)))
4006     
4007 ;;; Forwarding messages.
4008
4009 (defun message-forward-subject-author-subject (subject)
4010   "Generate a subject for a forwarded message.
4011 The form is: [Source] Subject, where if the original message was mail,
4012 Source is the sender, and if the original message was news, Source is
4013 the list of newsgroups is was posted to."
4014   (concat "["
4015           (or (message-fetch-field
4016                (if (message-news-p) "newsgroups" "from"))
4017               "(nowhere)")
4018           "] " subject))
4019
4020 (defun message-forward-subject-fwd (subject)
4021   "Generate a subject for a forwarded message.
4022 The form is: Fwd: Subject, where Subject is the original subject of
4023 the message."
4024   (concat "Fwd: " subject))
4025
4026 (defun message-make-forward-subject ()
4027   "Return a Subject header suitable for the message in the current buffer."
4028   (save-excursion
4029     (save-restriction
4030       (current-buffer)
4031       (message-narrow-to-head)
4032       (let ((funcs message-make-forward-subject-function)
4033             (subject (if message-wash-forwarded-subjects
4034                          (message-wash-subject
4035                           (or (eword-decode-unstructured-field-body
4036                                (message-fetch-field "Subject")) ""))
4037                        (or (eword-decode-unstructured-field-body
4038                             (message-fetch-field "Subject")) ""))))
4039         ;; Make sure funcs is a list.
4040         (and funcs
4041              (not (listp funcs))
4042              (setq funcs (list funcs)))
4043         ;; Apply funcs in order, passing subject generated by previous
4044         ;; func to the next one.
4045         (while funcs
4046           (when (message-functionp (car funcs))
4047             (setq subject (funcall (car funcs) subject)))
4048           (setq funcs (cdr funcs)))
4049         subject))))
4050
4051 ;;;###autoload
4052 (defun message-forward (&optional news)
4053   "Forward the current message via mail.
4054 Optional NEWS will use news to forward instead of mail."
4055   (interactive "P")
4056   (let ((cur (current-buffer))
4057         (subject (message-make-forward-subject))
4058         art-beg)
4059     (if news (message-news nil subject) (message-mail nil subject))
4060     ;; Put point where we want it before inserting the forwarded
4061     ;; message.
4062     (if message-signature-before-forwarded-message
4063         (goto-char (point-max))
4064       (message-goto-body))
4065     ;; Make sure we're at the start of the line.
4066     (unless (eolp)
4067       (insert "\n"))
4068     ;; Narrow to the area we are to insert.
4069     (narrow-to-region (point) (point))
4070     ;; Insert the separators and the forwarded buffer.
4071     (insert message-forward-start-separator)
4072     (setq art-beg (point))
4073     (insert-buffer-substring cur)
4074     (goto-char (point-max))
4075     (insert message-forward-end-separator)
4076     (set-text-properties (point-min) (point-max) nil)
4077     ;; Remove all unwanted headers.
4078     (goto-char art-beg)
4079     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
4080                                   (1- (point))
4081                                 (point)))
4082     (goto-char (point-min))
4083     (message-remove-header message-included-forward-headers t nil t)
4084     (widen)
4085     (message-position-point)))
4086
4087 ;;;###autoload
4088 (defun message-resend (address)
4089   "Resend the current article to ADDRESS."
4090   (interactive "sResend message to: ")
4091   (message "Resending message to %s..." address)
4092   (save-excursion
4093     (let ((cur (current-buffer))
4094           beg)
4095       ;; We first set up a normal mail buffer.
4096       (set-buffer (get-buffer-create " *message resend*"))
4097       (buffer-disable-undo (current-buffer))
4098       (erase-buffer)
4099       ;; avoid to turn-on-mime-edit
4100       (let (message-setup-hook)
4101         (message-setup `((To . ,address)))
4102         )
4103       ;; Insert our usual headers.
4104       (message-generate-headers '(From Date To))
4105       (message-narrow-to-headers)
4106       ;; Rename them all to "Resent-*".
4107       (while (re-search-forward "^[A-Za-z]" nil t)
4108         (forward-char -1)
4109         (insert "Resent-"))
4110       (widen)
4111       (forward-line)
4112       (delete-region (point) (point-max))
4113       (setq beg (point))
4114       ;; Insert the message to be resent.
4115       (insert-buffer-substring cur)
4116       (goto-char (point-min))
4117       (search-forward "\n\n")
4118       (forward-char -1)
4119       (save-restriction
4120         (narrow-to-region beg (point))
4121         (message-remove-header message-ignored-resent-headers t)
4122         (goto-char (point-max)))
4123       (insert mail-header-separator)
4124       ;; Rename all old ("Also-")Resent headers.
4125       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
4126         (beginning-of-line)
4127         (insert "Also-"))
4128       ;; Quote any "From " lines at the beginning.
4129       (goto-char beg)
4130       (when (looking-at "From ")
4131         (replace-match "X-From-Line: "))
4132       ;; Send it.
4133       (let ((message-encoding-buffer (current-buffer))
4134             (message-edit-buffer (current-buffer)))
4135         (message-send-mail))
4136       (kill-buffer (current-buffer)))
4137     (message "Resending message to %s...done" address)))
4138
4139 (defun message-bounce-setup-for-mime-edit ()
4140   (goto-char (point-min))
4141   (when (search-forward (concat "\n" mail-header-separator "\n") nil t)
4142     (replace-match "\n\n"))
4143   (set (make-local-variable 'message-setup-hook) nil)
4144   (mime-edit-again))
4145
4146 ;;;###autoload
4147 (defun message-bounce ()
4148   "Re-mail the current message.
4149 This only makes sense if the current message is a bounce message than
4150 contains some mail you have written which has been bounced back to
4151 you."
4152   (interactive)
4153   (let ((cur (current-buffer))
4154         boundary)
4155     (message-pop-to-buffer (message-buffer-name "bounce"))
4156     (insert-buffer-substring cur)
4157     (undo-boundary)
4158     (message-narrow-to-head)
4159     (if (and (message-fetch-field "MIME-Version")
4160              (setq boundary (message-fetch-field "Content-Type")))
4161         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
4162             (setq boundary (concat (match-string 1 boundary) " *\n"
4163                                    "Content-Type: message/rfc822"))
4164           (setq boundary nil)))
4165     (widen)
4166     (goto-char (point-min))
4167     (search-forward "\n\n" nil t)
4168     (or (and boundary
4169              (re-search-forward boundary nil t)
4170              (forward-line 2))
4171         (and (re-search-forward message-unsent-separator nil t)
4172              (forward-line 1))
4173         (re-search-forward "^Return-Path:.*\n" nil t))
4174     ;; We remove everything before the bounced mail.
4175     (delete-region
4176      (point-min)
4177      (if (re-search-forward "^[^ \n\t]+:" nil t)
4178          (match-beginning 0)
4179        (point)))
4180     (save-restriction
4181       (message-narrow-to-head)
4182       (message-remove-header message-ignored-bounced-headers t)
4183       (goto-char (point-max))
4184       (insert mail-header-separator))
4185     (when message-bounce-setup-function
4186       (funcall message-bounce-setup-function))
4187     (run-hooks 'message-bounce-setup-hook)
4188     (message-position-point)))
4189
4190 ;;;
4191 ;;; Interactive entry points for new message buffers.
4192 ;;;
4193
4194 ;;;###autoload
4195 (defun message-mail-other-window (&optional to subject)
4196   "Like `message-mail' command, but display mail buffer in another window."
4197   (interactive)
4198   (let ((pop-up-windows t)
4199         (special-display-buffer-names nil)
4200         (special-display-regexps nil)
4201         (same-window-buffer-names nil)
4202         (same-window-regexps nil))
4203     (message-pop-to-buffer (message-buffer-name "mail" to)))
4204   (let ((message-this-is-mail t))
4205     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4206
4207 ;;;###autoload
4208 (defun message-mail-other-frame (&optional to subject)
4209   "Like `message-mail' command, but display mail buffer in another frame."
4210   (interactive)
4211   (let ((pop-up-frames t)
4212         (special-display-buffer-names nil)
4213         (special-display-regexps nil)
4214         (same-window-buffer-names nil)
4215         (same-window-regexps nil))
4216     (message-pop-to-buffer (message-buffer-name "mail" to)))
4217   (let ((message-this-is-mail t))
4218     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4219
4220 ;;;###autoload
4221 (defun message-news-other-window (&optional newsgroups subject)
4222   "Start editing a news article to be sent."
4223   (interactive)
4224   (let ((pop-up-windows t)
4225         (special-display-buffer-names nil)
4226         (special-display-regexps nil)
4227         (same-window-buffer-names nil)
4228         (same-window-regexps nil))
4229     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4230   (let ((message-this-is-news t))
4231     (message-setup `((Newsgroups . ,(or newsgroups ""))
4232                      (Subject . ,(or subject ""))))))
4233
4234 ;;;###autoload
4235 (defun message-news-other-frame (&optional newsgroups subject)
4236   "Start editing a news article to be sent."
4237   (interactive)
4238   (let ((pop-up-frames t)
4239         (special-display-buffer-names nil)
4240         (special-display-regexps nil)
4241         (same-window-buffer-names nil)
4242         (same-window-regexps nil))
4243     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4244   (let ((message-this-is-news t))
4245     (message-setup `((Newsgroups . ,(or newsgroups ""))
4246                      (Subject . ,(or subject ""))))))
4247
4248 ;;; underline.el
4249
4250 ;; This code should be moved to underline.el (from which it is stolen).
4251
4252 ;;;###autoload
4253 (defun bold-region (start end)
4254   "Bold all nonblank characters in the region.
4255 Works by overstriking characters.
4256 Called from program, takes two arguments START and END
4257 which specify the range to operate on."
4258   (interactive "r")
4259   (save-excursion
4260     (let ((end1 (make-marker)))
4261       (move-marker end1 (max start end))
4262       (goto-char (min start end))
4263       (while (< (point) end1)
4264         (or (looking-at "[_\^@- ]")
4265             (insert (following-char) "\b"))
4266         (forward-char 1)))))
4267
4268 ;;;###autoload
4269 (defun unbold-region (start end)
4270   "Remove all boldness (overstruck characters) in the region.
4271 Called from program, takes two arguments START and END
4272 which specify the range to operate on."
4273   (interactive "r")
4274   (save-excursion
4275     (let ((end1 (make-marker)))
4276       (move-marker end1 (max start end))
4277       (goto-char (min start end))
4278       (while (re-search-forward "\b" end1 t)
4279         (if (eq (following-char) (char-after (- (point) 2)))
4280             (delete-char -2))))))
4281
4282 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
4283
4284 ;; Support for toolbar
4285 (when (string-match "XEmacs\\|Lucid" emacs-version)
4286   (require 'messagexmas))
4287
4288 ;;; Group name completion.
4289
4290 (defvar message-newgroups-header-regexp
4291   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
4292   "Regexp that match headers that lists groups.")
4293
4294 (defun message-tab ()
4295   "Expand group names in Newsgroups and Followup-To headers.
4296 Do a `tab-to-tab-stop' if not in those headers."
4297   (interactive)
4298   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
4299         (mail-abbrev-in-expansion-header-p))
4300       (message-expand-group)
4301     (tab-to-tab-stop)))
4302
4303 (defvar gnus-active-hashtb)
4304 (defun message-expand-group ()
4305   "Expand the group name under point."
4306   (let* ((b (save-excursion
4307               (save-restriction
4308                 (narrow-to-region
4309                  (save-excursion
4310                    (beginning-of-line)
4311                    (skip-chars-forward "^:")
4312                    (1+ (point)))
4313                  (point))
4314                 (skip-chars-backward "^, \t\n") (point))))
4315          (completion-ignore-case t)
4316          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
4317                                             (point))))
4318          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
4319          (completions (all-completions string hashtb))
4320          comp)
4321     (delete-region b (point))
4322     (cond
4323      ((= (length completions) 1)
4324       (if (string= (car completions) string)
4325           (progn
4326             (insert string)
4327             (message "Only matching group"))
4328         (insert (car completions))))
4329      ((and (setq comp (try-completion string hashtb))
4330            (not (string= comp string)))
4331       (insert comp))
4332      (t
4333       (insert string)
4334       (if (not comp)
4335           (message "No matching groups")
4336         (save-selected-window
4337           (pop-to-buffer "*Completions*")
4338           (buffer-disable-undo (current-buffer))
4339           (let ((buffer-read-only nil))
4340             (erase-buffer)
4341             (let ((standard-output (current-buffer)))
4342               (display-completion-list (sort completions 'string<)))
4343             (goto-char (point-min))
4344             (delete-region (point) (progn (forward-line 3) (point))))))))))
4345
4346 ;;; Help stuff.
4347
4348 (defun message-talkative-question (ask question show &rest text)
4349   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
4350 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
4351 The following arguments may contain lists of values."
4352   (if (and show
4353            (setq text (message-flatten-list text)))
4354       (save-window-excursion
4355         (save-excursion
4356           (with-output-to-temp-buffer " *MESSAGE information message*"
4357             (set-buffer " *MESSAGE information message*")
4358             (mapcar 'princ text)
4359             (goto-char (point-min))))
4360         (funcall ask question))
4361     (funcall ask question)))
4362
4363 (defun message-flatten-list (list)
4364   "Return a new, flat list that contains all elements of LIST.
4365
4366 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
4367 => (1 2 3 4 5 6 7)"
4368   (cond ((consp list)
4369          (apply 'append (mapcar 'message-flatten-list list)))
4370         (list
4371          (list list))))
4372
4373 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
4374   "Create and return a buffer with a name based on NAME using generate-new-buffer.
4375 Then clone the local variables and values from the old buffer to the
4376 new one, cloning only the locals having a substring matching the
4377 regexp varstr."
4378   (let ((oldbuf (current-buffer)))
4379     (save-excursion
4380       (set-buffer (generate-new-buffer name))
4381       (message-clone-locals oldbuf)
4382       (current-buffer))))
4383
4384 (defun message-clone-locals (buffer)
4385   "Clone the local variables from BUFFER to the current buffer."
4386   (let ((locals (save-excursion
4387                   (set-buffer buffer)
4388                   (buffer-local-variables)))
4389         (regexp "^\\(gnus\\|nn\\|message\\|user-\\(mail-address\\|full-name\\)\\)"))
4390     (mapcar
4391      (lambda (local)
4392        (when (and (consp local)
4393                   (car local)
4394                   (string-match regexp (symbol-name (car local))))
4395          (ignore-errors
4396            (set (make-local-variable (car local))
4397                 (cdr local)))))
4398      locals)))
4399
4400 ;;; @ for MIME Edit mode
4401 ;;;
4402
4403 (defun message-maybe-setup-default-charset ()
4404   (let ((charset
4405          (and (boundp 'gnus-summary-buffer)
4406               (buffer-live-p gnus-summary-buffer)
4407               (save-excursion
4408                 (set-buffer gnus-summary-buffer)
4409                 default-mime-charset))))
4410     (if charset
4411         (progn
4412           (make-local-variable 'default-mime-charset)
4413           (setq default-mime-charset charset)
4414           ))))
4415
4416 (defun message-maybe-encode ()
4417   (when message-mime-mode
4418     (run-hooks 'mime-edit-translate-hook)
4419     (if (catch 'mime-edit-error
4420           (save-excursion
4421             (mime-edit-translate-body)
4422             ))
4423         (error "Translation error!")
4424       )
4425     (end-of-invisible)
4426     (run-hooks 'mime-edit-exit-hook)
4427     ))
4428
4429 (defun message-mime-insert-article (&optional message)
4430   (interactive)
4431   (let ((message-cite-function 'mime-edit-inserted-message-filter)
4432         (message-reply-buffer (message-get-original-reply-buffer))
4433         (start (point)))
4434     (message-yank-original nil)
4435     ))
4436
4437 (set-alist 'mime-edit-message-inserter-alist
4438            'message-mode (function message-mime-insert-article))
4439
4440 ;;; Miscellaneous functions
4441
4442 ;; stolen (and renamed) from nnheader.el
4443 (defun message-replace-chars-in-string (string from to)
4444   "Replace characters in STRING from FROM to TO."
4445   (let ((string (substring string 0))   ;Copy string.
4446         (len (length string))
4447         (idx 0))
4448     ;; Replace all occurrences of FROM with TO.
4449     (while (< idx len)
4450       (when (= (aref string idx) from)
4451         (aset string idx to))
4452       (setq idx (1+ idx)))
4453     string))
4454
4455 (defvar message-save-buffer " *encoding")
4456 (defun message-save-drafts ()
4457   (interactive)
4458   (if (not (get-buffer message-save-buffer))
4459       (get-buffer-create message-save-buffer))
4460   (let ((filename buffer-file-name)
4461         (buffer (current-buffer)))
4462     (set-buffer message-save-buffer)
4463     (erase-buffer)
4464     (insert-buffer buffer)
4465     (mime-edit-translate-buffer)
4466     (write-region (point-min) (point-max) filename)
4467     (set-buffer buffer)
4468     (set-buffer-modified-p nil)))
4469
4470 (run-hooks 'message-load-hook)
4471
4472 (provide 'message)
4473
4474 ;;; message.el ends here