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