bd94eae94bd87aa40514fe6199407b08f43d88ee
[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 (defun message-eval-parameter (parameter)
1039   (condition-case ()
1040       (if (symbolp parameter)
1041           (if (functionp parameter)
1042               (funcall parameter)
1043             (eval parameter))
1044         parameter)
1045     (error nil)))
1046
1047 (defsubst message-get-parameter (key &optional alist)
1048   (unless alist
1049     (setq alist message-parameter-alist))
1050   (cdr (assq key alist)))
1051
1052 (defmacro message-get-parameter-with-eval (key &optional alist)
1053   `(message-eval-parameter (message-get-parameter ,alist ,key)))
1054
1055 (defmacro message-y-or-n-p (question show &rest text)
1056   "Ask QUESTION, displaying the rest of the arguments in a temp. buffer if SHOW"
1057   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1058
1059 ;; Delete the current line (and the next N lines.);
1060 (defmacro message-delete-line (&optional n)
1061   `(delete-region (progn (beginning-of-line) (point))
1062                   (progn (forward-line ,(or n 1)) (point))))
1063
1064 (defun message-tokenize-header (header &optional separator)
1065   "Split HEADER into a list of header elements.
1066 \",\" is used as the separator."
1067   (if (not header)
1068       nil
1069     (let ((regexp (format "[%s]+" (or separator ",")))
1070           (beg 1)
1071           (first t)
1072           quoted elems paren)
1073       (save-excursion
1074         (message-set-work-buffer)
1075         (insert header)
1076         (goto-char (point-min))
1077         (while (not (eobp))
1078           (if first
1079               (setq first nil)
1080             (forward-char 1))
1081           (cond ((and (> (point) beg)
1082                       (or (eobp)
1083                           (and (looking-at regexp)
1084                                (not quoted)
1085                                (not paren))))
1086                  (push (buffer-substring beg (point)) elems)
1087                  (setq beg (match-end 0)))
1088                 ((= (following-char) ?\")
1089                  (setq quoted (not quoted)))
1090                 ((and (= (following-char) ?\()
1091                       (not quoted))
1092                  (setq paren t))
1093                 ((and (= (following-char) ?\))
1094                       (not quoted))
1095                  (setq paren nil))))
1096         (nreverse elems)))))
1097
1098 (defun message-mail-file-mbox-p (file)
1099   "Say whether FILE looks like a Unix mbox file."
1100   (when (and (file-exists-p file)
1101              (file-readable-p file)
1102              (file-regular-p file))
1103     (nnheader-temp-write nil
1104       (nnheader-insert-file-contents file)
1105       (goto-char (point-min))
1106       (looking-at message-unix-mail-delimiter))))
1107
1108 (defun message-fetch-field (header &optional not-all)
1109   "The same as `mail-fetch-field', only remove all newlines."
1110   (let* ((inhibit-point-motion-hooks t)
1111          (value (mail-fetch-field header nil (not not-all))))
1112     (when value
1113       (nnheader-replace-chars-in-string value ?\n ? ))))
1114
1115 (defun message-add-header (&rest headers)
1116   "Add the HEADERS to the message header, skipping those already present."
1117   (while headers
1118     (let (hclean)
1119       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1120         (error "Invalid header `%s'" (car headers)))
1121       (setq hclean (match-string 1 (car headers)))
1122     (save-restriction
1123       (message-narrow-to-headers)
1124       (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1125         (insert (car headers) ?\n))))
1126     (setq headers (cdr headers))))
1127
1128 (defun message-fetch-reply-field (header)
1129   "Fetch FIELD from the message we're replying to."
1130   (let ((buffer (message-eval-parameter message-reply-buffer)))
1131     (when (and buffer
1132                (buffer-name buffer))
1133       (save-excursion
1134         (set-buffer buffer)
1135       (message-fetch-field header)))))
1136
1137 (defun message-set-work-buffer ()
1138   (if (get-buffer " *message work*")
1139       (progn
1140         (set-buffer " *message work*")
1141         (erase-buffer))
1142     (set-buffer (get-buffer-create " *message work*"))
1143     (kill-all-local-variables)
1144     (buffer-disable-undo (current-buffer))))
1145
1146 (defun message-functionp (form)
1147   "Return non-nil if FORM is funcallable."
1148   (or (and (symbolp form) (fboundp form))
1149       (and (listp form) (eq (car form) 'lambda))
1150       (byte-code-function-p form)))
1151
1152 (defun message-strip-subject-re (subject)
1153   "Remove \"Re:\" from subject lines."
1154   (if (string-match message-subject-re-regexp subject)
1155       (substring subject (match-end 0))
1156     subject))
1157
1158 (defun message-remove-header (header &optional is-regexp first reverse)
1159   "Remove HEADER in the narrowed buffer.
1160 If REGEXP, HEADER is a regular expression.
1161 If FIRST, only remove the first instance of the header.
1162 Return the number of headers removed."
1163   (goto-char (point-min))
1164   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1165         (number 0)
1166         (case-fold-search t)
1167         last)
1168     (while (and (not (eobp))
1169                 (not last))
1170       (if (if reverse
1171               (not (looking-at regexp))
1172             (looking-at regexp))
1173           (progn
1174             (incf number)
1175             (when first
1176               (setq last t))
1177             (delete-region
1178              (point)
1179              ;; There might be a continuation header, so we have to search
1180              ;; until we find a new non-continuation line.
1181              (progn
1182                (forward-line 1)
1183                (if (re-search-forward "^[^ \t]" nil t)
1184                    (goto-char (match-beginning 0))
1185                  (point-max)))))
1186         (forward-line 1)
1187         (if (re-search-forward "^[^ \t]" nil t)
1188             (goto-char (match-beginning 0))
1189           (point-max))))
1190     number))
1191
1192 (defun message-narrow-to-headers ()
1193   "Narrow the buffer to the head of the message."
1194   (widen)
1195   (narrow-to-region
1196    (goto-char (point-min))
1197    (if (re-search-forward
1198         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1199        (match-beginning 0)
1200      (point-max)))
1201   (goto-char (point-min)))
1202
1203 (defun message-narrow-to-head ()
1204   "Narrow the buffer to the head of the message."
1205   (widen)
1206   (narrow-to-region
1207    (goto-char (point-min))
1208    (if (search-forward "\n\n" nil 1)
1209        (1- (point))
1210      (point-max)))
1211   (goto-char (point-min)))
1212
1213 (defun message-news-p ()
1214   "Say whether the current buffer contains a news message."
1215   (and (not message-this-is-mail)
1216        (or message-this-is-news
1217            (save-excursion
1218              (save-restriction
1219                (message-narrow-to-headers)
1220                (and (message-fetch-field "newsgroups")
1221                     (not (message-fetch-field "posted-to"))))))))
1222
1223 (defun message-mail-p ()
1224   "Say whether the current buffer contains a mail message."
1225   (and (not message-this-is-news)
1226        (or message-this-is-mail
1227            (save-excursion
1228              (save-restriction
1229                (message-narrow-to-headers)
1230                (or (message-fetch-field "to")
1231                    (message-fetch-field "cc")
1232                    (message-fetch-field "bcc")))))))
1233
1234 (defun message-next-header ()
1235   "Go to the beginning of the next header."
1236   (beginning-of-line)
1237   (or (eobp) (forward-char 1))
1238   (not (if (re-search-forward "^[^ \t]" nil t)
1239            (beginning-of-line)
1240          (goto-char (point-max)))))
1241
1242 (defun message-sort-headers-1 ()
1243   "Sort the buffer as headers using `message-rank' text props."
1244   (goto-char (point-min))
1245   (sort-subr
1246    nil 'message-next-header
1247    (lambda ()
1248      (message-next-header)
1249      (unless (bobp)
1250        (forward-char -1)))
1251    (lambda ()
1252      (or (get-text-property (point) 'message-rank)
1253          10000))))
1254
1255 (defun message-sort-headers ()
1256   "Sort the headers of the current message according to `message-header-format-alist'."
1257   (interactive)
1258   (save-excursion
1259     (save-restriction
1260       (let ((max (1+ (length message-header-format-alist)))
1261             rank)
1262         (message-narrow-to-headers)
1263         (while (re-search-forward "^[^ \n]+:" nil t)
1264           (put-text-property
1265            (match-beginning 0) (1+ (match-beginning 0))
1266            'message-rank
1267            (if (setq rank (length (memq (assq (intern (buffer-substring
1268                                                        (match-beginning 0)
1269                                                        (1- (match-end 0))))
1270                                               message-header-format-alist)
1271                                         message-header-format-alist)))
1272                (- max rank)
1273              (1+ max)))))
1274       (message-sort-headers-1))))
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-eval-parameter message-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         (frame (selected-frame))
1987         (org-frame message-original-frame))
1988     (message-bury (current-buffer))
1989     (message-do-actions actions)
1990     (message-delete-frame frame org-frame)))
1991
1992 (defun message-kill-buffer ()
1993   "Kill the current buffer."
1994   (interactive)
1995   (when (or (not (buffer-modified-p))
1996             (eq t message-kill-buffer-query-function)
1997             (funcall message-kill-buffer-query-function
1998                      "The buffer modified; kill anyway? "))
1999     (let ((actions message-kill-actions)
2000           (frame (selected-frame))
2001           (org-frame message-original-frame))
2002       (setq buffer-file-name nil)
2003       (kill-buffer (current-buffer))
2004       (message-do-actions actions)
2005       (message-delete-frame frame org-frame)))
2006   (message ""))
2007
2008 (defun message-delete-frame (frame org-frame)
2009   "Delete frame for editing message."
2010   (when (and (or (and (featurep 'xemacs)
2011                       (not (eq 'tty (device-type))))
2012                  window-system
2013                  (>= emacs-major-version 20))
2014              (or (and (eq message-delete-frame-on-exit t)
2015                       (select-frame frame)
2016                       (or (eq frame org-frame)
2017                           (prog1
2018                               (y-or-n-p "Delete this frame?")
2019                             (message ""))))
2020                  (and (eq message-delete-frame-on-exit 'ask)
2021                       (select-frame frame)
2022                       (prog1
2023                           (y-or-n-p "Delete this frame?")
2024                         (message "")))))
2025     (delete-frame frame)))
2026
2027 (defun message-bury (buffer)
2028   "Bury this mail buffer."
2029   (let ((newbuf (other-buffer buffer)))
2030     (bury-buffer buffer)
2031     (if (and (fboundp 'frame-parameters)
2032              (cdr (assq 'dedicated (frame-parameters)))
2033              (not (null (delq (selected-frame) (visible-frame-list)))))
2034         (delete-frame (selected-frame))
2035       (switch-to-buffer newbuf))))
2036
2037 (defun message-send (&optional arg)
2038   "Send the message in the current buffer.
2039 If `message-interactive' is non-nil, wait for success indication
2040 or error messages, and inform user.
2041 Otherwise any failure is reported in a message back to
2042 the user from the mailer."
2043   (interactive "P")
2044   ;; Disabled test.
2045   (when (or (buffer-modified-p)
2046             (message-check-element 'unchanged)
2047             (y-or-n-p "No changes in the buffer; really send? "))
2048     ;; Make it possible to undo the coming changes.
2049     (undo-boundary)
2050     (let ((inhibit-read-only t))
2051       (put-text-property (point-min) (point-max) 'read-only nil))
2052     (run-hooks 'message-send-hook)
2053     (message "Sending...")
2054     (let ((message-encoding-buffer
2055            (message-generate-new-buffer-clone-locals " message encoding"))
2056           (message-edit-buffer (current-buffer))
2057           (message-mime-mode mime-edit-mode-flag)
2058           (alist message-send-method-alist)
2059           (success t)
2060           elem sent)
2061       (save-excursion
2062         (set-buffer message-encoding-buffer)
2063         (erase-buffer)
2064         (insert-buffer message-edit-buffer)
2065         (funcall message-encode-function)
2066         (message-fix-before-sending)
2067         (while (and success
2068                     (setq elem (pop alist)))
2069           (when (and (or (not (funcall (cadr elem)))
2070                          (and (or (not (memq (car elem)
2071                                              message-sent-message-via))
2072                                   (y-or-n-p
2073                                    (format
2074                                     "Already sent message via %s; resend? "
2075                                     (car elem))))
2076                               (setq success (funcall (caddr elem) arg)))))
2077             (setq sent t))))
2078       (when (and success sent)
2079         (message-do-fcc)
2080         ;;(when (fboundp 'mail-hist-put-headers-into-history)
2081         ;; (mail-hist-put-headers-into-history))
2082         (run-hooks 'message-sent-hook)
2083         (message "Sending...done")
2084         ;; Mark the buffer as unmodified and delete autosave.
2085         (set-buffer-modified-p nil)
2086         (delete-auto-save-file-if-necessary t)
2087         (message-disassociate-draft)
2088         ;; Delete other mail buffers and stuff.
2089         (message-do-send-housekeeping)
2090         (message-do-actions message-send-actions)
2091         ;; Return success.
2092         t))))
2093
2094 (defun message-send-via-mail (arg)
2095   "Send the current message via mail."
2096   (message-send-mail arg))
2097
2098 (defun message-send-via-news (arg)
2099   "Send the current message via news."
2100   (message-send-news arg))
2101
2102 (defun message-fix-before-sending ()
2103   "Do various things to make the message nice before sending it."
2104   ;; Make sure there's a newline at the end of the message.
2105   (goto-char (point-max))
2106   (unless (bolp)
2107     (insert "\n"))
2108   ;; Make all invisible text visible.
2109   ;;(when (text-property-any (point-min) (point-max) 'invisible t)
2110   ;;  (put-text-property (point-min) (point-max) 'invisible nil)
2111   ;;  (unless (yes-or-no-p "Invisible text found and made visible; continue posting?")
2112   ;;    (error "Invisible text found and made visible")))
2113   )
2114
2115 (defun message-add-action (action &rest types)
2116   "Add ACTION to be performed when doing an exit of type TYPES."
2117   (let (var)
2118     (while types
2119       (set (setq var (intern (format "message-%s-actions" (pop types))))
2120            (nconc (symbol-value var) (list action))))))
2121
2122 (defun message-do-actions (actions)
2123   "Perform all actions in ACTIONS."
2124   ;; Now perform actions on successful sending.
2125   (while actions
2126     (ignore-errors
2127       (cond
2128        ;; A simple function.
2129        ((message-functionp (car actions))
2130         (funcall (car actions)))
2131        ;; Something to be evaled.
2132        (t
2133         (eval (car actions)))))
2134     (pop actions)))
2135
2136 (defun message-send-mail (&optional arg)
2137   (require 'mail-utils)
2138   (let ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2139         (case-fold-search nil)
2140         (news (message-news-p)))
2141     (save-restriction
2142       (message-narrow-to-headers)
2143       ;; Insert some headers.
2144       (let ((message-deletable-headers
2145              (if news nil message-deletable-headers)))
2146         (message-generate-headers message-required-mail-headers))
2147       ;; Let the user do all of the above.
2148       (run-hooks 'message-header-hook)
2149       (when (functionp message-header-encode-function)
2150         (funcall message-header-encode-function))
2151       (run-hooks 'message-header-encoded-hook))
2152     (if (not (message-check-mail-syntax))
2153         (progn
2154           (message "")
2155           ;;(message "Posting not performed")
2156           nil)
2157       (unwind-protect
2158           (save-excursion
2159             (set-buffer tembuf)
2160             (erase-buffer)
2161             (insert-buffer message-encoding-buffer)
2162             ;; Remove some headers.
2163             (save-restriction
2164               (message-narrow-to-headers)
2165               (message-remove-header message-ignored-mail-headers t))
2166             (goto-char (point-max))
2167             ;; require one newline at the end.
2168             (or (= (preceding-char) ?\n)
2169                 (insert ?\n))
2170             (when (and news
2171                        (or (message-fetch-field "cc")
2172                            (message-fetch-field "to")))
2173               (message-insert-courtesy-copy))
2174             (mime-edit-maybe-split-and-send
2175              (function
2176               (lambda ()
2177                 (interactive)
2178                 (funcall message-send-mail-function)
2179                 )))
2180             (funcall message-send-mail-function))
2181         (kill-buffer tembuf))
2182       (set-buffer message-edit-buffer)
2183       (push 'mail message-sent-message-via))))
2184
2185 (defun message-send-mail-with-sendmail ()
2186   "Send off the prepared buffer with sendmail."
2187   (let ((errbuf (if message-interactive
2188                     (generate-new-buffer " sendmail errors")
2189                   0))
2190         resend-to-addresses delimline)
2191     (let ((case-fold-search t))
2192       (save-restriction
2193         (message-narrow-to-headers)
2194         (setq resend-to-addresses (message-fetch-field "resent-to")))
2195       ;; Change header-delimiter to be what sendmail expects.
2196       (goto-char (point-min))
2197       (re-search-forward
2198        (concat "^" (regexp-quote mail-header-separator) "\n"))
2199       (replace-match "\n")
2200       (backward-char 1)
2201       (setq delimline (point-marker))
2202       (run-hooks 'message-send-mail-hook)
2203       ;; Insert an extra newline if we need it to work around
2204       ;; Sun's bug that swallows newlines.
2205       (goto-char (1+ delimline))
2206       (when (eval message-mailer-swallows-blank-line)
2207         (newline))
2208       (when message-interactive
2209         (save-excursion
2210           (set-buffer errbuf)
2211           (erase-buffer))))
2212     (let ((default-directory "/")
2213           (coding-system-for-write message-send-coding-system))
2214       (apply 'call-process-region
2215              (append (list (point-min) (point-max)
2216                            (if (boundp 'sendmail-program)
2217                                sendmail-program
2218                              "/usr/lib/sendmail")
2219                            nil errbuf nil "-oi")
2220                      ;; Always specify who from,
2221                      ;; since some systems have broken sendmails.
2222                      ;; But some systems are more broken with -f, so
2223                      ;; we'll let users override this.
2224                      (if (null message-sendmail-f-is-evil)
2225                          (list "-f" (user-login-name)))
2226                      ;; These mean "report errors by mail"
2227                      ;; and "deliver in background".
2228                      (if (null message-interactive) '("-oem" "-odb"))
2229                      ;; Get the addresses from the message
2230                      ;; unless this is a resend.
2231                      ;; We must not do that for a resend
2232                      ;; because we would find the original addresses.
2233                      ;; For a resend, include the specific addresses.
2234                      (if resend-to-addresses
2235                          (list resend-to-addresses)
2236                        '("-t")))))
2237     (when message-interactive
2238       (save-excursion
2239         (set-buffer errbuf)
2240         (goto-char (point-min))
2241         (while (re-search-forward "\n\n* *" nil t)
2242           (replace-match "; "))
2243         (if (not (zerop (buffer-size)))
2244             (error "Sending...failed to %s"
2245                    (buffer-substring (point-min) (point-max)))))
2246       (when (bufferp errbuf)
2247         (kill-buffer errbuf)))))
2248
2249 (defun message-send-mail-with-qmail ()
2250   "Pass the prepared message buffer to qmail-inject.
2251 Refer to the documentation for the variable `message-send-mail-function'
2252 to find out how to use this."
2253   ;; replace the header delimiter with a blank line
2254   (goto-char (point-min))
2255   (re-search-forward
2256    (concat "^" (regexp-quote mail-header-separator) "\n"))
2257   (replace-match "\n")
2258   (run-hooks 'message-send-mail-hook)
2259   ;; send the message
2260   (case
2261       (let ((coding-system-for-write message-send-coding-system))
2262         (apply
2263          'call-process-region 1 (point-max) message-qmail-inject-program
2264          nil nil nil
2265          ;; qmail-inject's default behaviour is to look for addresses on the
2266          ;; command line; if there're none, it scans the headers.
2267          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2268          ;;
2269          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2270          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2271          ;; message from stdin.
2272          ;;
2273          ;; qmail also has the advantage of not having been raped by
2274          ;; various vendors, so we don't have to allow for that, either --
2275          ;; compare this with message-send-mail-with-sendmail and weep
2276          ;; for sendmail's lost innocence.
2277          ;;
2278          ;; all this is way cool coz it lets us keep the arguments entirely
2279          ;; free for -inject-arguments -- a big win for the user and for us
2280          ;; since we don't have to play that double-guessing game and the user
2281          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2282          message-qmail-inject-args))
2283     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2284     ;; we have to look at the retval instead
2285     (0 nil)
2286     (1   (error "qmail-inject reported permanent failure"))
2287     (111 (error "qmail-inject reported transient failure"))
2288     ;; should never happen
2289     (t   (error "qmail-inject reported unknown failure"))))
2290
2291 (defun message-send-mail-with-mh ()
2292   "Send the prepared message buffer with mh."
2293   (let ((mh-previous-window-config nil)
2294         (name (mh-new-draft-name)))
2295     (setq buffer-file-name name)
2296     ;; MH wants to generate these headers itself.
2297     (when message-mh-deletable-headers
2298       (let ((headers message-mh-deletable-headers))
2299         (while headers
2300           (goto-char (point-min))
2301           (and (re-search-forward
2302                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2303                (message-delete-line))
2304           (pop headers))))
2305     (run-hooks 'message-send-mail-hook)
2306     ;; Pass it on to mh.
2307     (mh-send-letter)))
2308
2309 (defun message-send-mail-with-smtp ()
2310   "Send the prepared message buffer with SMTP."
2311   (require 'smtp)
2312   (let ((errbuf (if mail-interactive
2313                     (generate-new-buffer " smtp errors")
2314                   0))
2315         (case-fold-search nil)
2316         resend-to-addresses
2317         delimline)
2318     (unwind-protect
2319         (save-excursion
2320           (goto-char (point-max))
2321           ;; require one newline at the end.
2322           (or (= (preceding-char) ?\n)
2323               (insert ?\n))
2324           ;; Change header-delimiter to be what sendmail expects.
2325           (goto-char (point-min))
2326           (re-search-forward
2327            (concat "^" (regexp-quote mail-header-separator) "\n"))
2328           (replace-match "\n")
2329           (backward-char 1)
2330           (setq delimline (point-marker))
2331           (run-hooks 'message-send-mail-hook)
2332           ;; (sendmail-synch-aliases)
2333           ;; (if mail-aliases
2334           ;;     (expand-mail-aliases (point-min) delimline))
2335           (goto-char (point-min))
2336           ;; ignore any blank lines in the header
2337           (while (and (re-search-forward "\n\n\n*" delimline t)
2338                       (< (point) delimline))
2339             (replace-match "\n"))
2340           (let ((case-fold-search t))
2341             (goto-char (point-min))
2342             (goto-char (point-min))
2343             (while (re-search-forward "^Resent-to:" delimline t)
2344               (setq resend-to-addresses
2345                     (save-restriction
2346                       (narrow-to-region (point)
2347                                         (save-excursion
2348                                           (end-of-line)
2349                                           (point)))
2350                       (append (mail-parse-comma-list)
2351                               resend-to-addresses))))
2352 ;;; Apparently this causes a duplicate Sender.
2353 ;;;         ;; If the From is different than current user, insert Sender.
2354 ;;;         (goto-char (point-min))
2355 ;;;         (and (re-search-forward "^From:"  delimline t)
2356 ;;;              (progn
2357 ;;;                (require 'mail-utils)
2358 ;;;                (not (string-equal
2359 ;;;                      (mail-strip-quoted-names
2360 ;;;                       (save-restriction
2361 ;;;                         (narrow-to-region (point-min) delimline)
2362 ;;;                         (mail-fetch-field "From")))
2363 ;;;                      (user-login-name))))
2364 ;;;              (progn
2365 ;;;                (forward-line 1)
2366 ;;;                (insert "Sender: " (user-login-name) "\n")))
2367             ;; Don't send out a blank subject line
2368             (goto-char (point-min))
2369             (if (re-search-forward "^Subject:[ \t]*\n" delimline t)
2370                 (replace-match ""))
2371             ;; Put the "From:" field in unless for some odd reason
2372             ;; they put one in themselves.
2373             (goto-char (point-min))
2374             (if (not (re-search-forward "^From:" delimline t))
2375                 (let* ((login user-mail-address)
2376                        (fullname (user-full-name)))
2377                   (cond ((eq mail-from-style 'angles)
2378                          (insert "From: " fullname)
2379                          (let ((fullname-start (+ (point-min) 6))
2380                                (fullname-end (point-marker)))
2381                            (goto-char fullname-start)
2382                            ;; Look for a character that cannot appear unquoted
2383                            ;; according to RFC 822.
2384                            (if (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]"
2385                                                   fullname-end 1)
2386                                (progn
2387                                  ;; Quote fullname, escaping specials.
2388                                  (goto-char fullname-start)
2389                                  (insert "\"")
2390                                  (while (re-search-forward "[\"\\]"
2391                                                            fullname-end 1)
2392                                    (replace-match "\\\\\\&" t))
2393                                  (insert "\""))))
2394                          (insert " <" login ">\n"))
2395                         ((eq mail-from-style 'parens)
2396                          (insert "From: " login " (")
2397                          (let ((fullname-start (point)))
2398                            (insert fullname)
2399                            (let ((fullname-end (point-marker)))
2400                              (goto-char fullname-start)
2401                              ;; RFC 822 says \ and nonmatching parentheses
2402                              ;; must be escaped in comments.
2403                              ;; Escape every instance of ()\ ...
2404                              (while (re-search-forward "[()\\]" fullname-end 1)
2405                                (replace-match "\\\\\\&" t))
2406                              ;; ... then undo escaping of matching parentheses,
2407                              ;; including matching nested parentheses.
2408                              (goto-char fullname-start)
2409                              (while (re-search-forward 
2410                                      "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
2411                                      fullname-end 1)
2412                                (replace-match "\\1(\\3)" t)
2413                                (goto-char fullname-start))))
2414                          (insert ")\n"))
2415                         ((null mail-from-style)
2416                          (insert "From: " login "\n")))))
2417             ;; Insert an extra newline if we need it to work around
2418             ;; Sun's bug that swallows newlines.
2419             (goto-char (1+ delimline))
2420             (if (eval mail-mailer-swallows-blank-line)
2421                 (newline))
2422             ;; Find and handle any FCC fields.
2423             (goto-char (point-min))
2424             (if (re-search-forward "^FCC:" delimline t)
2425                 (mail-do-fcc delimline))
2426             (if mail-interactive
2427                 (save-excursion
2428                   (set-buffer errbuf)
2429                   (erase-buffer))))
2430           ;;
2431           ;;
2432           ;;
2433           (let ((recipient-address-list
2434                  (or resend-to-addresses
2435                      (smtp-deduce-address-list (current-buffer)
2436                                                (point-min) delimline))))
2437             (smtp-do-bcc delimline)
2438             
2439             (if recipient-address-list
2440                 (if (not (smtp-via-smtp recipient-address-list
2441                                         (current-buffer)))
2442                     (error "Sending failed; SMTP protocol error"))
2443               (error "Sending failed; no recipients"))
2444             ))
2445       (if (bufferp errbuf)
2446           (kill-buffer errbuf)))))
2447
2448 (defun message-send-news (&optional arg)
2449   (let ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2450         (case-fold-search nil)
2451         (method (if (message-functionp message-post-method)
2452                     (funcall message-post-method arg)
2453                   message-post-method))
2454         (message-syntax-checks
2455          (if arg
2456              (cons '(existing-newsgroups . disabled)
2457                    message-syntax-checks)
2458            message-syntax-checks))
2459         result)
2460     (save-restriction
2461       (message-narrow-to-headers)
2462       ;; Insert some headers.
2463       (message-generate-headers message-required-news-headers)
2464       ;; Let the user do all of the above.
2465       (run-hooks 'message-header-hook)
2466       (when (functionp message-header-encode-function)
2467         (funcall message-header-encode-function))
2468       (run-hooks 'message-header-encoded-hook))
2469     (message-cleanup-headers)
2470     (if (not (message-check-news-syntax))
2471         (progn
2472           (message "")
2473           ;;(message "Posting not performed")
2474           nil)
2475       (unwind-protect
2476           (save-excursion
2477             (set-buffer tembuf)
2478             (buffer-disable-undo (current-buffer))
2479             (erase-buffer)
2480             (insert-buffer message-encoding-buffer)
2481             ;; Remove some headers.
2482             (save-restriction
2483               (message-narrow-to-headers)
2484               ;; Remove some headers.
2485               (message-remove-header message-ignored-news-headers t))
2486             (goto-char (point-max))
2487             ;; require one newline at the end.
2488             (or (= (preceding-char) ?\n)
2489                 (insert ?\n))
2490             (mime-edit-maybe-split-and-send
2491              (function
2492               (lambda ()
2493                 (interactive)
2494                 (save-restriction
2495                   (std11-narrow-to-header mail-header-separator)
2496                   (goto-char (point-min))
2497                   (when (re-search-forward "^Message-Id:" nil t)
2498                     (delete-region (match-end 0)(std11-field-end))
2499                     (insert (concat " " (message-make-message-id)))
2500                     ))
2501                 (funcall message-send-news-function method)
2502                 )))
2503             (setq result (funcall message-send-news-function method)))
2504         (kill-buffer tembuf))
2505       (set-buffer message-edit-buffer)
2506       (if result
2507           (push 'news message-sent-message-via)
2508         (message "Couldn't send message via news: %s"
2509                  (nnheader-get-report (car method)))
2510         nil))))
2511
2512 ;; 1997-09-29 by MORIOKA Tomohiko
2513 (defun message-send-news-with-gnus (method)
2514   (let ((case-fold-search t))
2515     ;; Remove the delimiter.
2516     (goto-char (point-min))
2517     (re-search-forward
2518      (concat "^" (regexp-quote mail-header-separator) "\n"))
2519     (replace-match "\n")
2520     (backward-char 1)
2521     (run-hooks 'message-send-news-hook)
2522     ;;(require (car method))
2523     ;;(funcall (intern (format "%s-open-server" (car method)))
2524     ;;(cadr method) (cddr method))
2525     ;;(setq result
2526     ;;    (funcall (intern (format "%s-request-post" (car method)))
2527     ;;             (cadr method)))
2528     (gnus-open-server method)
2529     (gnus-request-post method)
2530     ))
2531
2532 ;;;
2533 ;;; Header generation & syntax checking.
2534 ;;;
2535
2536 (defmacro message-check (type &rest forms)
2537   "Eval FORMS if TYPE is to be checked."
2538   `(or (message-check-element ,type)
2539        (save-excursion
2540          ,@forms)))
2541
2542 (put 'message-check 'lisp-indent-function 1)
2543 (put 'message-check 'edebug-form-spec '(form body))
2544
2545 (defun message-check-element (type)
2546   "Returns non-nil if this type is not to be checked."
2547   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2548       t
2549     (let ((able (assq type message-syntax-checks)))
2550       (and (consp able)
2551            (eq (cdr able) 'disabled)))))
2552
2553 (defun message-check-news-syntax ()
2554   "Check the syntax of the message."
2555   (save-excursion
2556     (save-restriction
2557       (widen)
2558       (and
2559        ;; We narrow to the headers and check them first.
2560        (save-excursion
2561          (save-restriction
2562            (message-narrow-to-headers)
2563            (message-check-news-header-syntax)))
2564        ;; Check the body.
2565        (save-excursion
2566          (set-buffer message-edit-buffer)
2567          (message-check-news-body-syntax))))))
2568
2569 (defun message-check-news-header-syntax ()
2570   (and
2571    ;; Check the Subject header.
2572    (message-check 'subject
2573      (let* ((case-fold-search t)
2574             (subject (message-fetch-field "subject")))
2575        (or
2576         (and subject
2577              (not (string-match "\\`[ \t]*\\'" subject)))
2578         (ignore
2579          (message
2580           "The subject field is empty or missing.  Posting is denied.")))))
2581    ;; Check for commands in Subject.
2582    (message-check 'subject-cmsg
2583      (if (string-match "^cmsg " (message-fetch-field "subject"))
2584          (y-or-n-p
2585           "The control code \"cmsg\" is in the subject.  Really post? ")
2586        t))
2587    ;; Check for multiple identical headers.
2588    (message-check 'multiple-headers
2589      (let (found)
2590        (while (and (not found)
2591                    (re-search-forward "^[^ \t:]+: " nil t))
2592          (save-excursion
2593            (or (re-search-forward
2594                 (concat "^"
2595                         (regexp-quote
2596                          (setq found
2597                                (buffer-substring
2598                                 (match-beginning 0) (- (match-end 0) 2))))
2599                         ":")
2600                 nil t)
2601                (setq found nil))))
2602        (if found
2603            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2604          t)))
2605    ;; Check for Version and Sendsys.
2606    (message-check 'sendsys
2607      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2608          (y-or-n-p
2609           (format "The article contains a %s command.  Really post? "
2610                   (buffer-substring (match-beginning 0)
2611                                     (1- (match-end 0)))))
2612        t))
2613    ;; See whether we can shorten Followup-To.
2614    (message-check 'shorten-followup-to
2615      (let ((newsgroups (message-fetch-field "newsgroups"))
2616            (followup-to (message-fetch-field "followup-to"))
2617            to)
2618        (when (and newsgroups
2619                   (string-match "," newsgroups)
2620                   (not followup-to)
2621                   (not
2622                    (zerop
2623                     (length
2624                      (setq to (completing-read
2625                                "Followups to: (default all groups) "
2626                                (mapcar (lambda (g) (list g))
2627                                        (cons "poster"
2628                                              (message-tokenize-header
2629                                               newsgroups)))))))))
2630          (goto-char (point-min))
2631          (insert "Followup-To: " to "\n"))
2632        t))
2633    ;; Check "Shoot me".
2634    (message-check 'shoot
2635      (if (re-search-forward
2636           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2637          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2638        t))
2639    ;; Check for Approved.
2640    (message-check 'approved
2641      (if (re-search-forward "^Approved:" nil t)
2642          (y-or-n-p "The article contains an Approved header.  Really post? ")
2643        t))
2644    ;; Check the Message-ID header.
2645    (message-check 'message-id
2646      (let* ((case-fold-search t)
2647             (message-id (message-fetch-field "message-id" t)))
2648        (or (not message-id)
2649            ;; Is there an @ in the ID?
2650            (and (string-match "@" message-id)
2651                 ;; Is there a dot in the ID?
2652                 (string-match "@[^.]*\\." message-id)
2653                 ;; Does the ID end with a dot?
2654                 (not (string-match "\\.>" message-id)))
2655            (y-or-n-p
2656             (format "The Message-ID looks strange: \"%s\".  Really post? "
2657                     message-id)))))
2658    ;; Check the Newsgroups & Followup-To headers.
2659    (message-check 'existing-newsgroups
2660      (let* ((case-fold-search t)
2661             (newsgroups (message-fetch-field "newsgroups"))
2662             (followup-to (message-fetch-field "followup-to"))
2663             (groups (message-tokenize-header
2664                      (if followup-to
2665                          (concat newsgroups "," followup-to)
2666                        newsgroups)))
2667             (hashtb (and (boundp 'gnus-active-hashtb)
2668                          gnus-active-hashtb))
2669             errors)
2670        (if (or (not hashtb)
2671                (not (boundp 'gnus-read-active-file))
2672                (not gnus-read-active-file)
2673                (eq gnus-read-active-file 'some))
2674            t
2675          (while groups
2676            (when (and (not (boundp (intern (car groups) hashtb)))
2677                       (not (equal (car groups) "poster")))
2678              (push (car groups) errors))
2679            (pop groups))
2680          (if (not errors)
2681              t
2682            (y-or-n-p
2683             (format
2684              "Really post to %s unknown group%s: %s "
2685              (if (= (length errors) 1) "this" "these")
2686              (if (= (length errors) 1) "" "s")
2687              (mapconcat 'identity errors ", ")))))))
2688    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2689    (message-check 'valid-newsgroups
2690      (let ((case-fold-search t)
2691            (headers '("Newsgroups" "Followup-To"))
2692            header error)
2693        (while (and headers (not error))
2694          (when (setq header (mail-fetch-field (car headers)))
2695            (if (or
2696                 (not
2697                  (string-match
2698                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2699                   header))
2700                 (memq
2701                  nil (mapcar
2702                       (lambda (g)
2703                         (not (string-match "\\.\\'\\|\\.\\." g)))
2704                       (message-tokenize-header header ","))))
2705                (setq error t)))
2706          (unless error
2707            (pop headers)))
2708        (if (not error)
2709            t
2710          (y-or-n-p
2711           (format "The %s header looks odd: \"%s\".  Really post? "
2712                   (car headers) header)))))
2713    (message-check 'repeated-newsgroups
2714      (let ((case-fold-search t)
2715            (headers '("Newsgroups" "Followup-To"))
2716            header error groups group)
2717        (while (and headers
2718                    (not error))
2719          (when (setq header (mail-fetch-field (pop headers)))
2720            (setq groups (message-tokenize-header header ","))
2721            (while (setq group (pop groups))
2722              (when (member group groups)
2723                (setq error group
2724                      groups nil)))))
2725        (if (not error)
2726            t
2727          (y-or-n-p
2728           (format "Group %s is repeated in headers.  Really post? " error)))))
2729    ;; Check the From header.
2730    (message-check 'from
2731      (let* ((case-fold-search t)
2732             (from (message-fetch-field "from"))
2733             (ad (nth 1 (mail-extract-address-components from))))
2734        (cond
2735         ((not from)
2736          (message "There is no From line.  Posting is denied.")
2737          nil)
2738         ((or (not (string-match "@[^\\.]*\\." ad)) ;larsi@ifi
2739              (string-match "\\.\\." ad) ;larsi@ifi..uio
2740              (string-match "@\\." ad)   ;larsi@.ifi.uio
2741              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2742              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2743              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2744          (message
2745           "Denied posting -- the From looks strange: \"%s\"." from)
2746          nil)
2747         (t t))))))
2748
2749 (defun message-check-news-body-syntax ()
2750   (and
2751    ;; Check for long lines.
2752    (message-check 'long-lines
2753      (goto-char (point-min))
2754      (re-search-forward
2755       (concat "^" (regexp-quote mail-header-separator) "$"))
2756      (while (and
2757              (progn
2758                (end-of-line)
2759                (< (current-column) 80))
2760              (zerop (forward-line 1))))
2761      (or (bolp)
2762          (eobp)
2763          (y-or-n-p
2764           "You have lines longer than 79 characters.  Really post? ")))
2765    ;; Check whether the article is empty.
2766    (message-check 'empty
2767      (goto-char (point-min))
2768      (re-search-forward
2769       (concat "^" (regexp-quote mail-header-separator) "$"))
2770      (forward-line 1)
2771      (let ((b (point)))
2772        (goto-char (point-max))
2773        (re-search-backward message-signature-separator nil t)
2774        (beginning-of-line)
2775        (or (re-search-backward "[^ \n\t]" b t)
2776            (y-or-n-p "Empty article.  Really post? "))))
2777    ;; Check for control characters.
2778    (message-check 'control-chars
2779      (if (re-search-forward "[\000-\007\013\015-\037\200-\237]" nil t)
2780          (y-or-n-p
2781           "The article contains control characters.  Really post? ")
2782        t))
2783    ;; Check 8bit characters.
2784    (message-check '8bit
2785      (message-check-8bit))
2786    ;; Check excessive size.
2787    (message-check 'size
2788      (if (> (buffer-size) 60000)
2789          (y-or-n-p
2790           (format "The article is %d octets long.  Really post? "
2791                   (buffer-size)))
2792        t))
2793    ;; Check whether any new text has been added.
2794    (message-check 'new-text
2795      (or
2796       (not message-checksum)
2797       (not (eq (message-checksum) message-checksum))
2798       (y-or-n-p
2799        "It looks like no new text has been added.  Really post? ")))
2800    ;; Check the length of the signature.
2801    (message-check 'signature
2802      (goto-char (point-max))
2803      (if (or (not (re-search-backward message-signature-separator nil t))
2804              (search-forward message-forward-end-separator nil t))
2805          t
2806        (if (> (count-lines (point) (point-max)) 5)
2807            (y-or-n-p
2808             (format
2809              "Your .sig is %d lines; it should be max 4.  Really post? "
2810              (1- (count-lines (point) (point-max)))))
2811          t)))))
2812
2813 (defun message-check-mail-syntax ()
2814   "Check the syntax of the message."
2815   (save-excursion
2816     (save-restriction
2817       (widen)
2818       (and
2819        ;; We narrow to the headers and check them first.
2820        (save-excursion
2821          (save-restriction
2822            (message-narrow-to-headers)
2823            (message-check-mail-header-syntax)))
2824        ;; Check the body.
2825        (save-excursion
2826          (set-buffer message-edit-buffer)
2827          (message-check-mail-body-syntax))))))
2828
2829 (defun message-check-mail-header-syntax ()
2830   t)
2831
2832 (defun message-check-mail-body-syntax ()
2833   (and
2834    ;; Check 8bit characters.
2835    (message-check '8bit
2836      (message-check-8bit)
2837      )))
2838
2839 (defun message-check-8bit ()
2840   "Check the article contains 8bit characters."
2841   (save-excursion
2842     (set-buffer message-encoding-buffer)
2843     (message-narrow-to-headers)
2844     (let* ((case-fold-search t)
2845            (field-value (message-fetch-field "content-transfer-encoding")))
2846       (if (and field-value
2847                (member (downcase field-value) message-8bit-encoding-list))
2848           t
2849         (widen)
2850         (set-buffer (get-buffer-create " message syntax"))
2851         (erase-buffer)
2852         (goto-char (point-min))
2853         (set-buffer-multibyte nil)
2854         (insert-buffer message-encoding-buffer)
2855         (goto-char (point-min))
2856         (if (re-search-forward "[^\x00-\x7f]" nil t)
2857             (y-or-n-p
2858              "The article contains 8bit characters.  Really post? ")
2859           t)))))
2860
2861 (defun message-checksum ()
2862   "Return a \"checksum\" for the current buffer."
2863   (let ((sum 0))
2864     (save-excursion
2865       (goto-char (point-min))
2866       (re-search-forward
2867        (concat "^" (regexp-quote mail-header-separator) "$"))
2868       (while (not (eobp))
2869         (when (not (looking-at "[ \t\n]"))
2870           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
2871                             (following-char))))
2872         (forward-char 1)))
2873     sum))
2874
2875 (defun message-do-fcc ()
2876   "Process Fcc headers in the current buffer."
2877   (let ((case-fold-search t)
2878         (coding-system-for-write 'raw-text)
2879         list file)
2880     (save-excursion
2881       (set-buffer (get-buffer-create " *message temp*"))
2882       (buffer-disable-undo (current-buffer))
2883       (erase-buffer)
2884       (insert-buffer-substring message-encoding-buffer)
2885       (save-restriction
2886         (message-narrow-to-headers)
2887         (while (setq file (message-fetch-field "fcc"))
2888           (push file list)
2889           (message-remove-header "fcc" nil t)))
2890       (goto-char (point-min))
2891       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
2892       (replace-match "" t t)
2893       ;; Process FCC operations.
2894       (while list
2895         (setq file (pop list))
2896         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
2897             ;; Pipe the article to the program in question.
2898             (call-process-region (point-min) (point-max) shell-file-name
2899                                  nil nil nil shell-command-switch
2900                                  (match-string 1 file))
2901           ;; Save the article.
2902           (setq file (expand-file-name file))
2903           (unless (file-exists-p (file-name-directory file))
2904             (make-directory (file-name-directory file) t))
2905           (if (and message-fcc-handler-function
2906                    (not (eq message-fcc-handler-function 'rmail-output)))
2907               (funcall message-fcc-handler-function file)
2908             (if (and (file-readable-p file) (mail-file-babyl-p file))
2909                 (rmail-output file 1 nil t)
2910               (let ((mail-use-rfc822 t))
2911                 (rmail-output file 1 t t))))))
2912
2913       (kill-buffer (current-buffer)))))
2914
2915 (defun message-output (filename)
2916   "Append this article to Unix/babyl mail file.."
2917   (if (and (file-readable-p filename)
2918            (mail-file-babyl-p filename))
2919       (gnus-output-to-rmail filename t)
2920     (gnus-output-to-mail filename t)))
2921
2922 (defun message-cleanup-headers ()
2923   "Do various automatic cleanups of the headers."
2924   ;; Remove empty lines in the header.
2925   (save-restriction
2926     (message-narrow-to-headers)
2927     ;; Remove blank lines.
2928     (while (re-search-forward "^[ \t]*\n" nil t)
2929       (replace-match "" t t))
2930
2931     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
2932     ;; spaces to comma and eliminate spaces around commas.  Eliminate
2933     ;; embedded line breaks.
2934     (goto-char (point-min))
2935     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2936       (save-restriction
2937         (narrow-to-region
2938          (point)
2939          (if (re-search-forward "^[^ \t]" nil t)
2940              (match-beginning 0)
2941            (forward-line 1)
2942            (point)))
2943         (goto-char (point-min))
2944         (while (re-search-forward "\n[ \t]+" nil t)
2945           (replace-match " " t t))      ;No line breaks (too confusing)
2946         (goto-char (point-min))
2947         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
2948           (replace-match "," t t))
2949         (goto-char (point-min))
2950         ;; Remove trailing commas.
2951         (when (re-search-forward ",+$" nil t)
2952           (replace-match "" t t))))))
2953
2954 (defun message-make-date ()
2955   "Make a valid data header."
2956   (let ((now (current-time)))
2957     (timezone-make-date-arpa-standard
2958      (current-time-string now) (current-time-zone now))))
2959
2960 (defun message-make-message-id ()
2961   "Make a unique Message-ID."
2962   (concat "<" (message-unique-id)
2963           (let ((psubject (save-excursion (message-fetch-field "subject")))
2964                 (psupersedes
2965                  (save-excursion (message-fetch-field "supersedes"))))
2966             (if (or
2967                  (and message-reply-headers
2968                       (mail-header-references message-reply-headers)
2969                       (mail-header-subject message-reply-headers)
2970                       psubject
2971                       (mail-header-subject message-reply-headers)
2972                       (not (string=
2973                             (message-strip-subject-re
2974                              (mail-header-subject message-reply-headers))
2975                             (message-strip-subject-re psubject))))
2976                  (and psupersedes
2977                       (string-match "_-_@" psupersedes)))
2978                 "_-_" ""))
2979           "@" (message-make-fqdn) ">"))
2980
2981 (defvar message-unique-id-char nil)
2982
2983 ;; If you ever change this function, make sure the new version
2984 ;; cannot generate IDs that the old version could.
2985 ;; You might for example insert a "." somewhere (not next to another dot
2986 ;; or string boundary), or modify the "fsf" string.
2987 (defun message-unique-id ()
2988   ;; Don't use microseconds from (current-time), they may be unsupported.
2989   ;; Instead we use this randomly inited counter.
2990   (setq message-unique-id-char
2991         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2992            ;; (current-time) returns 16-bit ints,
2993            ;; and 2^16*25 just fits into 4 digits i base 36.
2994            (* 25 25)))
2995   (let ((tm (current-time)))
2996     (concat
2997      (if (memq system-type '(ms-dos emx vax-vms))
2998          (let ((user (downcase (user-login-name))))
2999            (while (string-match "[^a-z0-9_]" user)
3000              (aset user (match-beginning 0) ?_))
3001            user)
3002        (message-number-base36 (user-uid) -1))
3003      (message-number-base36 (+ (car   tm)
3004                                (lsh (% message-unique-id-char 25) 16)) 4)
3005      (message-number-base36 (+ (nth 1 tm)
3006                                (lsh (/ message-unique-id-char 25) 16)) 4)
3007      ;; Append the newsreader name, because while the generated
3008      ;; ID is unique to this newsreader, other newsreaders might
3009      ;; otherwise generate the same ID via another algorithm.
3010      ".fsf")))
3011
3012 (defun message-number-base36 (num len)
3013   (if (if (< len 0)
3014           (<= num 0)
3015         (= len 0))
3016       ""
3017     (concat (message-number-base36 (/ num 36) (1- len))
3018             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
3019                                   (% num 36))))))
3020
3021 (defun message-make-organization ()
3022   "Make an Organization header."
3023   (let* ((organization
3024           (when message-user-organization
3025                 (if (message-functionp message-user-organization)
3026                     (funcall message-user-organization)
3027                   message-user-organization))))
3028     (save-excursion
3029       (message-set-work-buffer)
3030       (cond ((stringp organization)
3031              (insert organization))
3032             ((and (eq t organization)
3033                   message-user-organization-file
3034                   (file-exists-p message-user-organization-file))
3035              (insert-file-contents message-user-organization-file)))
3036       (goto-char (point-min))
3037       (while (re-search-forward "[\t\n]+" nil t)
3038         (replace-match "" t t))
3039       (unless (zerop (buffer-size))
3040         (buffer-string)))))
3041
3042 (defun message-make-lines ()
3043   "Count the number of lines and return numeric string."
3044   (save-excursion
3045     (save-restriction
3046       (widen)
3047       (goto-char (point-min))
3048       (re-search-forward
3049        (concat "^" (regexp-quote mail-header-separator) "$"))
3050       (forward-line 1)
3051       (int-to-string (count-lines (point) (point-max))))))
3052
3053 (defun message-make-in-reply-to ()
3054   "Return the In-Reply-To header for this message."
3055   (when message-reply-headers
3056     (let ((from (mail-header-from message-reply-headers))
3057           (date (mail-header-date message-reply-headers))
3058           (msg-id (mail-header-message-id message-reply-headers)))
3059       (when msg-id
3060         (concat msg-id
3061                 (when from
3062                   (let ((stop-pos
3063                          (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
3064                     (concat " ("
3065                             (if (and stop-pos
3066                                      (not (zerop stop-pos)))
3067                                 (substring from 0 stop-pos) from)
3068                             "'s message of \""
3069                             (if (or (not date) (string= date ""))
3070                                 "(unknown date)" date)
3071                             "\")"))))))))
3072
3073 (defun message-make-distribution ()
3074   "Make a Distribution header."
3075   (let ((orig-distribution (message-fetch-reply-field "distribution")))
3076     (cond ((message-functionp message-distribution-function)
3077            (funcall message-distribution-function))
3078           (t orig-distribution))))
3079
3080 (defun message-make-expires ()
3081   "Return an Expires header based on `message-expires'."
3082   (let ((current (current-time))
3083         (future (* 1.0 message-expires 60 60 24)))
3084     ;; Add the future to current.
3085     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
3086     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
3087     ;; Return the date in the future in UT.
3088     (timezone-make-date-arpa-standard
3089      (current-time-string current) (current-time-zone current) '(0 "UT"))))
3090
3091 (defun message-make-path ()
3092   "Return uucp path."
3093   (let ((login-name (user-login-name)))
3094     (cond ((null message-user-path)
3095            (concat (system-name) "!" login-name))
3096           ((stringp message-user-path)
3097            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
3098            (concat message-user-path "!" login-name))
3099           (t login-name))))
3100
3101 (defun message-make-from ()
3102   "Make a From header."
3103   (let* ((style message-from-style)
3104          (login (message-make-address))
3105          (fullname
3106           (or (and (boundp 'user-full-name)
3107                    user-full-name)
3108               (user-full-name))))
3109     (when (string= fullname "&")
3110       (setq fullname (user-login-name)))
3111     (save-excursion
3112       (message-set-work-buffer)
3113       (cond
3114        ((or (null style)
3115             (equal fullname ""))
3116         (insert login))
3117        ((or (eq style 'angles)
3118             (and (not (eq style 'parens))
3119                  ;; Use angles if no quoting is needed, or if parens would
3120                  ;; need quoting too.
3121                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
3122                      (let ((tmp (concat fullname nil)))
3123                        (while (string-match "([^()]*)" tmp)
3124                          (aset tmp (match-beginning 0) ?-)
3125                          (aset tmp (1- (match-end 0)) ?-))
3126                        (string-match "[\\()]" tmp)))))
3127         (insert fullname)
3128         (goto-char (point-min))
3129         ;; Look for a character that cannot appear unquoted
3130         ;; according to RFC 822.
3131         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
3132           ;; Quote fullname, escaping specials.
3133           (goto-char (point-min))
3134           (insert "\"")
3135           (while (re-search-forward "[\"\\]" nil 1)
3136             (replace-match "\\\\\\&" t))
3137           (insert "\""))
3138         (insert " <" login ">"))
3139        (t                               ; 'parens or default
3140         (insert login " (")
3141         (let ((fullname-start (point)))
3142           (insert fullname)
3143           (goto-char fullname-start)
3144           ;; RFC 822 says \ and nonmatching parentheses
3145           ;; must be escaped in comments.
3146           ;; Escape every instance of ()\ ...
3147           (while (re-search-forward "[()\\]" nil 1)
3148             (replace-match "\\\\\\&" t))
3149           ;; ... then undo escaping of matching parentheses,
3150           ;; including matching nested parentheses.
3151           (goto-char fullname-start)
3152           (while (re-search-forward
3153                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3154                   nil 1)
3155             (replace-match "\\1(\\3)" t)
3156             (goto-char fullname-start)))
3157         (insert ")")))
3158       (buffer-string))))
3159
3160 (defun message-make-sender ()
3161   "Return the \"real\" user address.
3162 This function tries to ignore all user modifications, and
3163 give as trustworthy answer as possible."
3164   (concat (user-login-name) "@" (system-name)))
3165
3166 (defun message-make-address ()
3167   "Make the address of the user."
3168   (or (message-user-mail-address)
3169       (concat (user-login-name) "@" (message-make-domain))))
3170
3171 (defun message-user-mail-address ()
3172   "Return the pertinent part of `user-mail-address'."
3173   (when user-mail-address
3174     (if (string-match " " user-mail-address)
3175         (nth 1 (mail-extract-address-components user-mail-address))
3176       user-mail-address)))
3177
3178 (defun message-make-fqdn ()
3179   "Return user's fully qualified domain name."
3180   (let ((system-name (system-name))
3181         (user-mail (message-user-mail-address)))
3182     (cond
3183      ((string-match "[^.]\\.[^.]" system-name)
3184       ;; `system-name' returned the right result.
3185       system-name)
3186      ;; Try `mail-host-address'.
3187      ((and (boundp 'mail-host-address)
3188            (stringp mail-host-address)
3189            (string-match "\\." mail-host-address))
3190       mail-host-address)
3191      ;; We try `user-mail-address' as a backup.
3192      ((and user-mail
3193            (string-match "\\." user-mail)
3194            (string-match "@\\(.*\\)\\'" user-mail))
3195       (match-string 1 user-mail))
3196      ;; Default to this bogus thing.
3197      (t
3198       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
3199
3200 (defun message-make-host-name ()
3201   "Return the name of the host."
3202   (let ((fqdn (message-make-fqdn)))
3203     (string-match "^[^.]+\\." fqdn)
3204     (substring fqdn 0 (1- (match-end 0)))))
3205
3206 (defun message-make-domain ()
3207   "Return the domain name."
3208   (or mail-host-address
3209       (message-make-fqdn)))
3210
3211 (defun message-make-user-agent ()
3212   "Return user-agent info."
3213   (if message-user-agent
3214       (save-excursion
3215         (goto-char (point-min))
3216         (let ((case-fold-search t)
3217               user-agent beg p end)
3218           (if (re-search-forward "^User-Agent:[ \t]*" nil t)
3219               (progn
3220                 (setq beg (match-beginning 0)
3221                       p (match-end 0)
3222                       end (std11-field-end)
3223                       user-agent (buffer-substring p end))
3224                 (delete-region beg (1+ end))
3225                 (concat message-user-agent " " user-agent)
3226                 )
3227             message-user-agent)))))
3228
3229 (defun message-generate-headers (headers)
3230   "Prepare article HEADERS.
3231 Headers already prepared in the buffer are not modified."
3232   (save-restriction
3233     (message-narrow-to-headers)
3234     (let* ((Date (message-make-date))
3235            (Message-ID (message-make-message-id))
3236            (Organization (message-make-organization))
3237            (From (message-make-from))
3238            (Path (message-make-path))
3239            (Subject nil)
3240            (Newsgroups nil)
3241            (In-Reply-To (message-make-in-reply-to))
3242            (To nil)
3243            (Distribution (message-make-distribution))
3244            (Lines (message-make-lines))
3245            (User-Agent (message-make-user-agent))
3246            (Expires (message-make-expires))
3247            (case-fold-search t)
3248            header value elem)
3249       ;; First we remove any old generated headers.
3250       (let ((headers message-deletable-headers))
3251         (unless (buffer-modified-p)
3252           (setq headers (delq 'Message-ID (copy-sequence headers))))
3253         (while headers
3254           (goto-char (point-min))
3255           (and (re-search-forward
3256                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3257                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3258                (message-delete-line))
3259           (pop headers)))
3260       ;; Go through all the required headers and see if they are in the
3261       ;; articles already.  If they are not, or are empty, they are
3262       ;; inserted automatically - except for Subject, Newsgroups and
3263       ;; Distribution.
3264       (while headers
3265         (goto-char (point-min))
3266         (setq elem (pop headers))
3267         (if (consp elem)
3268             (if (eq (car elem) 'optional)
3269                 (setq header (cdr elem))
3270               (setq header (car elem)))
3271           (setq header elem))
3272         (when (or (not (re-search-forward
3273                         (concat "^"
3274                                 (regexp-quote
3275                                  (downcase
3276                                   (if (stringp header)
3277                                       header
3278                                     (symbol-name header))))
3279                                 ":")
3280                         nil t))
3281                   (progn
3282                     ;; The header was found.  We insert a space after the
3283                     ;; colon, if there is none.
3284                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
3285                     ;; Find out whether the header is empty...
3286                     (looking-at "[ \t]*$")))
3287           ;; So we find out what value we should insert.
3288           (setq value
3289                 (cond
3290                  ((and (consp elem) (eq (car elem) 'optional))
3291                   ;; This is an optional header.  If the cdr of this
3292                   ;; is something that is nil, then we do not insert
3293                   ;; this header.
3294                   (setq header (cdr elem))
3295                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3296                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3297                  ((consp elem)
3298                   ;; The element is a cons.  Either the cdr is a
3299                   ;; string to be inserted verbatim, or it is a
3300                   ;; function, and we insert the value returned from
3301                   ;; this function.
3302                   (or (and (stringp (cdr elem)) (cdr elem))
3303                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3304                  ((and (boundp header) (symbol-value header))
3305                   ;; The element is a symbol.  We insert the value
3306                   ;; of this symbol, if any.
3307                   (symbol-value header))
3308                  (t
3309                   ;; We couldn't generate a value for this header,
3310                   ;; so we just ask the user.
3311                   (read-from-minibuffer
3312                    (format "Empty header for %s; enter value: " header)))))
3313           ;; Finally insert the header.
3314           (when (and value
3315                      (not (equal value "")))
3316             (save-excursion
3317               (if (bolp)
3318                   (progn
3319                     ;; This header didn't exist, so we insert it.
3320                     (goto-char (point-max))
3321                     (insert (if (stringp header) header (symbol-name header))
3322                             ": " value "\n")
3323                     (forward-line -1))
3324                 ;; The value of this header was empty, so we clear
3325                 ;; totally and insert the new value.
3326                 (delete-region (point) (gnus-point-at-eol))
3327                 (insert value))
3328               ;; Add the deletable property to the headers that require it.
3329               (and (memq header message-deletable-headers)
3330                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3331                    (add-text-properties
3332                     (point) (match-end 0)
3333                     '(message-deletable t face italic) (current-buffer)))))))
3334       ;; Insert new Sender if the From is strange.
3335       (let ((from (message-fetch-field "from"))
3336             (sender (message-fetch-field "sender"))
3337             (secure-sender (message-make-sender)))
3338         (when (and from
3339                    (not (message-check-element 'sender))
3340                    (not (string=
3341                          (downcase
3342                           (cadr (mail-extract-address-components from)))
3343                          (downcase secure-sender)))
3344                    (or (null sender)
3345                        (not
3346                         (string=
3347                          (downcase
3348                           (cadr (mail-extract-address-components sender)))
3349                          (downcase secure-sender)))))
3350           (goto-char (point-min))
3351           ;; Rename any old Sender headers to Original-Sender.
3352           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3353             (beginning-of-line)
3354             (insert "Original-")
3355             (beginning-of-line))
3356           (when (or (message-news-p)
3357                     (string-match "@.+\\.." secure-sender))
3358             (insert "Sender: " secure-sender "\n")))))))
3359
3360 (defun message-insert-courtesy-copy ()
3361   "Insert a courtesy message in mail copies of combined messages."
3362   (let (newsgroups)
3363     (save-excursion
3364       (save-restriction
3365         (message-narrow-to-headers)
3366         (when (setq newsgroups (message-fetch-field "newsgroups"))
3367           (goto-char (point-max))
3368           (insert "Posted-To: " newsgroups "\n")))
3369       (forward-line 1)
3370       (when message-courtesy-message
3371         (cond
3372          ((string-match "%s" message-courtesy-message)
3373           (insert (format message-courtesy-message newsgroups)))
3374          (t
3375           (insert message-courtesy-message)))))))
3376
3377 ;;;
3378 ;;; Setting up a message buffer
3379 ;;;
3380
3381 (defun message-fill-address (header value)
3382   (save-restriction
3383     (narrow-to-region (point) (point))
3384     (insert (capitalize (symbol-name header))
3385             ": "
3386             (if (consp value) (car value) value)
3387             "\n")
3388     (narrow-to-region (point-min) (1- (point-max)))
3389     (let (quoted last)
3390       (goto-char (point-min))
3391       (while (not (eobp))
3392         (skip-chars-forward "^,\"" (point-max))
3393         (if (or (= (following-char) ?,)
3394                 (eobp))
3395             (when (not quoted)
3396               (if (and (> (current-column) 78)
3397                        last)
3398                   (progn
3399                     (save-excursion
3400                       (goto-char last)
3401                       (insert "\n\t"))
3402                     (setq last (1+ (point))))
3403                 (setq last (1+ (point)))))
3404           (setq quoted (not quoted)))
3405         (unless (eobp)
3406           (forward-char 1))))
3407     (goto-char (point-max))
3408     (widen)
3409     (forward-line 1)))
3410
3411 (defun message-fill-references (header value)
3412   (insert (capitalize (symbol-name header))
3413           ": "
3414           (std11-fill-msg-id-list-string
3415            (if (consp value) (car value) value))
3416           "\n"))
3417
3418 (defun message-fill-header (header value)
3419   (let ((begin (point))
3420         (fill-column 990)
3421         (fill-prefix "\t"))
3422     (insert (capitalize (symbol-name header))
3423             ": "
3424             (if (consp value) (car value) value)
3425             "\n")
3426     (save-restriction
3427       (narrow-to-region begin (point))
3428       (fill-region-as-paragraph begin (point))
3429       ;; Tapdance around looong Message-IDs.
3430       (forward-line -1)
3431       (when (looking-at "[ \t]*$")
3432         (message-delete-line))
3433       (goto-char begin)
3434       (re-search-forward ":" nil t)
3435       (when (looking-at "\n[ \t]+")
3436         (replace-match " " t t))
3437       (goto-char (point-max)))))
3438
3439 (defun message-shorten-references (header references)
3440   "Limit REFERENCES to be shorter than 988 characters."
3441   (let ((max 988)
3442         (cut 4)
3443         refs)
3444     (nnheader-temp-write nil
3445       (insert references)
3446       (goto-char (point-min))
3447       (while (re-search-forward "<[^>]+>" nil t)
3448         (push (match-string 0) refs))
3449       (setq refs (nreverse refs))
3450       (while (> (length (mapconcat 'identity refs " ")) max)
3451         (when (< (length refs) (1+ cut))
3452           (decf cut))
3453         (setcdr (nthcdr cut refs) (cddr (nthcdr cut refs)))))
3454     (insert (capitalize (symbol-name header)) ": "
3455             (mapconcat 'identity refs " ") "\n")))
3456
3457 (defun message-position-point ()
3458   "Move point to where the user probably wants to find it."
3459   (message-narrow-to-headers)
3460   (cond
3461    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3462     (search-backward ":" )
3463     (widen)
3464     (forward-char 1)
3465     (if (= (following-char) ? )
3466         (forward-char 1)
3467       (insert " ")))
3468    (t
3469     (goto-char (point-max))
3470     (widen)
3471     (forward-line 1)
3472     (unless (looking-at "$")
3473       (forward-line 2)))
3474    (sit-for 0)))
3475
3476 (defun message-buffer-name (type &optional to group)
3477   "Return a new (unique) buffer name based on TYPE and TO."
3478   (cond
3479    ;; Check whether `message-generate-new-buffers' is a function,
3480    ;; and if so, call it.
3481    ((message-functionp message-generate-new-buffers)
3482     (funcall message-generate-new-buffers type to group))
3483    ;; Generate a new buffer name The Message Way.
3484    (message-generate-new-buffers
3485     (generate-new-buffer-name
3486      (concat "*" type
3487              (if to
3488                  (concat " to "
3489                          (or (car (mail-extract-address-components to))
3490                              to) "")
3491                "")
3492              (if (and group (not (string= group ""))) (concat " on " group) "")
3493              "*")))
3494    ;; Use standard name.
3495    (t
3496     (format "*%s message*" type))))
3497
3498 (defun message-pop-to-buffer (name)
3499   "Pop to buffer NAME, and warn if it already exists and is modified."
3500   (let ((pop-up-frames pop-up-frames)
3501         (special-display-buffer-names special-display-buffer-names)
3502         (special-display-regexps special-display-regexps)
3503         (same-window-buffer-names same-window-buffer-names)
3504         (same-window-regexps same-window-regexps)
3505         (buffer (get-buffer name))
3506         (cur (current-buffer)))
3507     (if (or (and (featurep 'xemacs)
3508                  (not (eq 'tty (device-type))))
3509             window-system
3510             (>= emacs-major-version 20))
3511         (when message-use-multi-frames
3512           (setq pop-up-frames t
3513                 special-display-buffer-names nil
3514                 special-display-regexps nil
3515                 same-window-buffer-names nil
3516                 same-window-regexps nil))
3517       (setq pop-up-frames nil))
3518     (if (and buffer
3519              (buffer-name buffer))
3520         (progn
3521           (set-buffer (pop-to-buffer buffer))
3522           (when (and (buffer-modified-p)
3523                      (not (y-or-n-p
3524                            "Message already being composed; erase? ")))
3525             (error "Message being composed")))
3526       (set-buffer (pop-to-buffer name)))
3527     (erase-buffer)
3528     (message-mode)
3529     (when pop-up-frames
3530       (make-local-variable 'message-original-frame)
3531       (setq message-original-frame (selected-frame)))))
3532
3533 (defun message-do-send-housekeeping ()
3534   "Kill old message buffers."
3535   ;; We might have sent this buffer already.  Delete it from the
3536   ;; list of buffers.
3537   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3538   (while (and message-max-buffers
3539               message-buffer-list
3540               (>= (length message-buffer-list) message-max-buffers))
3541     ;; Kill the oldest buffer -- unless it has been changed.
3542     (let ((buffer (pop message-buffer-list)))
3543       (when (and (buffer-name buffer)
3544                  (not (buffer-modified-p buffer)))
3545         (kill-buffer buffer))))
3546   ;; Rename the buffer.
3547   (if message-send-rename-function
3548       (funcall message-send-rename-function)
3549     (when (string-match "\\`\\*" (buffer-name))
3550       (rename-buffer
3551        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3552   ;; Push the current buffer onto the list.
3553   (when message-max-buffers
3554     (setq message-buffer-list
3555           (nconc message-buffer-list (list (current-buffer))))))
3556
3557 (defvar mc-modes-alist)
3558 (defun message-setup (headers &optional replybuffer actions)
3559   (when (and (boundp 'mc-modes-alist)
3560              (not (assq 'message-mode mc-modes-alist)))
3561     (push '(message-mode (encrypt . mc-encrypt-message)
3562                          (sign . mc-sign-message))
3563           mc-modes-alist))
3564   (when actions
3565     (setq message-send-actions actions))
3566   (setq message-reply-buffer
3567         (or (message-get-parameter 'reply-buffer)
3568             replybuffer))
3569   (goto-char (point-min))
3570   ;; Insert all the headers.
3571   (mail-header-format
3572    (let ((h headers)
3573          (alist message-header-format-alist))
3574      (while h
3575        (unless (assq (caar h) message-header-format-alist)
3576          (push (list (caar h)) alist))
3577        (pop h))
3578      alist)
3579    headers)
3580   (delete-region (point) (progn (forward-line -1) (point)))
3581   (when message-default-headers
3582     (insert message-default-headers)
3583     (or (bolp) (insert ?\n)))
3584   (put-text-property
3585    (point)
3586    (progn
3587      (insert mail-header-separator "\n")
3588      (1- (point)))
3589    'read-only nil)
3590   (forward-line -1)
3591   (when (message-news-p)
3592     (when message-default-news-headers
3593       (insert message-default-news-headers)
3594       (or (bolp) (insert ?\n)))
3595     (when message-generate-headers-first
3596       (message-generate-headers
3597        (delq 'Lines
3598              (delq 'Subject
3599                    (copy-sequence message-required-news-headers))))))
3600   (when (message-mail-p)
3601     (when message-default-mail-headers
3602       (insert message-default-mail-headers)
3603       (or (bolp) (insert ?\n)))
3604     (when message-generate-headers-first
3605       (message-generate-headers
3606        (delq 'Lines
3607              (delq 'Subject
3608                    (copy-sequence message-required-mail-headers))))))
3609   (run-hooks 'message-signature-setup-hook)
3610   (message-insert-signature)
3611   (save-restriction
3612     (message-narrow-to-headers)
3613     (run-hooks 'message-header-setup-hook))
3614   (set-buffer-modified-p nil)
3615   (setq buffer-undo-list nil)
3616   (run-hooks 'message-setup-hook)
3617   (message-position-point)
3618   (undo-boundary))
3619
3620 (defun message-set-auto-save-file-name ()
3621   "Associate the message buffer with a file in the drafts directory."
3622   (when message-autosave-directory
3623     (if (gnus-alive-p)
3624         (setq message-draft-article
3625               (nndraft-request-associate-buffer "drafts"))
3626       (setq buffer-file-name (expand-file-name "*message*"
3627                                                message-autosave-directory))
3628       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
3629     (clear-visited-file-modtime)))
3630
3631 (defun message-disassociate-draft ()
3632   "Disassociate the message buffer from the drafts directory."
3633   (when message-draft-article
3634     (nndraft-request-expire-articles
3635      (list message-draft-article) "drafts" nil t)))
3636
3637 \f
3638
3639 ;;;
3640 ;;; Commands for interfacing with message
3641 ;;;
3642
3643 ;;;###autoload
3644 (defun message-mail (&optional to subject
3645                                other-headers continue switch-function
3646                                yank-action send-actions)
3647   "Start editing a mail message to be sent.
3648 OTHER-HEADERS is an alist of header/value pairs."
3649   (interactive)
3650   (let ((message-this-is-mail t))
3651     (message-pop-to-buffer (message-buffer-name "mail" to))
3652     (message-setup
3653      (nconc
3654       `((To . ,(or to "")) (Subject . ,(or subject "")))
3655       (when other-headers other-headers)))))
3656
3657 ;;;###autoload
3658 (defun message-news (&optional newsgroups subject)
3659   "Start editing a news article to be sent."
3660   (interactive)
3661   (let ((message-this-is-news t))
3662     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3663     (message-setup `((Newsgroups . ,(or newsgroups ""))
3664                      (Subject . ,(or subject ""))))))
3665
3666 ;;;###autoload
3667 (defun message-reply (&optional to-address wide)
3668   "Start editing a reply to the article in the current buffer."
3669   (interactive)
3670   (let ((cur (current-buffer))
3671         from subject date reply-to to cc
3672         references message-id follow-to
3673         (inhibit-point-motion-hooks t)
3674         mct never-mct gnus-warning)
3675     (save-restriction
3676       (message-narrow-to-head)
3677       ;; Allow customizations to have their say.
3678       (if (not wide)
3679           ;; This is a regular reply.
3680           (if (message-functionp message-reply-to-function)
3681               (setq follow-to (funcall message-reply-to-function)))
3682         ;; This is a followup.
3683         (if (message-functionp message-wide-reply-to-function)
3684             (save-excursion
3685               (setq follow-to
3686                     (funcall message-wide-reply-to-function)))))
3687       ;; Find all relevant headers we need.
3688       (setq from (message-fetch-field "from")
3689             date (message-fetch-field "date")
3690             subject (or (message-fetch-field "subject") "none")
3691             to (message-fetch-field "to")
3692             cc (message-fetch-field "cc")
3693             mct (message-fetch-field "mail-copies-to")
3694             reply-to (message-fetch-field "reply-to")
3695             references (message-fetch-field "references")
3696             message-id (message-fetch-field "message-id" t))
3697       ;; Remove any (buggy) Re:'s that are present and make a
3698       ;; proper one.
3699       (when (string-match message-subject-re-regexp subject)
3700         (setq subject (substring subject (match-end 0))))
3701       (setq subject (concat "Re: " subject))
3702
3703       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3704                  (string-match "<[^>]+>" gnus-warning))
3705         (setq message-id (match-string 0 gnus-warning)))
3706
3707       ;; Handle special values of Mail-Copies-To.
3708       (when mct
3709         (cond ((equal (downcase mct) "never")
3710                (setq never-mct t)
3711                (setq mct nil))
3712               ((equal (downcase mct) "always")
3713                (setq mct (or reply-to from)))))
3714
3715       (unless follow-to
3716         (if (or (not wide)
3717                 to-address)
3718             (progn
3719               (setq follow-to (list (cons 'To (or to-address reply-to from))))
3720               (when (and wide mct)
3721                 (push (cons 'Cc mct) follow-to)))
3722           (let (ccalist)
3723             (save-excursion
3724               (message-set-work-buffer)
3725               (unless never-mct
3726                 (insert (or reply-to from "")))
3727               (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3728               (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3729               (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
3730               (goto-char (point-min))
3731               (while (re-search-forward "[ \t]+" nil t)
3732                 (replace-match " " t t))
3733               ;; Remove addresses that match `rmail-dont-reply-to-names'.
3734               (insert (prog1 (rmail-dont-reply-to (buffer-string))
3735                         (erase-buffer)))
3736               (goto-char (point-min))
3737               ;; Perhaps Mail-Copies-To: never removed the only address?
3738               (when (eobp)
3739                 (insert (or reply-to from "")))
3740               (setq ccalist
3741                     (mapcar
3742                      (lambda (addr)
3743                        (cons (mail-strip-quoted-names addr) addr))
3744                      (message-tokenize-header (buffer-string))))
3745               (let ((s ccalist))
3746                 (while s
3747                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3748             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3749             (when ccalist
3750               (let ((ccs (cons 'Cc (mapconcat
3751                                     (lambda (addr) (cdr addr)) ccalist ", "))))
3752                 (when (string-match "^ +" (cdr ccs))
3753                   (setcdr ccs (substring (cdr ccs) (match-end 0))))
3754                 (push ccs follow-to))))))
3755       (widen))
3756
3757     (message-pop-to-buffer (message-buffer-name
3758                             (if wide "wide reply" "reply") from
3759                             (if wide to-address nil)))
3760
3761     (setq message-reply-headers
3762           (make-full-mail-header-from-decoded-header
3763            0 subject from date message-id references 0 0 ""))
3764
3765     (message-setup
3766      `((Subject . ,subject)
3767        ,@follow-to
3768        ,@(if (or references message-id)
3769              `((References . ,(concat (or references "") (and references " ")
3770                                       (or message-id ""))))
3771            nil))
3772      cur)))
3773
3774 ;;;###autoload
3775 (defun message-wide-reply (&optional to-address)
3776   "Make a \"wide\" reply to the message in the current buffer."
3777   (interactive)
3778   (message-reply to-address t))
3779
3780 ;;;###autoload
3781 (defun message-followup (&optional to-newsgroups)
3782   "Follow up to the message in the current buffer.
3783 If TO-NEWSGROUPS, use that as the new Newsgroups line."
3784   (interactive)
3785   (let ((cur (current-buffer))
3786         from subject date reply-to mct
3787         references message-id follow-to
3788         (inhibit-point-motion-hooks t)
3789         (message-this-is-news t)
3790         followup-to distribution newsgroups gnus-warning posted-to)
3791     (save-restriction
3792       (narrow-to-region
3793        (goto-char (point-min))
3794        (if (search-forward "\n\n" nil t)
3795            (1- (point))
3796          (point-max)))
3797       (when (message-functionp message-followup-to-function)
3798         (setq follow-to
3799               (funcall message-followup-to-function)))
3800       (setq from (message-fetch-field "from")
3801             date (message-fetch-field "date")
3802             subject (or (message-fetch-field "subject") "none")
3803             references (message-fetch-field "references")
3804             message-id (message-fetch-field "message-id" t)
3805             followup-to (message-fetch-field "followup-to")
3806             newsgroups (message-fetch-field "newsgroups")
3807             posted-to (message-fetch-field "posted-to")
3808             reply-to (message-fetch-field "reply-to")
3809             distribution (message-fetch-field "distribution")
3810             mct (message-fetch-field "mail-copies-to"))
3811       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3812                  (string-match "<[^>]+>" gnus-warning))
3813         (setq message-id (match-string 0 gnus-warning)))
3814       ;; Remove bogus distribution.
3815       (when (and (stringp distribution)
3816                  (let ((case-fold-search t))
3817                    (string-match "world" distribution)))
3818         (setq distribution nil))
3819       ;; Remove any (buggy) Re:'s that are present and make a
3820       ;; proper one.
3821       (when (string-match message-subject-re-regexp subject)
3822         (setq subject (substring subject (match-end 0))))
3823       (setq subject (concat "Re: " subject))
3824       (widen))
3825
3826     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3827
3828     (message-setup
3829      `((Subject . ,subject)
3830        ,@(cond
3831           (to-newsgroups
3832            (list (cons 'Newsgroups to-newsgroups)))
3833           (follow-to follow-to)
3834           ((and followup-to message-use-followup-to)
3835            (list
3836             (cond
3837              ((equal (downcase followup-to) "poster")
3838               (if (or (eq message-use-followup-to 'use)
3839                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
3840 You should normally obey the Followup-To: header.
3841
3842 `Followup-To: poster' sends your response via e-mail instead of news.
3843
3844 A typical situation where `Followup-To: poster' is used is when the poster
3845 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3846                   (progn
3847                     (setq message-this-is-news nil)
3848                     (cons 'To (or reply-to from "")))
3849                 (cons 'Newsgroups newsgroups)))
3850              (t
3851               (if (or (equal followup-to newsgroups)
3852                       (not (eq message-use-followup-to 'ask))
3853                       (message-y-or-n-p
3854                        (concat "Obey Followup-To: " followup-to "? ") t "\
3855 You should normally obey the Followup-To: header.
3856
3857         `Followup-To: " followup-to "'
3858 directs your response to " (if (string-match "," followup-to)
3859                                "the specified newsgroups"
3860                              "that newsgroup only") ".
3861
3862 If a message is posted to several newsgroups, Followup-To is often
3863 used to direct the following discussion to one newsgroup only,
3864 because discussions that are spread over several newsgroup tend to
3865 be fragmented and very difficult to follow.
3866
3867 Also, some source/announcement newsgroups are not indented for discussion;
3868 responses here are directed to other newsgroups."))
3869                   (cons 'Newsgroups followup-to)
3870                 (cons 'Newsgroups newsgroups))))))
3871           (posted-to
3872            `((Newsgroups . ,posted-to)))
3873           (t
3874            `((Newsgroups . ,newsgroups))))
3875        ,@(and distribution (list (cons 'Distribution distribution)))
3876        ,@(if (or references message-id)
3877              `((References . ,(concat (or references "") (and references " ")
3878                                       (or message-id "")))))
3879        ,@(when (and mct
3880                     (not (equal (downcase mct) "never")))
3881            (list (cons 'Cc (if (equal (downcase mct) "always")
3882                                (or reply-to from "")
3883                              mct)))))
3884
3885      cur)
3886
3887     (setq message-reply-headers
3888           (make-full-mail-header-from-decoded-header
3889            0 subject from date message-id references 0 0 ""))))
3890
3891
3892 ;;;###autoload
3893 (defun message-cancel-news ()
3894   "Cancel an article you posted."
3895   (interactive)
3896   (unless (message-news-p)
3897     (error "This is not a news article; canceling is impossible"))
3898   (when (yes-or-no-p "Do you really want to cancel this article? ")
3899     (let (from newsgroups message-id distribution buf sender)
3900       (save-excursion
3901         ;; Get header info. from original article.
3902         (save-restriction
3903           (message-narrow-to-head)
3904           (setq from (message-fetch-field "from")
3905                 sender (message-fetch-field "sender")
3906                 newsgroups (message-fetch-field "newsgroups")
3907                 message-id (message-fetch-field "message-id" t)
3908                 distribution (message-fetch-field "distribution")))
3909         ;; Make sure that this article was written by the user.
3910         (unless (or (and sender
3911                          (string-equal
3912                           (downcase sender)
3913                           (downcase (message-make-sender))))
3914                     (string-equal
3915                      (downcase (cadr (mail-extract-address-components from)))
3916                      (downcase (cadr (mail-extract-address-components
3917                                       (message-make-from))))))
3918           (error "This article is not yours"))
3919         ;; Make control message.
3920         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
3921         (buffer-disable-undo (current-buffer))
3922         (erase-buffer)
3923         (insert "Newsgroups: " newsgroups "\n"
3924                 "From: " (message-make-from) "\n"
3925                 "Subject: cmsg cancel " message-id "\n"
3926                 "Control: cancel " message-id "\n"
3927                 (if distribution
3928                     (concat "Distribution: " distribution "\n")
3929                   "")
3930                 mail-header-separator "\n"
3931                 message-cancel-message)
3932         (message "Canceling your article...")
3933         (if (let ((message-syntax-checks
3934                    'dont-check-for-anything-just-trust-me)
3935                   (message-encoding-buffer (current-buffer))
3936                   (message-edit-buffer (current-buffer)))
3937               (message-send-news))
3938             (message "Canceling your article...done"))
3939         (kill-buffer buf)))))
3940
3941 ;;;###autoload
3942 (defun message-supersede ()
3943   "Start composing a message to supersede the current message.
3944 This is done simply by taking the old article and adding a Supersedes
3945 header line with the old Message-ID."
3946   (interactive)
3947   (let ((cur (current-buffer))
3948         (sender (message-fetch-field "sender"))
3949         (from (message-fetch-field "from")))
3950     ;; Check whether the user owns the article that is to be superseded.
3951     (unless (or (and sender
3952                      (string-equal
3953                       (downcase sender)
3954                       (downcase (message-make-sender))))
3955                 (string-equal
3956                  (downcase (cadr (mail-extract-address-components from)))
3957                  (downcase (cadr (mail-extract-address-components
3958                                   (message-make-from))))))
3959       (error "This article is not yours"))
3960     ;; Get a normal message buffer.
3961     (message-pop-to-buffer (message-buffer-name "supersede"))
3962     (insert-buffer-substring cur)
3963     (message-narrow-to-head)
3964     ;; Remove unwanted headers.
3965     (when message-ignored-supersedes-headers
3966       (message-remove-header message-ignored-supersedes-headers t))
3967     (goto-char (point-min))
3968     (if (not (re-search-forward "^Message-ID: " nil t))
3969         (error "No Message-ID in this article")
3970       (replace-match "Supersedes: " t t))
3971     (goto-char (point-max))
3972     (insert mail-header-separator)
3973     (widen)
3974     (forward-line 1)))
3975
3976 ;;;###autoload
3977 (defun message-recover ()
3978   "Reread contents of current buffer from its last auto-save file."
3979   (interactive)
3980   (let ((file-name (make-auto-save-file-name)))
3981     (cond ((save-window-excursion
3982              (if (not (eq system-type 'vax-vms))
3983                  (with-output-to-temp-buffer "*Directory*"
3984                    (buffer-disable-undo standard-output)
3985                    (let ((default-directory "/"))
3986                      (call-process
3987                       "ls" nil standard-output nil "-l" file-name))))
3988              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3989            (let ((buffer-read-only nil))
3990              (erase-buffer)
3991              (insert-file-contents file-name nil)))
3992           (t (error "message-recover cancelled")))))
3993
3994 ;;; Washing Subject:
3995
3996 (defun message-wash-subject (subject)
3997   "Remove junk like \"Re:\", \"(fwd)\", etc. that was added to the subject by previous forwarders, replyers, etc."
3998   (nnheader-temp-write nil
3999     (insert-string subject)
4000     (goto-char (point-min))
4001     ;; strip Re/Fwd stuff off the beginning
4002     (while (re-search-forward
4003             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
4004       (replace-match ""))
4005
4006     ;; and gnus-style forwards [foo@bar.com] subject
4007     (goto-char (point-min))
4008     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
4009       (replace-match ""))
4010
4011     ;; and off the end
4012     (goto-char (point-max))
4013     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
4014       (replace-match ""))
4015
4016     ;; and finally, any whitespace that was left-over
4017     (goto-char (point-min))
4018     (while (re-search-forward "^[ \t]+" nil t)
4019       (replace-match ""))
4020     (goto-char (point-max))
4021     (while (re-search-backward "[ \t]+$" nil t)
4022       (replace-match ""))
4023
4024     (buffer-string)))
4025     
4026 ;;; Forwarding messages.
4027
4028 (defun message-forward-subject-author-subject (subject)
4029   "Generate a subject for a forwarded message.
4030 The form is: [Source] Subject, where if the original message was mail,
4031 Source is the sender, and if the original message was news, Source is
4032 the list of newsgroups is was posted to."
4033   (concat "["
4034           (or (message-fetch-field
4035                (if (message-news-p) "newsgroups" "from"))
4036               "(nowhere)")
4037           "] " subject))
4038
4039 (defun message-forward-subject-fwd (subject)
4040   "Generate a subject for a forwarded message.
4041 The form is: Fwd: Subject, where Subject is the original subject of
4042 the message."
4043   (concat "Fwd: " subject))
4044
4045 (defun message-make-forward-subject ()
4046   "Return a Subject header suitable for the message in the current buffer."
4047   (save-excursion
4048     (save-restriction
4049       (current-buffer)
4050       (message-narrow-to-head)
4051       (let ((funcs message-make-forward-subject-function)
4052             (subject (if message-wash-forwarded-subjects
4053                          (message-wash-subject
4054                           (or (nnheader-decode-subject
4055                                (message-fetch-field "Subject"))
4056                               ""))
4057                        (or (nnheader-decode-subject
4058                             (message-fetch-field "Subject"))
4059                            ""))))
4060         ;; Make sure funcs is a list.
4061         (and funcs
4062              (not (listp funcs))
4063              (setq funcs (list funcs)))
4064         ;; Apply funcs in order, passing subject generated by previous
4065         ;; func to the next one.
4066         (while funcs
4067           (when (message-functionp (car funcs))
4068             (setq subject (funcall (car funcs) subject)))
4069           (setq funcs (cdr funcs)))
4070         subject))))
4071
4072 ;;;###autoload
4073 (defun message-forward (&optional news)
4074   "Forward the current message via mail.
4075 Optional NEWS will use news to forward instead of mail."
4076   (interactive "P")
4077   (let ((cur (current-buffer))
4078         (subject (message-make-forward-subject))
4079         art-beg)
4080     (if news (message-news nil subject) (message-mail nil subject))
4081     ;; Put point where we want it before inserting the forwarded
4082     ;; message.
4083     (if message-signature-before-forwarded-message
4084         (goto-char (point-max))
4085       (message-goto-body))
4086     ;; Make sure we're at the start of the line.
4087     (unless (eolp)
4088       (insert "\n"))
4089     ;; Narrow to the area we are to insert.
4090     (narrow-to-region (point) (point))
4091     ;; Insert the separators and the forwarded buffer.
4092     (insert message-forward-start-separator)
4093     (setq art-beg (point))
4094     (insert-buffer-substring cur)
4095     (goto-char (point-max))
4096     (insert message-forward-end-separator)
4097     (set-text-properties (point-min) (point-max) nil)
4098     ;; Remove all unwanted headers.
4099     (goto-char art-beg)
4100     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
4101                                   (1- (point))
4102                                 (point)))
4103     (goto-char (point-min))
4104     (message-remove-header message-included-forward-headers t nil t)
4105     (widen)
4106     (message-position-point)))
4107
4108 ;;;###autoload
4109 (defun message-resend (address)
4110   "Resend the current article to ADDRESS."
4111   (interactive "sResend message to: ")
4112   (message "Resending message to %s..." address)
4113   (save-excursion
4114     (let ((cur (current-buffer))
4115           beg)
4116       ;; We first set up a normal mail buffer.
4117       (set-buffer (get-buffer-create " *message resend*"))
4118       (buffer-disable-undo (current-buffer))
4119       (erase-buffer)
4120       ;; avoid to turn-on-mime-edit
4121       (let (message-setup-hook)
4122         (message-setup `((To . ,address)))
4123         )
4124       ;; Insert our usual headers.
4125       (message-generate-headers '(From Date To))
4126       (message-narrow-to-headers)
4127       ;; Rename them all to "Resent-*".
4128       (while (re-search-forward "^[A-Za-z]" nil t)
4129         (forward-char -1)
4130         (insert "Resent-"))
4131       (widen)
4132       (forward-line)
4133       (delete-region (point) (point-max))
4134       (setq beg (point))
4135       ;; Insert the message to be resent.
4136       (insert-buffer-substring cur)
4137       (goto-char (point-min))
4138       (search-forward "\n\n")
4139       (forward-char -1)
4140       (save-restriction
4141         (narrow-to-region beg (point))
4142         (message-remove-header message-ignored-resent-headers t)
4143         (goto-char (point-max)))
4144       (insert mail-header-separator)
4145       ;; Rename all old ("Also-")Resent headers.
4146       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
4147         (beginning-of-line)
4148         (insert "Also-"))
4149       ;; Quote any "From " lines at the beginning.
4150       (goto-char beg)
4151       (when (looking-at "From ")
4152         (replace-match "X-From-Line: "))
4153       ;; Send it.
4154       (let ((message-encoding-buffer (current-buffer))
4155             (message-edit-buffer (current-buffer)))
4156         (message-send-mail))
4157       (kill-buffer (current-buffer)))
4158     (message "Resending message to %s...done" address)))
4159
4160 (defun message-bounce-setup-for-mime-edit ()
4161   (goto-char (point-min))
4162   (when (search-forward (concat "\n" mail-header-separator "\n") nil t)
4163     (replace-match "\n\n"))
4164   (set (make-local-variable 'message-setup-hook) nil)
4165   (mime-edit-again))
4166
4167 ;;;###autoload
4168 (defun message-bounce ()
4169   "Re-mail the current message.
4170 This only makes sense if the current message is a bounce message than
4171 contains some mail you have written which has been bounced back to
4172 you."
4173   (interactive)
4174   (let ((cur (current-buffer))
4175         boundary)
4176     (message-pop-to-buffer (message-buffer-name "bounce"))
4177     (insert-buffer-substring cur)
4178     (undo-boundary)
4179     (message-narrow-to-head)
4180     (if (and (message-fetch-field "MIME-Version")
4181              (setq boundary (message-fetch-field "Content-Type")))
4182         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
4183             (setq boundary (concat (match-string 1 boundary) " *\n"
4184                                    "Content-Type: message/rfc822"))
4185           (setq boundary nil)))
4186     (widen)
4187     (goto-char (point-min))
4188     (search-forward "\n\n" nil t)
4189     (or (and boundary
4190              (re-search-forward boundary nil t)
4191              (forward-line 2))
4192         (and (re-search-forward message-unsent-separator nil t)
4193              (forward-line 1))
4194         (re-search-forward "^Return-Path:.*\n" nil t))
4195     ;; We remove everything before the bounced mail.
4196     (delete-region
4197      (point-min)
4198      (if (re-search-forward "^[^ \n\t]+:" nil t)
4199          (match-beginning 0)
4200        (point)))
4201     (save-restriction
4202       (message-narrow-to-head)
4203       (message-remove-header message-ignored-bounced-headers t)
4204       (goto-char (point-max))
4205       (insert mail-header-separator))
4206     (when message-bounce-setup-function
4207       (funcall message-bounce-setup-function))
4208     (run-hooks 'message-bounce-setup-hook)
4209     (message-position-point)))
4210
4211 ;;;
4212 ;;; Interactive entry points for new message buffers.
4213 ;;;
4214
4215 ;;;###autoload
4216 (defun message-mail-other-window (&optional to subject)
4217   "Like `message-mail' command, but display mail buffer in another window."
4218   (interactive)
4219   (let ((pop-up-windows t)
4220         (special-display-buffer-names nil)
4221         (special-display-regexps nil)
4222         (same-window-buffer-names nil)
4223         (same-window-regexps nil))
4224     (message-pop-to-buffer (message-buffer-name "mail" to)))
4225   (let ((message-this-is-mail t))
4226     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4227
4228 ;;;###autoload
4229 (defun message-mail-other-frame (&optional to subject)
4230   "Like `message-mail' command, but display mail buffer in another frame."
4231   (interactive)
4232   (let ((pop-up-frames t)
4233         (special-display-buffer-names nil)
4234         (special-display-regexps nil)
4235         (same-window-buffer-names nil)
4236         (same-window-regexps nil))
4237     (message-pop-to-buffer (message-buffer-name "mail" to)))
4238   (let ((message-this-is-mail t))
4239     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4240
4241 ;;;###autoload
4242 (defun message-news-other-window (&optional newsgroups subject)
4243   "Start editing a news article to be sent."
4244   (interactive)
4245   (let ((pop-up-windows t)
4246         (special-display-buffer-names nil)
4247         (special-display-regexps nil)
4248         (same-window-buffer-names nil)
4249         (same-window-regexps nil))
4250     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4251   (let ((message-this-is-news t))
4252     (message-setup `((Newsgroups . ,(or newsgroups ""))
4253                      (Subject . ,(or subject ""))))))
4254
4255 ;;;###autoload
4256 (defun message-news-other-frame (&optional newsgroups subject)
4257   "Start editing a news article to be sent."
4258   (interactive)
4259   (let ((pop-up-frames t)
4260         (special-display-buffer-names nil)
4261         (special-display-regexps nil)
4262         (same-window-buffer-names nil)
4263         (same-window-regexps nil))
4264     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4265   (let ((message-this-is-news t))
4266     (message-setup `((Newsgroups . ,(or newsgroups ""))
4267                      (Subject . ,(or subject ""))))))
4268
4269 ;;; underline.el
4270
4271 ;; This code should be moved to underline.el (from which it is stolen).
4272
4273 ;;;###autoload
4274 (defun bold-region (start end)
4275   "Bold all nonblank characters in the region.
4276 Works by overstriking characters.
4277 Called from program, takes two arguments START and END
4278 which specify the range to operate on."
4279   (interactive "r")
4280   (save-excursion
4281     (let ((end1 (make-marker)))
4282       (move-marker end1 (max start end))
4283       (goto-char (min start end))
4284       (while (< (point) end1)
4285         (or (looking-at "[_\^@- ]")
4286             (insert (following-char) "\b"))
4287         (forward-char 1)))))
4288
4289 ;;;###autoload
4290 (defun unbold-region (start end)
4291   "Remove all boldness (overstruck characters) in the region.
4292 Called from program, takes two arguments START and END
4293 which specify the range to operate on."
4294   (interactive "r")
4295   (save-excursion
4296     (let ((end1 (make-marker)))
4297       (move-marker end1 (max start end))
4298       (goto-char (min start end))
4299       (while (re-search-forward "\b" end1 t)
4300         (if (eq (following-char) (char-after (- (point) 2)))
4301             (delete-char -2))))))
4302
4303 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
4304
4305 ;; Support for toolbar
4306 (when (string-match "XEmacs\\|Lucid" emacs-version)
4307   (require 'messagexmas))
4308
4309 ;;; Group name completion.
4310
4311 (defvar message-newgroups-header-regexp
4312   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
4313   "Regexp that match headers that lists groups.")
4314
4315 (defun message-tab ()
4316   "Expand group names in Newsgroups and Followup-To headers.
4317 Do a `tab-to-tab-stop' if not in those headers."
4318   (interactive)
4319   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
4320         (mail-abbrev-in-expansion-header-p))
4321       (message-expand-group)
4322     (tab-to-tab-stop)))
4323
4324 (defvar gnus-active-hashtb)
4325 (defun message-expand-group ()
4326   "Expand the group name under point."
4327   (let* ((b (save-excursion
4328               (save-restriction
4329                 (narrow-to-region
4330                  (save-excursion
4331                    (beginning-of-line)
4332                    (skip-chars-forward "^:")
4333                    (1+ (point)))
4334                  (point))
4335                 (skip-chars-backward "^, \t\n") (point))))
4336          (completion-ignore-case t)
4337          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
4338                                             (point))))
4339          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
4340          (completions (all-completions string hashtb))
4341          comp)
4342     (delete-region b (point))
4343     (cond
4344      ((= (length completions) 1)
4345       (if (string= (car completions) string)
4346           (progn
4347             (insert string)
4348             (message "Only matching group"))
4349         (insert (car completions))))
4350      ((and (setq comp (try-completion string hashtb))
4351            (not (string= comp string)))
4352       (insert comp))
4353      (t
4354       (insert string)
4355       (if (not comp)
4356           (message "No matching groups")
4357         (save-selected-window
4358           (pop-to-buffer "*Completions*")
4359           (buffer-disable-undo (current-buffer))
4360           (let ((buffer-read-only nil))
4361             (erase-buffer)
4362             (let ((standard-output (current-buffer)))
4363               (display-completion-list (sort completions 'string<)))
4364             (goto-char (point-min))
4365             (delete-region (point) (progn (forward-line 3) (point))))))))))
4366
4367 ;;; Help stuff.
4368
4369 (defun message-talkative-question (ask question show &rest text)
4370   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
4371 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
4372 The following arguments may contain lists of values."
4373   (if (and show
4374            (setq text (message-flatten-list text)))
4375       (save-window-excursion
4376         (save-excursion
4377           (with-output-to-temp-buffer " *MESSAGE information message*"
4378             (set-buffer " *MESSAGE information message*")
4379             (mapcar 'princ text)
4380             (goto-char (point-min))))
4381         (funcall ask question))
4382     (funcall ask question)))
4383
4384 (defun message-flatten-list (list)
4385   "Return a new, flat list that contains all elements of LIST.
4386
4387 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
4388 => (1 2 3 4 5 6 7)"
4389   (cond ((consp list)
4390          (apply 'append (mapcar 'message-flatten-list list)))
4391         (list
4392          (list list))))
4393
4394 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
4395   "Create and return a buffer with a name based on NAME using generate-new-buffer.
4396 Then clone the local variables and values from the old buffer to the
4397 new one, cloning only the locals having a substring matching the
4398 regexp varstr."
4399   (let ((oldbuf (current-buffer)))
4400     (save-excursion
4401       (set-buffer (generate-new-buffer name))
4402       (message-clone-locals oldbuf)
4403       (current-buffer))))
4404
4405 (defun message-clone-locals (buffer)
4406   "Clone the local variables from BUFFER to the current buffer."
4407   (let ((locals (save-excursion
4408                   (set-buffer buffer)
4409                   (buffer-local-variables)))
4410         (regexp "^\\(gnus\\|nn\\|message\\|user-\\(mail-address\\|full-name\\)\\)"))
4411     (mapcar
4412      (lambda (local)
4413        (when (and (consp local)
4414                   (car local)
4415                   (string-match regexp (symbol-name (car local))))
4416          (ignore-errors
4417            (set (make-local-variable (car local))
4418                 (cdr local)))))
4419      locals)))
4420
4421 ;;; @ for MIME Edit mode
4422 ;;;
4423
4424 (defun message-maybe-encode ()
4425   (when message-mime-mode
4426     (run-hooks 'mime-edit-translate-hook)
4427     (if (catch 'mime-edit-error
4428           (save-excursion
4429             (mime-edit-translate-body)
4430             ))
4431         (error "Translation error!")
4432       )
4433     (end-of-invisible)
4434     (run-hooks 'mime-edit-exit-hook)
4435     ))
4436
4437 (defun message-mime-insert-article (&optional message)
4438   (interactive)
4439   (let ((message-cite-function 'mime-edit-inserted-message-filter)
4440         (message-reply-buffer
4441          (message-get-parameter-with-eval 'original-buffer))
4442         (start (point)))
4443     (message-yank-original nil)
4444     (save-excursion
4445       (narrow-to-region (goto-char start)
4446                         (if (search-forward "\n\n" nil t)
4447                             (1- (point))
4448                           (point-max)))
4449       (goto-char (point-min))
4450       (message-remove-header message-included-forward-headers t nil t)
4451       (widen))))
4452
4453 (set-alist 'mime-edit-message-inserter-alist
4454            'message-mode (function message-mime-insert-article))
4455
4456 (defun message-mime-encode (start end &optional orig-buf)
4457   (save-restriction
4458     (narrow-to-region start end)
4459     (when (with-current-buffer orig-buf
4460             mime-edit-mode-flag)
4461       (run-hooks 'mime-edit-translate-hook)
4462       (mime-edit-translate-buffer)
4463       )
4464     (goto-char start)
4465     (and (search-forward (concat "\n" mail-header-separator "\n") nil t)
4466          (replace-match "\n\n"))
4467     ))
4468
4469 (set-alist 'format-alist
4470            'mime-message
4471            '("MIME message."
4472              "1\\(^\\)"
4473              nil
4474              message-mime-encode
4475              t nil))
4476
4477 (defun message-mime-setup ()
4478   (turn-on-mime-edit)
4479   (add-to-list 'buffer-file-format 'mime-message))
4480
4481 ;;; Miscellaneous functions
4482
4483 ;; stolen (and renamed) from nnheader.el
4484 (defun message-replace-chars-in-string (string from to)
4485   "Replace characters in STRING from FROM to TO."
4486   (let ((string (substring string 0))   ;Copy string.
4487         (len (length string))
4488         (idx 0))
4489     ;; Replace all occurrences of FROM with TO.
4490     (while (< idx len)
4491       (when (= (aref string idx) from)
4492         (aset string idx to))
4493       (setq idx (1+ idx)))
4494     string))
4495
4496 (run-hooks 'message-load-hook)
4497
4498 (provide 'message)
4499
4500 ;;; message.el ends here