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