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