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