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