*** 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 If there is no signature in the article, go to the end and
1422 return nil."
1423   (interactive)
1424   (goto-char (point-min))
1425   (if (re-search-forward message-signature-separator nil t)
1426       (forward-line 1)
1427     (goto-char (point-max))
1428     nil))
1429
1430 \f
1431
1432 (defun message-insert-to (&optional force)
1433   "Insert a To header that points to the author of the article being replied to.
1434 If the original author requested not to be sent mail, the function signals
1435 an error.
1436 With the prefix argument FORCE, insert the header anyway."
1437   (interactive "P")
1438   (let ((co (message-fetch-reply-field "mail-copies-to")))
1439     (when (and (null force)
1440                co
1441                (equal (downcase co) "never"))
1442       (error "The user has requested not to have copies sent via mail")))
1443   (when (and (message-position-on-field "To")
1444              (mail-fetch-field "to")
1445              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1446     (insert ", "))
1447   (insert (or (message-fetch-reply-field "reply-to")
1448               (message-fetch-reply-field "from") "")))
1449
1450 (defun message-insert-newsgroups ()
1451   "Insert the Newsgroups header from the article being replied to."
1452   (interactive)
1453   (when (and (message-position-on-field "Newsgroups")
1454              (mail-fetch-field "newsgroups")
1455              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1456     (insert ","))
1457   (insert (or (message-fetch-reply-field "newsgroups") "")))
1458
1459 \f
1460
1461 ;;; Various commands
1462
1463 (defun message-delete-not-region (beg end)
1464   "Delete everything in the body of the current message that is outside of the region."
1465   (interactive "r")
1466   (save-excursion
1467     (goto-char end)
1468     (delete-region (point) (if (not (message-goto-signature))
1469                                (point)
1470                              (forward-line -2)
1471                              (point)))
1472     (insert "\n")
1473     (goto-char beg)
1474     (delete-region beg (progn (message-goto-body)
1475                               (forward-line 2)
1476                               (point))))
1477   (when (message-goto-signature)
1478     (forward-line -2)))
1479
1480 (defun message-kill-to-signature ()
1481   "Deletes all text up to the signature."
1482   (interactive)
1483   (let ((point (point)))
1484     (message-goto-signature)
1485     (unless (eobp)
1486       (forward-line -2))
1487     (kill-region point (point))
1488     (unless (bolp)
1489       (insert "\n"))))
1490
1491 (defun message-newline-and-reformat ()
1492   "Insert four newlines, and then reformat if inside quoted text."
1493   (interactive)
1494   (let ((point (point))
1495         quoted)
1496     (save-excursion
1497       (beginning-of-line)
1498       (setq quoted (looking-at (regexp-quote message-yank-prefix))))
1499     (insert "\n\n\n\n")
1500     (when quoted
1501       (insert message-yank-prefix))
1502     (fill-paragraph nil)
1503     (goto-char point)
1504     (forward-line 2)))
1505
1506 (defun message-insert-signature (&optional force)
1507   "Insert a signature.  See documentation for the `message-signature' variable."
1508   (interactive (list 0))
1509   (let* ((signature
1510           (cond
1511            ((and (null message-signature)
1512                  (eq force 0))
1513             (save-excursion
1514               (goto-char (point-max))
1515               (not (re-search-backward
1516                     message-signature-separator nil t))))
1517            ((and (null message-signature)
1518                  force)
1519             t)
1520            ((message-functionp message-signature)
1521             (funcall message-signature))
1522            ((listp message-signature)
1523             (eval message-signature))
1524            (t message-signature)))
1525          (signature
1526           (cond ((stringp signature)
1527                  signature)
1528                 ((and (eq t signature)
1529                       message-signature-file
1530                       (file-exists-p message-signature-file))
1531                  signature))))
1532     (when signature
1533       (goto-char (point-max))
1534       ;; Insert the signature.
1535       (unless (bolp)
1536         (insert "\n"))
1537       (insert "\n-- \n")
1538       (if (eq signature t)
1539           (insert-file-contents message-signature-file)
1540         (insert signature))
1541       (goto-char (point-max))
1542       (or (bolp) (insert "\n")))))
1543
1544 (defun message-elide-region (b e)
1545   "Elide the text between point and mark.
1546 An ellipsis (from `message-elide-elipsis') will be inserted where the
1547 text was killed."
1548   (interactive "r")
1549   (kill-region b e)
1550   (unless (bolp)
1551     (insert "\n"))
1552   (insert message-elide-elipsis))
1553
1554 (defvar message-caesar-translation-table nil)
1555
1556 (defun message-caesar-region (b e &optional n)
1557   "Caesar rotation of region by N, default 13, for decrypting netnews."
1558   (interactive
1559    (list
1560     (min (point) (or (mark t) (point)))
1561     (max (point) (or (mark t) (point)))
1562     (when current-prefix-arg
1563       (prefix-numeric-value current-prefix-arg))))
1564
1565   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1566   (unless (or (zerop n)                 ; no action needed for a rot of 0
1567               (= b e))                  ; no region to rotate
1568     ;; We build the table, if necessary.
1569     (when (or (not message-caesar-translation-table)
1570               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1571         (setq message-caesar-translation-table
1572               (message-make-caesar-translation-table n)))
1573     ;; Then we translate the region.  Do it this way to retain
1574     ;; text properties.
1575     (while (< b e)
1576       (subst-char-in-region
1577        b (1+ b) (char-after b)
1578        (aref message-caesar-translation-table (char-after b)))
1579       (incf b))))
1580
1581 (defun message-make-caesar-translation-table (n)
1582   "Create a rot table with offset N."
1583   (let ((i -1)
1584         (table (make-string 256 0)))
1585     (while (< (incf i) 256)
1586       (aset table i i))
1587     (concat
1588      (substring table 0 ?A)
1589      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1590      (substring table ?A (+ ?A n))
1591      (substring table (+ ?A 26) ?a)
1592      (substring table (+ ?a n) (+ ?a n (- 26 n)))
1593      (substring table ?a (+ ?a n))
1594      (substring table (+ ?a 26) 255))))
1595
1596 (defun message-caesar-buffer-body (&optional rotnum)
1597   "Caesar rotates all letters in the current buffer by 13 places.
1598 Used to encode/decode possiblyun offensive messages (commonly in net.jokes).
1599 With prefix arg, specifies the number of places to rotate each letter forward.
1600 Mail and USENET news headers are not rotated."
1601   (interactive (if current-prefix-arg
1602                    (list (prefix-numeric-value current-prefix-arg))
1603                  (list nil)))
1604   (save-excursion
1605     (save-restriction
1606       (when (message-goto-body)
1607         (narrow-to-region (point) (point-max)))
1608       (message-caesar-region (point-min) (point-max) rotnum))))
1609
1610 (defun message-pipe-buffer-body (program)
1611   "Pipe the message body in the current buffer through PROGRAM."
1612   (save-excursion
1613     (save-restriction
1614       (when (message-goto-body)
1615         (narrow-to-region (point) (point-max)))
1616       (let ((body (buffer-substring (point-min) (point-max))))
1617         (unless (equal 0 (call-process-region
1618                            (point-min) (point-max) program t t))
1619             (insert body)
1620             (message "%s failed." program))))))
1621
1622 (defun message-rename-buffer (&optional enter-string)
1623   "Rename the *message* buffer to \"*message* RECIPIENT\".
1624 If the function is run with a prefix, it will ask for a new buffer
1625 name, rather than giving an automatic name."
1626   (interactive "Pbuffer name: ")
1627   (save-excursion
1628     (save-restriction
1629       (goto-char (point-min))
1630       (narrow-to-region (point)
1631                         (search-forward mail-header-separator nil 'end))
1632       (let* ((mail-to (or
1633                        (if (message-news-p) (message-fetch-field "Newsgroups")
1634                          (message-fetch-field "To"))
1635                        ""))
1636              (mail-trimmed-to
1637               (if (string-match "," mail-to)
1638                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1639                 mail-to))
1640              (name-default (concat "*message* " mail-trimmed-to))
1641              (name (if enter-string
1642                        (read-string "New buffer name: " name-default)
1643                      name-default)))
1644         (rename-buffer name t)))))
1645
1646 (defun message-fill-yanked-message (&optional justifyp)
1647   "Fill the paragraphs of a message yanked into this one.
1648 Numeric argument means justify as well."
1649   (interactive "P")
1650   (save-excursion
1651     (goto-char (point-min))
1652     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1653     (let ((fill-prefix message-yank-prefix))
1654       (fill-individual-paragraphs (point) (point-max) justifyp t))))
1655
1656 (defun message-indent-citation ()
1657   "Modify text just inserted from a message to be cited.
1658 The inserted text should be the region.
1659 When this function returns, the region is again around the modified text.
1660
1661 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1662 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1663   (let ((start (point)))
1664     ;; Remove unwanted headers.
1665     (when message-ignored-cited-headers
1666       (let (all-removed)
1667         (save-restriction
1668           (narrow-to-region
1669            (goto-char start)
1670            (if (search-forward "\n\n" nil t)
1671                (1- (point))
1672              (point)))
1673           (message-remove-header message-ignored-cited-headers t)
1674           (when (= (point-min) (point-max))
1675             (setq all-removed t))
1676           (goto-char (point-max)))
1677         (if all-removed
1678             (goto-char start)
1679           (forward-line 1))))
1680     ;; Delete blank lines at the start of the buffer.
1681     (while (and (point-min)
1682                 (eolp)
1683                 (not (eobp)))
1684       (message-delete-line))
1685     ;; Delete blank lines at the end of the buffer.
1686     (goto-char (point-max))
1687     (unless (eolp)
1688       (insert "\n"))
1689     (while (and (zerop (forward-line -1))
1690                 (looking-at "$"))
1691       (message-delete-line))
1692     ;; Do the indentation.
1693     (if (null message-yank-prefix)
1694         (indent-rigidly start (mark t) message-indentation-spaces)
1695       (save-excursion
1696         (goto-char start)
1697         (while (< (point) (mark t))
1698           (insert message-yank-prefix)
1699           (forward-line 1))))
1700     (goto-char start)))
1701
1702 (defun message-yank-original (&optional arg)
1703   "Insert the message being replied to, if any.
1704 Puts point before the text and mark after.
1705 Normally indents each nonblank line ARG spaces (default 3).  However,
1706 if `message-yank-prefix' is non-nil, insert that prefix on each line.
1707
1708 This function uses `message-cite-function' to do the actual citing.
1709
1710 Just \\[universal-argument] as argument means don't indent, insert no
1711 prefix, and don't delete any headers."
1712   (interactive "P")
1713   (let ((modified (buffer-modified-p)))
1714     (when (and message-reply-buffer
1715                message-cite-function)
1716       (delete-windows-on message-reply-buffer t)
1717       (insert-buffer message-reply-buffer)
1718       (funcall message-cite-function)
1719       (message-exchange-point-and-mark)
1720       (unless (bolp)
1721         (insert ?\n))
1722       (unless modified
1723         (setq message-checksum (message-checksum))))))
1724
1725 (defun message-cite-original-without-signature ()
1726   "Cite function in the standard Message manner."
1727   (let ((start (point))
1728         (end (mark t))
1729         (functions
1730          (when message-indent-citation-function
1731            (if (listp message-indent-citation-function)
1732                message-indent-citation-function
1733              (list message-indent-citation-function)))))
1734     (goto-char end)
1735     (when (re-search-backward "^-- $" start t)
1736       ;; Also peel off any blank lines before the signature.
1737       (forward-line -1)
1738       (while (looking-at "^[ \t]*$")
1739         (forward-line -1))
1740       (forward-line 1)
1741       (delete-region (point) end))
1742     (goto-char start)
1743     (while functions
1744       (funcall (pop functions)))
1745     (when message-citation-line-function
1746       (unless (bolp)
1747         (insert "\n"))
1748       (funcall message-citation-line-function))))
1749
1750 (defun message-cite-original ()
1751   "Cite function in the standard Message manner."
1752   (if (and (boundp 'mail-citation-hook)
1753            mail-citation-hook)
1754       (run-hooks 'mail-citation-hook)
1755     (let ((start (point))
1756           (functions
1757            (when message-indent-citation-function
1758              (if (listp message-indent-citation-function)
1759                  message-indent-citation-function
1760                (list message-indent-citation-function)))))
1761       (goto-char start)
1762       (while functions
1763         (funcall (pop functions)))
1764       (when message-citation-line-function
1765         (unless (bolp)
1766           (insert "\n"))
1767         (funcall message-citation-line-function)))))
1768
1769 (defun message-insert-citation-line ()
1770   "Function that inserts a simple citation line."
1771   (when message-reply-headers
1772     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
1773
1774 (defun message-position-on-field (header &rest afters)
1775   (let ((case-fold-search t))
1776     (save-restriction
1777       (narrow-to-region
1778        (goto-char (point-min))
1779        (progn
1780          (re-search-forward
1781           (concat "^" (regexp-quote mail-header-separator) "$"))
1782          (match-beginning 0)))
1783       (goto-char (point-min))
1784       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
1785           (progn
1786             (re-search-forward "^[^ \t]" nil 'move)
1787             (beginning-of-line)
1788             (skip-chars-backward "\n")
1789             t)
1790         (while (and afters
1791                     (not (re-search-forward
1792                           (concat "^" (regexp-quote (car afters)) ":")
1793                           nil t)))
1794           (pop afters))
1795         (when afters
1796           (re-search-forward "^[^ \t]" nil 'move)
1797           (beginning-of-line))
1798         (insert header ": \n")
1799         (forward-char -1)
1800         nil))))
1801
1802 (defun message-remove-signature ()
1803   "Remove the signature from the text between point and mark.
1804 The text will also be indented the normal way."
1805   (save-excursion
1806     (let ((start (point))
1807           mark)
1808       (if (not (re-search-forward message-signature-separator (mark t) t))
1809           ;; No signature here, so we just indent the cited text.
1810           (message-indent-citation)
1811         ;; Find the last non-empty line.
1812         (forward-line -1)
1813         (while (looking-at "[ \t]*$")
1814           (forward-line -1))
1815         (forward-line 1)
1816         (setq mark (set-marker (make-marker) (point)))
1817         (goto-char start)
1818         (message-indent-citation)
1819         ;; Enable undoing the deletion.
1820         (undo-boundary)
1821         (delete-region mark (mark t))
1822         (set-marker mark nil)))))
1823
1824 \f
1825
1826 ;;;
1827 ;;; Sending messages
1828 ;;;
1829
1830 (defun message-send-and-exit (&optional arg)
1831   "Send message like `message-send', then, if no errors, exit from mail buffer."
1832   (interactive "P")
1833   (let ((buf (current-buffer))
1834         (actions message-exit-actions))
1835     (when (and (message-send arg)
1836                (buffer-name buf))
1837       (if message-kill-buffer-on-exit
1838           (kill-buffer buf)
1839         (bury-buffer buf)
1840         (when (eq buf (current-buffer))
1841           (message-bury buf)))
1842       (message-do-actions actions))))
1843
1844 (defun message-dont-send ()
1845   "Don't send the message you have been editing."
1846   (interactive)
1847   (set-buffer-modified-p t)
1848   (save-buffer)
1849   (let ((actions message-postpone-actions))
1850     (message-bury (current-buffer))
1851     (message-do-actions actions)))
1852
1853 (defun message-kill-buffer ()
1854   "Kill the current buffer."
1855   (interactive)
1856   (when (or (not (buffer-modified-p))
1857             (yes-or-no-p "Message modified; kill anyway? "))
1858     (let ((actions message-kill-actions))
1859       (setq buffer-file-name nil)
1860       (kill-buffer (current-buffer))
1861       (message-do-actions actions))))
1862
1863 (defun message-bury (buffer)
1864   "Bury this mail buffer."
1865   (let ((newbuf (other-buffer buffer)))
1866     (bury-buffer buffer)
1867     (if (and (fboundp 'frame-parameters)
1868              (cdr (assq 'dedicated (frame-parameters)))
1869              (not (null (delq (selected-frame) (visible-frame-list)))))
1870         (delete-frame (selected-frame))
1871       (switch-to-buffer newbuf))))
1872
1873 (defun message-send (&optional arg)
1874   "Send the message in the current buffer.
1875 If `message-interactive' is non-nil, wait for success indication
1876 or error messages, and inform user.
1877 Otherwise any failure is reported in a message back to
1878 the user from the mailer."
1879   (interactive "P")
1880   ;; Disabled test.
1881   (when (or (buffer-modified-p)
1882             (message-check-element 'unchanged)
1883             (y-or-n-p "No changes in the buffer; really send? "))
1884     ;; Make it possible to undo the coming changes.
1885     (undo-boundary)
1886     (let ((inhibit-read-only t))
1887       (put-text-property (point-min) (point-max) 'read-only nil))
1888     (message-fix-before-sending)
1889     (run-hooks 'message-send-hook)
1890     (message "Sending...")
1891     (let ((alist message-send-method-alist)
1892           (success t)
1893           elem sent)
1894       (while (and success
1895                   (setq elem (pop alist)))
1896         (when (and (or (not (funcall (cadr elem)))
1897                        (and (or (not (memq (car elem)
1898                                            message-sent-message-via))
1899                                 (y-or-n-p
1900                                  (format
1901                                   "Already sent message via %s; resend? "
1902                                   (car elem))))
1903                             (setq success (funcall (caddr elem) arg)))))
1904           (setq sent t)))
1905       (when (and success sent)
1906         (message-do-fcc)
1907         ;;(when (fboundp 'mail-hist-put-headers-into-history)
1908         ;; (mail-hist-put-headers-into-history))
1909         (run-hooks 'message-sent-hook)
1910         (message "Sending...done")
1911         ;; Mark the buffer as unmodified and delete autosave.
1912         (set-buffer-modified-p nil)
1913         (delete-auto-save-file-if-necessary t)
1914         (message-disassociate-draft)
1915         ;; Delete other mail buffers and stuff.
1916         (message-do-send-housekeeping)
1917         (message-do-actions message-send-actions)
1918         ;; Return success.
1919         t))))
1920
1921 (defun message-send-via-mail (arg)
1922   "Send the current message via mail."
1923   (message-send-mail arg))
1924
1925 (defun message-send-via-news (arg)
1926   "Send the current message via news."
1927   (funcall message-send-news-function arg))
1928
1929 (defun message-fix-before-sending ()
1930   "Do various things to make the message nice before sending it."
1931   ;; Make sure there's a newline at the end of the message.
1932   (goto-char (point-max))
1933   (unless (bolp)
1934     (insert "\n")))
1935
1936 (defun message-add-action (action &rest types)
1937   "Add ACTION to be performed when doing an exit of type TYPES."
1938   (let (var)
1939     (while types
1940       (set (setq var (intern (format "message-%s-actions" (pop types))))
1941            (nconc (symbol-value var) (list action))))))
1942
1943 (defun message-do-actions (actions)
1944   "Perform all actions in ACTIONS."
1945   ;; Now perform actions on successful sending.
1946   (while actions
1947     (ignore-errors
1948       (cond
1949        ;; A simple function.
1950        ((message-functionp (car actions))
1951         (funcall (car actions)))
1952        ;; Something to be evaled.
1953        (t
1954         (eval (car actions)))))
1955     (pop actions)))
1956
1957 (defun message-send-mail (&optional arg)
1958   (require 'mail-utils)
1959   (let ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
1960         (case-fold-search nil)
1961         (news (message-news-p))
1962         (mailbuf (current-buffer)))
1963     (save-restriction
1964       (message-narrow-to-headers)
1965       ;; Insert some headers.
1966       (let ((message-deletable-headers
1967              (if news nil message-deletable-headers)))
1968         (message-generate-headers message-required-mail-headers))
1969       ;; Let the user do all of the above.
1970       (run-hooks 'message-header-hook))
1971     (unwind-protect
1972         (save-excursion
1973           (set-buffer tembuf)
1974           (erase-buffer)
1975           ;; Avoid copying text props.
1976           (insert (format
1977                    "%s" (save-excursion
1978                           (set-buffer mailbuf)
1979                           (buffer-string))))
1980           ;; Remove some headers.
1981           (save-restriction
1982             (message-narrow-to-headers)
1983             ;; Remove some headers.
1984             (message-remove-header message-ignored-mail-headers t))
1985           (goto-char (point-max))
1986           ;; require one newline at the end.
1987           (or (= (preceding-char) ?\n)
1988               (insert ?\n))
1989           (when (and news
1990                      (or (message-fetch-field "cc")
1991                          (message-fetch-field "to")))
1992             (message-insert-courtesy-copy))
1993           (funcall message-send-mail-function))
1994       (kill-buffer tembuf))
1995     (set-buffer mailbuf)
1996     (push 'mail message-sent-message-via)))
1997
1998 (defun message-send-mail-with-sendmail ()
1999   "Send off the prepared buffer with sendmail."
2000   (let ((errbuf (if message-interactive
2001                     (generate-new-buffer " sendmail errors")
2002                   0))
2003         resend-to-addresses delimline)
2004     (let ((case-fold-search t))
2005       (save-restriction
2006         (message-narrow-to-headers)
2007         (setq resend-to-addresses (message-fetch-field "resent-to")))
2008       ;; Change header-delimiter to be what sendmail expects.
2009       (goto-char (point-min))
2010       (re-search-forward
2011        (concat "^" (regexp-quote mail-header-separator) "\n"))
2012       (replace-match "\n")
2013       (backward-char 1)
2014       (setq delimline (point-marker))
2015       (run-hooks 'message-send-mail-hook)
2016       ;; Insert an extra newline if we need it to work around
2017       ;; Sun's bug that swallows newlines.
2018       (goto-char (1+ delimline))
2019       (when (eval message-mailer-swallows-blank-line)
2020         (newline))
2021       (when message-interactive
2022         (save-excursion
2023           (set-buffer errbuf)
2024           (erase-buffer))))
2025     (let ((default-directory "/")
2026           (coding-system-for-write 'binary))
2027       (apply 'call-process-region
2028              (append (list (point-min) (point-max)
2029                            (if (boundp 'sendmail-program)
2030                                sendmail-program
2031                              "/usr/lib/sendmail")
2032                            nil errbuf nil "-oi")
2033                      ;; Always specify who from,
2034                      ;; since some systems have broken sendmails.
2035                      ;; But some systems are more broken with -f, so
2036                      ;; we'll let users override this.
2037                      (if (null message-sendmail-f-is-evil)
2038                          (list "-f" (user-login-name)))
2039                      ;; These mean "report errors by mail"
2040                      ;; and "deliver in background".
2041                      (if (null message-interactive) '("-oem" "-odb"))
2042                      ;; Get the addresses from the message
2043                      ;; unless this is a resend.
2044                      ;; We must not do that for a resend
2045                      ;; because we would find the original addresses.
2046                      ;; For a resend, include the specific addresses.
2047                      (if resend-to-addresses
2048                          (list resend-to-addresses)
2049                        '("-t")))))
2050     (when message-interactive
2051       (save-excursion
2052         (set-buffer errbuf)
2053         (goto-char (point-min))
2054         (while (re-search-forward "\n\n* *" nil t)
2055           (replace-match "; "))
2056         (if (not (zerop (buffer-size)))
2057             (error "Sending...failed to %s"
2058                    (buffer-substring (point-min) (point-max)))))
2059       (when (bufferp errbuf)
2060         (kill-buffer errbuf)))))
2061
2062 (defun message-send-mail-with-qmail ()
2063   "Pass the prepared message buffer to qmail-inject.
2064 Refer to the documentation for the variable `message-send-mail-function'
2065 to find out how to use this."
2066   ;; replace the header delimiter with a blank line
2067   (goto-char (point-min))
2068   (re-search-forward
2069    (concat "^" (regexp-quote mail-header-separator) "\n"))
2070   (replace-match "\n")
2071   (run-hooks 'message-send-mail-hook)
2072   ;; send the message
2073   (case
2074       (let ((coding-system-for-write 'binary))
2075         (apply
2076          'call-process-region 1 (point-max) message-qmail-inject-program
2077          nil nil nil
2078          ;; qmail-inject's default behaviour is to look for addresses on the
2079          ;; command line; if there're none, it scans the headers.
2080          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2081          ;;
2082          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2083          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2084          ;; message from stdin.
2085          ;;
2086          ;; qmail also has the advantage of not having been raped by
2087          ;; various vendors, so we don't have to allow for that, either --
2088          ;; compare this with message-send-mail-with-sendmail and weep
2089          ;; for sendmail's lost innocence.
2090          ;;
2091          ;; all this is way cool coz it lets us keep the arguments entirely
2092          ;; free for -inject-arguments -- a big win for the user and for us
2093          ;; since we don't have to play that double-guessing game and the user
2094          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2095          message-qmail-inject-args))
2096     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2097     ;; we have to look at the retval instead
2098     (0 nil)
2099     (1   (error "qmail-inject reported permanent failure"))
2100     (111 (error "qmail-inject reported transient failure"))
2101     ;; should never happen
2102     (t   (error "qmail-inject reported unknown failure"))))
2103
2104 (defun message-send-mail-with-mh ()
2105   "Send the prepared message buffer with mh."
2106   (let ((mh-previous-window-config nil)
2107         (name (mh-new-draft-name)))
2108     (setq buffer-file-name name)
2109     ;; MH wants to generate these headers itself.
2110     (when message-mh-deletable-headers
2111       (let ((headers message-mh-deletable-headers))
2112         (while headers
2113           (goto-char (point-min))
2114           (and (re-search-forward
2115                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2116                (message-delete-line))
2117           (pop headers))))
2118     (run-hooks 'message-send-mail-hook)
2119     ;; Pass it on to mh.
2120     (mh-send-letter)))
2121
2122 (defun message-send-news (&optional arg)
2123   (let ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2124         (case-fold-search nil)
2125         (method (if (message-functionp message-post-method)
2126                     (funcall message-post-method arg)
2127                   message-post-method))
2128         (messbuf (current-buffer))
2129         (message-syntax-checks
2130          (if arg
2131              (cons '(existing-newsgroups . disabled)
2132                    message-syntax-checks)
2133            message-syntax-checks))
2134         result)
2135     (save-restriction
2136       (message-narrow-to-headers)
2137       ;; Insert some headers.
2138       (message-generate-headers message-required-news-headers)
2139       ;; Let the user do all of the above.
2140       (run-hooks 'message-header-hook))
2141     (message-cleanup-headers)
2142     (if (not (message-check-news-syntax))
2143         (progn
2144           ;;(message "Posting not performed")
2145           nil)
2146       (unwind-protect
2147           (save-excursion
2148             (set-buffer tembuf)
2149             (buffer-disable-undo (current-buffer))
2150             (erase-buffer)
2151             ;; Avoid copying text props.
2152             (insert (format
2153                      "%s" (save-excursion
2154                             (set-buffer messbuf)
2155                             (buffer-string))))
2156             ;; Remove some headers.
2157             (save-restriction
2158               (message-narrow-to-headers)
2159               ;; Remove some headers.
2160               (message-remove-header message-ignored-news-headers t))
2161             (goto-char (point-max))
2162             ;; require one newline at the end.
2163             (or (= (preceding-char) ?\n)
2164                 (insert ?\n))
2165             (let ((case-fold-search t))
2166               ;; Remove the delimiter.
2167               (goto-char (point-min))
2168               (re-search-forward
2169                (concat "^" (regexp-quote mail-header-separator) "\n"))
2170               (replace-match "\n")
2171               (backward-char 1))
2172             (run-hooks 'message-send-news-hook)
2173             ;;(require (car method))
2174             ;;(funcall (intern (format "%s-open-server" (car method)))
2175             ;;(cadr method) (cddr method))
2176             ;;(setq result
2177             ;;    (funcall (intern (format "%s-request-post" (car method)))
2178             ;;             (cadr method)))
2179             (gnus-open-server method)
2180             (setq result (gnus-request-post method)))
2181         (kill-buffer tembuf))
2182       (set-buffer messbuf)
2183       (if result
2184           (push 'news message-sent-message-via)
2185         (message "Couldn't send message via news: %s"
2186                  (nnheader-get-report (car method)))
2187         nil))))
2188
2189 ;;;
2190 ;;; Header generation & syntax checking.
2191 ;;;
2192
2193 (defmacro message-check (type &rest forms)
2194   "Eval FORMS if TYPE is to be checked."
2195   `(or (message-check-element ,type)
2196        (save-excursion
2197          ,@forms)))
2198
2199 (put 'message-check 'lisp-indent-function 1)
2200 (put 'message-check 'edebug-form-spec '(form body))
2201
2202 (defun message-check-element (type)
2203   "Returns non-nil if this type is not to be checked."
2204   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2205       t
2206     (let ((able (assq type message-syntax-checks)))
2207       (and (consp able)
2208            (eq (cdr able) 'disabled)))))
2209
2210 (defun message-check-news-syntax ()
2211   "Check the syntax of the message."
2212   (save-excursion
2213     (save-restriction
2214       (widen)
2215       (and
2216        ;; We narrow to the headers and check them first.
2217        (save-excursion
2218          (save-restriction
2219            (message-narrow-to-headers)
2220            (message-check-news-header-syntax)))
2221        ;; Check the body.
2222        (message-check-news-body-syntax)))))
2223
2224 (defun message-check-news-header-syntax ()
2225   (and
2226    ;; Check the Subject header.
2227    (message-check 'subject
2228      (let* ((case-fold-search t)
2229             (subject (message-fetch-field "subject")))
2230        (or
2231         (and subject
2232              (not (string-match "\\`[ \t]*\\'" subject)))
2233         (ignore
2234          (message
2235           "The subject field is empty or missing.  Posting is denied.")))))
2236    ;; Check for commands in Subject.
2237    (message-check 'subject-cmsg
2238      (if (string-match "^cmsg " (message-fetch-field "subject"))
2239          (y-or-n-p
2240           "The control code \"cmsg\" is in the subject.  Really post? ")
2241        t))
2242    ;; Check for multiple identical headers.
2243    (message-check 'multiple-headers
2244      (let (found)
2245        (while (and (not found)
2246                    (re-search-forward "^[^ \t:]+: " nil t))
2247          (save-excursion
2248            (or (re-search-forward
2249                 (concat "^"
2250                         (regexp-quote
2251                          (setq found
2252                                (buffer-substring
2253                                 (match-beginning 0) (- (match-end 0) 2))))
2254                         ":")
2255                 nil t)
2256                (setq found nil))))
2257        (if found
2258            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2259          t)))
2260    ;; Check for Version and Sendsys.
2261    (message-check 'sendsys
2262      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2263          (y-or-n-p
2264           (format "The article contains a %s command.  Really post? "
2265                   (buffer-substring (match-beginning 0)
2266                                     (1- (match-end 0)))))
2267        t))
2268    ;; See whether we can shorten Followup-To.
2269    (message-check 'shorten-followup-to
2270      (let ((newsgroups (message-fetch-field "newsgroups"))
2271            (followup-to (message-fetch-field "followup-to"))
2272            to)
2273        (when (and newsgroups
2274                   (string-match "," newsgroups)
2275                   (not followup-to)
2276                   (not
2277                    (zerop
2278                     (length
2279                      (setq to (completing-read
2280                                "Followups to: (default all groups) "
2281                                (mapcar (lambda (g) (list g))
2282                                        (cons "poster"
2283                                              (message-tokenize-header
2284                                               newsgroups)))))))))
2285          (goto-char (point-min))
2286          (insert "Followup-To: " to "\n"))
2287        t))
2288    ;; Check "Shoot me".
2289    (message-check 'shoot
2290      (if (re-search-forward
2291           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2292          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2293        t))
2294    ;; Check for Approved.
2295    (message-check 'approved
2296      (if (re-search-forward "^Approved:" nil t)
2297          (y-or-n-p "The article contains an Approved header.  Really post? ")
2298        t))
2299    ;; Check the Message-ID header.
2300    (message-check 'message-id
2301      (let* ((case-fold-search t)
2302             (message-id (message-fetch-field "message-id" t)))
2303        (or (not message-id)
2304            ;; Is there an @ in the ID?
2305            (and (string-match "@" message-id)
2306                 ;; Is there a dot in the ID?
2307                 (string-match "@[^.]*\\." message-id)
2308                 ;; Does the ID end with a dot?
2309                 (not (string-match "\\.>" message-id)))
2310            (y-or-n-p
2311             (format "The Message-ID looks strange: \"%s\".  Really post? "
2312                     message-id)))))
2313    ;; Check the Newsgroups & Followup-To headers.
2314    (message-check 'existing-newsgroups
2315      (let* ((case-fold-search t)
2316             (newsgroups (message-fetch-field "newsgroups"))
2317             (followup-to (message-fetch-field "followup-to"))
2318             (groups (message-tokenize-header
2319                      (if followup-to
2320                          (concat newsgroups "," followup-to)
2321                        newsgroups)))
2322             (hashtb (and (boundp 'gnus-active-hashtb)
2323                          gnus-active-hashtb))
2324             errors)
2325        (if (or (not hashtb)
2326                (not (boundp 'gnus-read-active-file))
2327                (not gnus-read-active-file)
2328                (eq gnus-read-active-file 'some))
2329            t
2330          (while groups
2331            (when (and (not (boundp (intern (car groups) hashtb)))
2332                       (not (equal (car groups) "poster")))
2333              (push (car groups) errors))
2334            (pop groups))
2335          (if (not errors)
2336              t
2337            (y-or-n-p
2338             (format
2339              "Really post to %s unknown group%s: %s "
2340              (if (= (length errors) 1) "this" "these")
2341              (if (= (length errors) 1) "" "s")
2342              (mapconcat 'identity errors ", ")))))))
2343    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2344    (message-check 'valid-newsgroups
2345      (let ((case-fold-search t)
2346            (headers '("Newsgroups" "Followup-To"))
2347            header error)
2348        (while (and headers (not error))
2349          (when (setq header (mail-fetch-field (car headers)))
2350            (if (or
2351                 (not
2352                  (string-match
2353                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2354                   header))
2355                 (memq
2356                  nil (mapcar
2357                       (lambda (g)
2358                         (not (string-match "\\.\\'\\|\\.\\." g)))
2359                       (message-tokenize-header header ","))))
2360                (setq error t)))
2361          (unless error
2362            (pop headers)))
2363        (if (not error)
2364            t
2365          (y-or-n-p
2366           (format "The %s header looks odd: \"%s\".  Really post? "
2367                   (car headers) header)))))
2368    (message-check 'repeated-newsgroups
2369      (let ((case-fold-search t)
2370            (headers '("Newsgroups" "Followup-To"))
2371            header error groups group)
2372        (while (and headers
2373                    (not error))
2374          (when (setq header (mail-fetch-field (pop headers)))
2375            (setq groups (message-tokenize-header header ","))
2376            (while (setq group (pop groups))
2377              (when (member group groups)
2378                (setq error group
2379                      groups nil)))))
2380        (if (not error)
2381            t
2382          (y-or-n-p
2383           (format "Group %s is repeated in headers.  Really post? " error)))))
2384    ;; Check the From header.
2385    (message-check 'from
2386      (let* ((case-fold-search t)
2387             (from (message-fetch-field "from"))
2388             (ad (nth 1 (mail-extract-address-components from))))
2389        (cond
2390         ((not from)
2391          (message "There is no From line.  Posting is denied.")
2392          nil)
2393         ((or (not (string-match "@[^\\.]*\\." ad)) ;larsi@ifi
2394              (string-match "\\.\\." ad) ;larsi@ifi..uio
2395              (string-match "@\\." ad)   ;larsi@.ifi.uio
2396              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2397              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2398              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2399          (message
2400           "Denied posting -- the From looks strange: \"%s\"." from)
2401          nil)
2402         (t t))))))
2403
2404 (defun message-check-news-body-syntax ()
2405   (and
2406    ;; Check for long lines.
2407    (message-check 'long-lines
2408      (goto-char (point-min))
2409      (re-search-forward
2410       (concat "^" (regexp-quote mail-header-separator) "$"))
2411      (while (and
2412              (progn
2413                (end-of-line)
2414                (< (current-column) 80))
2415              (zerop (forward-line 1))))
2416      (or (bolp)
2417          (eobp)
2418          (y-or-n-p
2419           "You have lines longer than 79 characters.  Really post? ")))
2420    ;; Check whether the article is empty.
2421    (message-check 'empty
2422      (goto-char (point-min))
2423      (re-search-forward
2424       (concat "^" (regexp-quote mail-header-separator) "$"))
2425      (forward-line 1)
2426      (let ((b (point)))
2427        (goto-char (point-max))
2428        (re-search-backward message-signature-separator nil t)
2429        (beginning-of-line)
2430        (or (re-search-backward "[^ \n\t]" b t)
2431            (y-or-n-p "Empty article.  Really post? "))))
2432    ;; Check for control characters.
2433    (message-check 'control-chars
2434      (if (re-search-forward "[\000-\007\013\015-\037\200-\237]" nil t)
2435          (y-or-n-p
2436           "The article contains control characters.  Really post? ")
2437        t))
2438    ;; Check excessive size.
2439    (message-check 'size
2440      (if (> (buffer-size) 60000)
2441          (y-or-n-p
2442           (format "The article is %d octets long.  Really post? "
2443                   (buffer-size)))
2444        t))
2445    ;; Check whether any new text has been added.
2446    (message-check 'new-text
2447      (or
2448       (not message-checksum)
2449       (not (eq (message-checksum) message-checksum))
2450       (y-or-n-p
2451        "It looks like no new text has been added.  Really post? ")))
2452    ;; Check the length of the signature.
2453    (message-check 'signature
2454      (goto-char (point-max))
2455      (if (or (not (re-search-backward message-signature-separator nil t))
2456              (search-forward message-forward-end-separator nil t))
2457          t
2458        (if (> (count-lines (point) (point-max)) 5)
2459            (y-or-n-p
2460             (format
2461              "Your .sig is %d lines; it should be max 4.  Really post? "
2462              (1- (count-lines (point) (point-max)))))
2463          t)))))
2464
2465 (defun message-checksum ()
2466   "Return a \"checksum\" for the current buffer."
2467   (let ((sum 0))
2468     (save-excursion
2469       (goto-char (point-min))
2470       (re-search-forward
2471        (concat "^" (regexp-quote mail-header-separator) "$"))
2472       (while (not (eobp))
2473         (when (not (looking-at "[ \t\n]"))
2474           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
2475                             (following-char))))
2476         (forward-char 1)))
2477     sum))
2478
2479 (defun message-do-fcc ()
2480   "Process Fcc headers in the current buffer."
2481   (let ((case-fold-search t)
2482         (buf (current-buffer))
2483         list file)
2484     (save-excursion
2485       (set-buffer (get-buffer-create " *message temp*"))
2486       (buffer-disable-undo (current-buffer))
2487       (erase-buffer)
2488       (insert-buffer-substring buf)
2489       (save-restriction
2490         (message-narrow-to-headers)
2491         (while (setq file (message-fetch-field "fcc"))
2492           (push file list)
2493           (message-remove-header "fcc" nil t)))
2494       (goto-char (point-min))
2495       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
2496       (replace-match "" t t)
2497       ;; Process FCC operations.
2498       (while list
2499         (setq file (pop list))
2500         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
2501             ;; Pipe the article to the program in question.
2502             (call-process-region (point-min) (point-max) shell-file-name
2503                                  nil nil nil shell-command-switch
2504                                  (match-string 1 file))
2505           ;; Save the article.
2506           (setq file (expand-file-name file))
2507           (unless (file-exists-p (file-name-directory file))
2508             (make-directory (file-name-directory file) t))
2509           (if (and message-fcc-handler-function
2510                    (not (eq message-fcc-handler-function 'rmail-output)))
2511               (funcall message-fcc-handler-function file)
2512             (if (and (file-readable-p file) (mail-file-babyl-p file))
2513                 (rmail-output file 1 nil t)
2514               (let ((mail-use-rfc822 t))
2515                 (rmail-output file 1 t t))))))
2516
2517       (kill-buffer (current-buffer)))))
2518
2519 (defun message-output (filename)
2520   "Append this article to Unix/babyl mail file.."
2521   (if (and (file-readable-p filename)
2522            (mail-file-babyl-p filename))
2523       (gnus-output-to-rmail filename t)
2524     (gnus-output-to-mail filename t)))
2525
2526 (defun message-cleanup-headers ()
2527   "Do various automatic cleanups of the headers."
2528   ;; Remove empty lines in the header.
2529   (save-restriction
2530     (message-narrow-to-headers)
2531     ;; Remove blank lines.
2532     (while (re-search-forward "^[ \t]*\n" nil t)
2533       (replace-match "" t t))
2534
2535     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
2536     ;; spaces to comma and eliminate spaces around commas.  Eliminate
2537     ;; embedded line breaks.
2538     (goto-char (point-min))
2539     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2540       (save-restriction
2541         (narrow-to-region
2542          (point)
2543          (if (re-search-forward "^[^ \t]" nil t)
2544              (match-beginning 0)
2545            (forward-line 1)
2546            (point)))
2547         (goto-char (point-min))
2548         (while (re-search-forward "\n[ \t]+" nil t)
2549           (replace-match " " t t))      ;No line breaks (too confusing)
2550         (goto-char (point-min))
2551         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
2552           (replace-match "," t t))
2553         (goto-char (point-min))
2554         ;; Remove trailing commas.
2555         (when (re-search-forward ",+$" nil t)
2556           (replace-match "" t t))))))
2557
2558 (defun message-make-date ()
2559   "Make a valid data header."
2560   (let ((now (current-time)))
2561     (timezone-make-date-arpa-standard
2562      (current-time-string now) (current-time-zone now))))
2563
2564 (defun message-make-message-id ()
2565   "Make a unique Message-ID."
2566   (concat "<" (message-unique-id)
2567           (let ((psubject (save-excursion (message-fetch-field "subject")))
2568                 (psupersedes
2569                  (save-excursion (message-fetch-field "supersedes"))))
2570             (if (or
2571                  (and message-reply-headers
2572                       (mail-header-references message-reply-headers)
2573                       (mail-header-subject message-reply-headers)
2574                       psubject
2575                       (mail-header-subject message-reply-headers)
2576                       (not (string=
2577                             (message-strip-subject-re
2578                              (mail-header-subject message-reply-headers))
2579                             (message-strip-subject-re psubject))))
2580                  (and psupersedes
2581                       (string-match "_-_@" psupersedes)))
2582                 "_-_" ""))
2583           "@" (message-make-fqdn) ">"))
2584
2585 (defvar message-unique-id-char nil)
2586
2587 ;; If you ever change this function, make sure the new version
2588 ;; cannot generate IDs that the old version could.
2589 ;; You might for example insert a "." somewhere (not next to another dot
2590 ;; or string boundary), or modify the "fsf" string.
2591 (defun message-unique-id ()
2592   ;; Don't use microseconds from (current-time), they may be unsupported.
2593   ;; Instead we use this randomly inited counter.
2594   (setq message-unique-id-char
2595         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2596            ;; (current-time) returns 16-bit ints,
2597            ;; and 2^16*25 just fits into 4 digits i base 36.
2598            (* 25 25)))
2599   (let ((tm (current-time)))
2600     (concat
2601      (if (memq system-type '(ms-dos emx vax-vms))
2602          (let ((user (downcase (user-login-name))))
2603            (while (string-match "[^a-z0-9_]" user)
2604              (aset user (match-beginning 0) ?_))
2605            user)
2606        (message-number-base36 (user-uid) -1))
2607      (message-number-base36 (+ (car   tm)
2608                                (lsh (% message-unique-id-char 25) 16)) 4)
2609      (message-number-base36 (+ (nth 1 tm)
2610                                (lsh (/ message-unique-id-char 25) 16)) 4)
2611      ;; Append the newsreader name, because while the generated
2612      ;; ID is unique to this newsreader, other newsreaders might
2613      ;; otherwise generate the same ID via another algorithm.
2614      ".fsf")))
2615
2616 (defun message-number-base36 (num len)
2617   (if (if (< len 0)
2618           (<= num 0)
2619         (= len 0))
2620       ""
2621     (concat (message-number-base36 (/ num 36) (1- len))
2622             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
2623                                   (% num 36))))))
2624
2625 (defun message-make-organization ()
2626   "Make an Organization header."
2627   (let* ((organization
2628           (when message-user-organization
2629                 (if (message-functionp message-user-organization)
2630                     (funcall message-user-organization)
2631                   message-user-organization))))
2632     (save-excursion
2633       (message-set-work-buffer)
2634       (cond ((stringp organization)
2635              (insert organization))
2636             ((and (eq t organization)
2637                   message-user-organization-file
2638                   (file-exists-p message-user-organization-file))
2639              (insert-file-contents message-user-organization-file)))
2640       (goto-char (point-min))
2641       (while (re-search-forward "[\t\n]+" nil t)
2642         (replace-match "" t t))
2643       (unless (zerop (buffer-size))
2644         (buffer-string)))))
2645
2646 (defun message-make-lines ()
2647   "Count the number of lines and return numeric string."
2648   (save-excursion
2649     (save-restriction
2650       (widen)
2651       (goto-char (point-min))
2652       (re-search-forward
2653        (concat "^" (regexp-quote mail-header-separator) "$"))
2654       (forward-line 1)
2655       (int-to-string (count-lines (point) (point-max))))))
2656
2657 (defun message-make-in-reply-to ()
2658   "Return the In-Reply-To header for this message."
2659   (when message-reply-headers
2660     (let ((from (mail-header-from message-reply-headers))
2661           (date (mail-header-date message-reply-headers)))
2662       (when from
2663         (let ((stop-pos
2664                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
2665           (concat (if (and stop-pos
2666                            (not (zerop stop-pos)))
2667                       (substring from 0 stop-pos) from)
2668                   "'s message of \""
2669                   (if (or (not date) (string= date ""))
2670                       "(unknown date)" date)
2671                   "\""))))))
2672
2673 (defun message-make-distribution ()
2674   "Make a Distribution header."
2675   (let ((orig-distribution (message-fetch-reply-field "distribution")))
2676     (cond ((message-functionp message-distribution-function)
2677            (funcall message-distribution-function))
2678           (t orig-distribution))))
2679
2680 (defun message-make-expires ()
2681   "Return an Expires header based on `message-expires'."
2682   (let ((current (current-time))
2683         (future (* 1.0 message-expires 60 60 24)))
2684     ;; Add the future to current.
2685     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
2686     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
2687     ;; Return the date in the future in UT.
2688     (timezone-make-date-arpa-standard
2689      (current-time-string current) (current-time-zone current) '(0 "UT"))))
2690
2691 (defun message-make-path ()
2692   "Return uucp path."
2693   (let ((login-name (user-login-name)))
2694     (cond ((null message-user-path)
2695            (concat (system-name) "!" login-name))
2696           ((stringp message-user-path)
2697            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
2698            (concat message-user-path "!" login-name))
2699           (t login-name))))
2700
2701 (defun message-make-from ()
2702   "Make a From header."
2703   (let* ((style message-from-style)
2704          (login (message-make-address))
2705          (fullname
2706           (or (and (boundp 'user-full-name)
2707                    user-full-name)
2708               (user-full-name))))
2709     (when (string= fullname "&")
2710       (setq fullname (user-login-name)))
2711     (save-excursion
2712       (message-set-work-buffer)
2713       (cond
2714        ((or (null style)
2715             (equal fullname ""))
2716         (insert login))
2717        ((or (eq style 'angles)
2718             (and (not (eq style 'parens))
2719                  ;; Use angles if no quoting is needed, or if parens would
2720                  ;; need quoting too.
2721                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
2722                      (let ((tmp (concat fullname nil)))
2723                        (while (string-match "([^()]*)" tmp)
2724                          (aset tmp (match-beginning 0) ?-)
2725                          (aset tmp (1- (match-end 0)) ?-))
2726                        (string-match "[\\()]" tmp)))))
2727         (insert fullname)
2728         (goto-char (point-min))
2729         ;; Look for a character that cannot appear unquoted
2730         ;; according to RFC 822.
2731         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
2732           ;; Quote fullname, escaping specials.
2733           (goto-char (point-min))
2734           (insert "\"")
2735           (while (re-search-forward "[\"\\]" nil 1)
2736             (replace-match "\\\\\\&" t))
2737           (insert "\""))
2738         (insert " <" login ">"))
2739        (t                               ; 'parens or default
2740         (insert login " (")
2741         (let ((fullname-start (point)))
2742           (insert fullname)
2743           (goto-char fullname-start)
2744           ;; RFC 822 says \ and nonmatching parentheses
2745           ;; must be escaped in comments.
2746           ;; Escape every instance of ()\ ...
2747           (while (re-search-forward "[()\\]" nil 1)
2748             (replace-match "\\\\\\&" t))
2749           ;; ... then undo escaping of matching parentheses,
2750           ;; including matching nested parentheses.
2751           (goto-char fullname-start)
2752           (while (re-search-forward
2753                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
2754                   nil 1)
2755             (replace-match "\\1(\\3)" t)
2756             (goto-char fullname-start)))
2757         (insert ")")))
2758       (buffer-string))))
2759
2760 (defun message-make-sender ()
2761   "Return the \"real\" user address.
2762 This function tries to ignore all user modifications, and
2763 give as trustworthy answer as possible."
2764   (concat (user-login-name) "@" (system-name)))
2765
2766 (defun message-make-address ()
2767   "Make the address of the user."
2768   (or (message-user-mail-address)
2769       (concat (user-login-name) "@" (message-make-domain))))
2770
2771 (defun message-user-mail-address ()
2772   "Return the pertinent part of `user-mail-address'."
2773   (when user-mail-address
2774     (if (string-match " " user-mail-address)
2775         (nth 1 (mail-extract-address-components user-mail-address))
2776       user-mail-address)))
2777
2778 (defun message-make-fqdn ()
2779   "Return user's fully qualified domain name."
2780   (let ((system-name (system-name))
2781         (user-mail (message-user-mail-address)))
2782     (cond
2783      ((string-match "[^.]\\.[^.]" system-name)
2784       ;; `system-name' returned the right result.
2785       system-name)
2786      ;; Try `mail-host-address'.
2787      ((and (boundp 'mail-host-address)
2788            (stringp mail-host-address)
2789            (string-match "\\." mail-host-address))
2790       mail-host-address)
2791      ;; We try `user-mail-address' as a backup.
2792      ((and user-mail
2793            (string-match "\\." user-mail)
2794            (string-match "@\\(.*\\)\\'" user-mail))
2795       (match-string 1 user-mail))
2796      ;; Default to this bogus thing.
2797      (t
2798       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
2799
2800 (defun message-make-host-name ()
2801   "Return the name of the host."
2802   (let ((fqdn (message-make-fqdn)))
2803     (string-match "^[^.]+\\." fqdn)
2804     (substring fqdn 0 (1- (match-end 0)))))
2805
2806 (defun message-make-domain ()
2807   "Return the domain name."
2808   (or mail-host-address
2809       (message-make-fqdn)))
2810
2811 (defun message-generate-headers (headers)
2812   "Prepare article HEADERS.
2813 Headers already prepared in the buffer are not modified."
2814   (save-restriction
2815     (message-narrow-to-headers)
2816     (let* ((Date (message-make-date))
2817            (Message-ID (message-make-message-id))
2818            (Organization (message-make-organization))
2819            (From (message-make-from))
2820            (Path (message-make-path))
2821            (Subject nil)
2822            (Newsgroups nil)
2823            (In-Reply-To (message-make-in-reply-to))
2824            (To nil)
2825            (Distribution (message-make-distribution))
2826            (Lines (message-make-lines))
2827            (X-Newsreader message-newsreader)
2828            (X-Mailer (and (not (message-fetch-field "X-Newsreader"))
2829                           message-mailer))
2830            (Expires (message-make-expires))
2831            (case-fold-search t)
2832            header value elem)
2833       ;; First we remove any old generated headers.
2834       (let ((headers message-deletable-headers))
2835         (unless (buffer-modified-p)
2836           (setq headers (delq 'Message-ID (copy-sequence headers))))
2837         (while headers
2838           (goto-char (point-min))
2839           (and (re-search-forward
2840                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2841                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
2842                (message-delete-line))
2843           (pop headers)))
2844       ;; Go through all the required headers and see if they are in the
2845       ;; articles already.  If they are not, or are empty, they are
2846       ;; inserted automatically - except for Subject, Newsgroups and
2847       ;; Distribution.
2848       (while headers
2849         (goto-char (point-min))
2850         (setq elem (pop headers))
2851         (if (consp elem)
2852             (if (eq (car elem) 'optional)
2853                 (setq header (cdr elem))
2854               (setq header (car elem)))
2855           (setq header elem))
2856         (when (or (not (re-search-forward
2857                         (concat "^"
2858                                 (regexp-quote
2859                                  (downcase
2860                                   (if (stringp header)
2861                                       header
2862                                     (symbol-name header))))
2863                                 ":")
2864                         nil t))
2865                   (progn
2866                     ;; The header was found.  We insert a space after the
2867                     ;; colon, if there is none.
2868                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
2869                     ;; Find out whether the header is empty...
2870                     (looking-at "[ \t]*$")))
2871           ;; So we find out what value we should insert.
2872           (setq value
2873                 (cond
2874                  ((and (consp elem) (eq (car elem) 'optional))
2875                   ;; This is an optional header.  If the cdr of this
2876                   ;; is something that is nil, then we do not insert
2877                   ;; this header.
2878                   (setq header (cdr elem))
2879                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
2880                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
2881                  ((consp elem)
2882                   ;; The element is a cons.  Either the cdr is a
2883                   ;; string to be inserted verbatim, or it is a
2884                   ;; function, and we insert the value returned from
2885                   ;; this function.
2886                   (or (and (stringp (cdr elem)) (cdr elem))
2887                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
2888                  ((and (boundp header) (symbol-value header))
2889                   ;; The element is a symbol.  We insert the value
2890                   ;; of this symbol, if any.
2891                   (symbol-value header))
2892                  (t
2893                   ;; We couldn't generate a value for this header,
2894                   ;; so we just ask the user.
2895                   (read-from-minibuffer
2896                    (format "Empty header for %s; enter value: " header)))))
2897           ;; Finally insert the header.
2898           (when (and value
2899                      (not (equal value "")))
2900             (save-excursion
2901               (if (bolp)
2902                   (progn
2903                     ;; This header didn't exist, so we insert it.
2904                     (goto-char (point-max))
2905                     (insert (if (stringp header) header (symbol-name header))
2906                             ": " value "\n")
2907                     (forward-line -1))
2908                 ;; The value of this header was empty, so we clear
2909                 ;; totally and insert the new value.
2910                 (delete-region (point) (gnus-point-at-eol))
2911                 (insert value))
2912               ;; Add the deletable property to the headers that require it.
2913               (and (memq header message-deletable-headers)
2914                    (progn (beginning-of-line) (looking-at "[^:]+: "))
2915                    (add-text-properties
2916                     (point) (match-end 0)
2917                     '(message-deletable t face italic) (current-buffer)))))))
2918       ;; Insert new Sender if the From is strange.
2919       (let ((from (message-fetch-field "from"))
2920             (sender (message-fetch-field "sender"))
2921             (secure-sender (message-make-sender)))
2922         (when (and from
2923                    (not (message-check-element 'sender))
2924                    (not (string=
2925                          (downcase
2926                           (cadr (mail-extract-address-components from)))
2927                          (downcase secure-sender)))
2928                    (or (null sender)
2929                        (not
2930                         (string=
2931                          (downcase
2932                           (cadr (mail-extract-address-components sender)))
2933                          (downcase secure-sender)))))
2934           (goto-char (point-min))
2935           ;; Rename any old Sender headers to Original-Sender.
2936           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
2937             (beginning-of-line)
2938             (insert "Original-")
2939             (beginning-of-line))
2940           (when (or (message-news-p)
2941                     (string-match "@.+\\.." secure-sender))
2942             (insert "Sender: " secure-sender "\n")))))))
2943
2944 (defun message-insert-courtesy-copy ()
2945   "Insert a courtesy message in mail copies of combined messages."
2946   (let (newsgroups)
2947     (save-excursion
2948       (save-restriction
2949         (message-narrow-to-headers)
2950         (when (setq newsgroups (message-fetch-field "newsgroups"))
2951           (goto-char (point-max))
2952           (insert "Posted-To: " newsgroups "\n")))
2953       (forward-line 1)
2954       (when message-courtesy-message
2955         (cond
2956          ((string-match "%s" message-courtesy-message)
2957           (insert (format message-courtesy-message newsgroups)))
2958          (t
2959           (insert message-courtesy-message)))))))
2960
2961 ;;;
2962 ;;; Setting up a message buffer
2963 ;;;
2964
2965 (defun message-fill-address (header value)
2966   (save-restriction
2967     (narrow-to-region (point) (point))
2968     (insert (capitalize (symbol-name header))
2969             ": "
2970             (if (consp value) (car value) value)
2971             "\n")
2972     (narrow-to-region (point-min) (1- (point-max)))
2973     (let (quoted last)
2974       (goto-char (point-min))
2975       (while (not (eobp))
2976         (skip-chars-forward "^,\"" (point-max))
2977         (if (or (= (following-char) ?,)
2978                 (eobp))
2979             (when (not quoted)
2980               (if (and (> (current-column) 78)
2981                        last)
2982                   (progn
2983                     (save-excursion
2984                       (goto-char last)
2985                       (insert "\n\t"))
2986                     (setq last (1+ (point))))
2987                 (setq last (1+ (point)))))
2988           (setq quoted (not quoted)))
2989         (unless (eobp)
2990           (forward-char 1))))
2991     (goto-char (point-max))
2992     (widen)
2993     (forward-line 1)))
2994
2995 (defun message-fill-header (header value)
2996   (let ((begin (point))
2997         (fill-column 990)
2998         (fill-prefix "\t"))
2999     (insert (capitalize (symbol-name header))
3000             ": "
3001             (if (consp value) (car value) value)
3002             "\n")
3003     (save-restriction
3004       (narrow-to-region begin (point))
3005       (fill-region-as-paragraph begin (point))
3006       ;; Tapdance around looong Message-IDs.
3007       (forward-line -1)
3008       (when (looking-at "[ \t]*$")
3009         (message-delete-line))
3010       (goto-char begin)
3011       (re-search-forward ":" nil t)
3012       (when (looking-at "\n[ \t]+")
3013         (replace-match " " t t))
3014       (goto-char (point-max)))))
3015
3016 (defun message-shorten-references (header references)
3017   "Limit REFERENCES to be shorter than 988 characters."
3018   (let ((max 988)
3019         (cut 4)
3020         refs)
3021     (nnheader-temp-write nil
3022       (insert references)
3023       (goto-char (point-min))
3024       (while (re-search-forward "<[^>]+>" nil t)
3025         (push (match-string 0) refs))
3026       (setq refs (nreverse refs))
3027       (while (> (length (mapconcat 'identity refs " ")) max)
3028         (when (< (length refs) (1+ cut))
3029           (decf cut))
3030         (setcdr (nthcdr cut refs) (cddr (nthcdr cut refs)))))
3031     (insert (capitalize (symbol-name header)) ": "
3032             (mapconcat 'identity refs " ") "\n")))
3033
3034 (defun message-position-point ()
3035   "Move point to where the user probably wants to find it."
3036   (message-narrow-to-headers)
3037   (cond
3038    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3039     (search-backward ":" )
3040     (widen)
3041     (forward-char 1)
3042     (if (= (following-char) ? )
3043         (forward-char 1)
3044       (insert " ")))
3045    (t
3046     (goto-char (point-max))
3047     (widen)
3048     (forward-line 1)
3049     (unless (looking-at "$")
3050       (forward-line 2)))
3051    (sit-for 0)))
3052
3053 (defun message-buffer-name (type &optional to group)
3054   "Return a new (unique) buffer name based on TYPE and TO."
3055   (cond
3056    ;; Check whether `message-generate-new-buffers' is a function,
3057    ;; and if so, call it.
3058    ((message-functionp message-generate-new-buffers)
3059     (funcall message-generate-new-buffers type to group))
3060    ;; Generate a new buffer name The Message Way.
3061    (message-generate-new-buffers
3062     (generate-new-buffer-name
3063      (concat "*" type
3064              (if to
3065                  (concat " to "
3066                          (or (car (mail-extract-address-components to))
3067                              to) "")
3068                "")
3069              (if (and group (not (string= group ""))) (concat " on " group) "")
3070              "*")))
3071    ;; Use standard name.
3072    (t
3073     (format "*%s message*" type))))
3074
3075 (defun message-pop-to-buffer (name)
3076   "Pop to buffer NAME, and warn if it already exists and is modified."
3077   (let ((buffer (get-buffer name))
3078         (cur (current-buffer)))
3079     (if (and buffer
3080              (buffer-name buffer))
3081         (progn
3082           (set-buffer (pop-to-buffer buffer))
3083           (when (and (buffer-modified-p)
3084                      (not (y-or-n-p
3085                            "Message already being composed; erase? ")))
3086             (error "Message being composed")))
3087       (set-buffer (pop-to-buffer name)))
3088     (erase-buffer)
3089     (message-mode)))
3090
3091 (defun message-do-send-housekeeping ()
3092   "Kill old message buffers."
3093   ;; We might have sent this buffer already.  Delete it from the
3094   ;; list of buffers.
3095   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3096   (while (and message-max-buffers
3097               message-buffer-list
3098               (>= (length message-buffer-list) message-max-buffers))
3099     ;; Kill the oldest buffer -- unless it has been changed.
3100     (let ((buffer (pop message-buffer-list)))
3101       (when (and (buffer-name buffer)
3102                  (not (buffer-modified-p buffer)))
3103         (kill-buffer buffer))))
3104   ;; Rename the buffer.
3105   (if message-send-rename-function
3106       (funcall message-send-rename-function)
3107     (when (string-match "\\`\\*" (buffer-name))
3108       (rename-buffer
3109        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3110   ;; Push the current buffer onto the list.
3111   (when message-max-buffers
3112     (setq message-buffer-list
3113           (nconc message-buffer-list (list (current-buffer))))))
3114
3115 (defvar mc-modes-alist)
3116 (defun message-setup (headers &optional replybuffer actions)
3117   (when (and (boundp 'mc-modes-alist)
3118              (not (assq 'message-mode mc-modes-alist)))
3119     (push '(message-mode (encrypt . mc-encrypt-message)
3120                          (sign . mc-sign-message))
3121           mc-modes-alist))
3122   (when actions
3123     (setq message-send-actions actions))
3124   (setq message-reply-buffer replybuffer)
3125   (goto-char (point-min))
3126   ;; Insert all the headers.
3127   (mail-header-format
3128    (let ((h headers)
3129          (alist message-header-format-alist))
3130      (while h
3131        (unless (assq (caar h) message-header-format-alist)
3132          (push (list (caar h)) alist))
3133        (pop h))
3134      alist)
3135    headers)
3136   (delete-region (point) (progn (forward-line -1) (point)))
3137   (when message-default-headers
3138     (insert message-default-headers)
3139     (or (bolp) (insert ?\n)))
3140   (put-text-property
3141    (point)
3142    (progn
3143      (insert mail-header-separator "\n")
3144      (1- (point)))
3145    'read-only nil)
3146   (forward-line -1)
3147   (when (message-news-p)
3148     (when message-default-news-headers
3149       (insert message-default-news-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-news-headers))))))
3156   (when (message-mail-p)
3157     (when message-default-mail-headers
3158       (insert message-default-mail-headers)
3159       (or (bolp) (insert ?\n)))
3160     (when message-generate-headers-first
3161       (message-generate-headers
3162        (delq 'Lines
3163              (delq 'Subject
3164                    (copy-sequence message-required-mail-headers))))))
3165   (run-hooks 'message-signature-setup-hook)
3166   (message-insert-signature)
3167   (save-restriction
3168     (message-narrow-to-headers)
3169     (run-hooks 'message-header-setup-hook))
3170   (set-buffer-modified-p nil)
3171   (setq buffer-undo-list nil)
3172   (run-hooks 'message-setup-hook)
3173   (message-position-point)
3174   (undo-boundary))
3175
3176 (defun message-set-auto-save-file-name ()
3177   "Associate the message buffer with a file in the drafts directory."
3178   (when message-autosave-directory
3179     (if (gnus-alive-p)
3180         (setq message-draft-article
3181               (nndraft-request-associate-buffer "drafts"))
3182       (setq buffer-file-name (expand-file-name "*message*"
3183                                                message-autosave-directory))
3184       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
3185     (clear-visited-file-modtime)))
3186
3187 (defun message-disassociate-draft ()
3188   "Disassociate the message buffer from the drafts directory."
3189   (when message-draft-article
3190     (nndraft-request-expire-articles
3191      (list message-draft-article) "drafts" nil t)))
3192
3193 \f
3194
3195 ;;;
3196 ;;; Commands for interfacing with message
3197 ;;;
3198
3199 ;;;###autoload
3200 (defun message-mail (&optional to subject
3201                                other-headers continue switch-function
3202                                yank-action send-actions)
3203   "Start editing a mail message to be sent."
3204   (interactive)
3205   (let ((message-this-is-mail t))
3206     (message-pop-to-buffer (message-buffer-name "mail" to))
3207     (message-setup
3208      (nconc
3209       `((To . ,(or to "")) (Subject . ,(or subject "")))
3210       (when other-headers other-headers)))))
3211
3212 ;;;###autoload
3213 (defun message-news (&optional newsgroups subject)
3214   "Start editing a news article to be sent."
3215   (interactive)
3216   (let ((message-this-is-news t))
3217     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3218     (message-setup `((Newsgroups . ,(or newsgroups ""))
3219                      (Subject . ,(or subject ""))))))
3220
3221 ;;;###autoload
3222 (defun message-reply (&optional to-address wide)
3223   "Start editing a reply to the article in the current buffer."
3224   (interactive)
3225   (let ((cur (current-buffer))
3226         from subject date reply-to to cc
3227         references message-id follow-to
3228         (inhibit-point-motion-hooks t)
3229         mct never-mct gnus-warning)
3230     (save-restriction
3231       (message-narrow-to-head)
3232       ;; Allow customizations to have their say.
3233       (if (not wide)
3234           ;; This is a regular reply.
3235           (if (message-functionp message-reply-to-function)
3236               (setq follow-to (funcall message-reply-to-function)))
3237         ;; This is a followup.
3238         (if (message-functionp message-wide-reply-to-function)
3239             (save-excursion
3240               (setq follow-to
3241                     (funcall message-wide-reply-to-function)))))
3242       ;; Find all relevant headers we need.
3243       (setq from (message-fetch-field "from")
3244             date (message-fetch-field "date")
3245             subject (or (message-fetch-field "subject") "none")
3246             to (message-fetch-field "to")
3247             cc (message-fetch-field "cc")
3248             mct (message-fetch-field "mail-copies-to")
3249             reply-to (message-fetch-field "reply-to")
3250             references (message-fetch-field "references")
3251             message-id (message-fetch-field "message-id" t))
3252       ;; Remove any (buggy) Re:'s that are present and make a
3253       ;; proper one.
3254       (when (string-match message-subject-re-regexp subject)
3255         (setq subject (substring subject (match-end 0))))
3256       (setq subject (concat "Re: " subject))
3257
3258       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3259                  (string-match "<[^>]+>" gnus-warning))
3260         (setq message-id (match-string 0 gnus-warning)))
3261
3262       ;; Handle special values of Mail-Copies-To.
3263       (when mct
3264         (cond ((equal (downcase mct) "never")
3265                (setq never-mct t)
3266                (setq mct nil))
3267               ((equal (downcase mct) "always")
3268                (setq mct (or reply-to from)))))
3269
3270       (unless follow-to
3271         (if (or (not wide)
3272                 to-address)
3273             (progn
3274               (setq follow-to (list (cons 'To (or to-address reply-to from))))
3275               (when (and wide mct)
3276                 (push (cons 'Cc mct) follow-to)))
3277           (let (ccalist)
3278             (save-excursion
3279               (message-set-work-buffer)
3280               (unless never-mct
3281                 (insert (or reply-to from "")))
3282               (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3283               (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3284               (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
3285               (goto-char (point-min))
3286               (while (re-search-forward "[ \t]+" nil t)
3287                 (replace-match " " t t))
3288               ;; Remove addresses that match `rmail-dont-reply-to-names'.
3289               (insert (prog1 (rmail-dont-reply-to (buffer-string))
3290                         (erase-buffer)))
3291               (goto-char (point-min))
3292               ;; Perhaps Mail-Copies-To: never removed the only address?
3293               (when (eobp)
3294                 (insert (or reply-to from "")))
3295               (setq ccalist
3296                     (mapcar
3297                      (lambda (addr)
3298                        (cons (mail-strip-quoted-names addr) addr))
3299                      (message-tokenize-header (buffer-string))))
3300               (let ((s ccalist))
3301                 (while s
3302                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3303             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3304             (when ccalist
3305               (let ((ccs (cons 'Cc (mapconcat
3306                                     (lambda (addr) (cdr addr)) ccalist ", "))))
3307                 (when (string-match "^ +" (cdr ccs))
3308                   (setcdr ccs (substring (cdr ccs) (match-end 0))))
3309                 (push ccs follow-to))))))
3310       (widen))
3311
3312     (message-pop-to-buffer (message-buffer-name
3313                             (if wide "wide reply" "reply") from
3314                             (if wide to-address nil)))
3315
3316     (setq message-reply-headers
3317           (vector 0 subject from date message-id references 0 0 ""))
3318
3319     (message-setup
3320      `((Subject . ,subject)
3321        ,@follow-to
3322        ,@(if (or references message-id)
3323              `((References . ,(concat (or references "") (and references " ")
3324                                       (or message-id ""))))
3325            nil))
3326      cur)))
3327
3328 ;;;###autoload
3329 (defun message-wide-reply (&optional to-address)
3330   "Make a \"wide\" reply to the message in the current buffer."
3331   (interactive)
3332   (message-reply to-address t))
3333
3334 ;;;###autoload
3335 (defun message-followup (&optional to-newsgroups)
3336   "Follow up to the message in the current buffer.
3337 If TO-NEWSGROUPS, use that as the new Newsgroups line."
3338   (interactive)
3339   (let ((cur (current-buffer))
3340         from subject date reply-to mct
3341         references message-id follow-to
3342         (inhibit-point-motion-hooks t)
3343         (message-this-is-news t)
3344         followup-to distribution newsgroups gnus-warning posted-to)
3345     (save-restriction
3346       (narrow-to-region
3347        (goto-char (point-min))
3348        (if (search-forward "\n\n" nil t)
3349            (1- (point))
3350          (point-max)))
3351       (when (message-functionp message-followup-to-function)
3352         (setq follow-to
3353               (funcall message-followup-to-function)))
3354       (setq from (message-fetch-field "from")
3355             date (message-fetch-field "date")
3356             subject (or (message-fetch-field "subject") "none")
3357             references (message-fetch-field "references")
3358             message-id (message-fetch-field "message-id" t)
3359             followup-to (message-fetch-field "followup-to")
3360             newsgroups (message-fetch-field "newsgroups")
3361             posted-to (message-fetch-field "posted-to")
3362             reply-to (message-fetch-field "reply-to")
3363             distribution (message-fetch-field "distribution")
3364             mct (message-fetch-field "mail-copies-to"))
3365       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3366                  (string-match "<[^>]+>" gnus-warning))
3367         (setq message-id (match-string 0 gnus-warning)))
3368       ;; Remove bogus distribution.
3369       (when (and (stringp distribution)
3370                  (let ((case-fold-search t))
3371                    (string-match "world" distribution)))
3372         (setq distribution nil))
3373       ;; Remove any (buggy) Re:'s that are present and make a
3374       ;; proper one.
3375       (when (string-match message-subject-re-regexp subject)
3376         (setq subject (substring subject (match-end 0))))
3377       (setq subject (concat "Re: " subject))
3378       (widen))
3379
3380     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3381
3382     (message-setup
3383      `((Subject . ,subject)
3384        ,@(cond
3385           (to-newsgroups
3386            (list (cons 'Newsgroups to-newsgroups)))
3387           (follow-to follow-to)
3388           ((and followup-to message-use-followup-to)
3389            (list
3390             (cond
3391              ((equal (downcase followup-to) "poster")
3392               (if (or (eq message-use-followup-to 'use)
3393                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
3394 You should normally obey the Followup-To: header.
3395
3396 `Followup-To: poster' sends your response via e-mail instead of news.
3397
3398 A typical situation where `Followup-To: poster' is used is when the poster
3399 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3400                   (progn
3401                     (setq message-this-is-news nil)
3402                     (cons 'To (or reply-to from "")))
3403                 (cons 'Newsgroups newsgroups)))
3404              (t
3405               (if (or (equal followup-to newsgroups)
3406                       (not (eq message-use-followup-to 'ask))
3407                       (message-y-or-n-p
3408                        (concat "Obey Followup-To: " followup-to "? ") t "\
3409 You should normally obey the Followup-To: header.
3410
3411         `Followup-To: " followup-to "'
3412 directs your response to " (if (string-match "," followup-to)
3413                                "the specified newsgroups"
3414                              "that newsgroup only") ".
3415
3416 If a message is posted to several newsgroups, Followup-To is often
3417 used to direct the following discussion to one newsgroup only,
3418 because discussions that are spread over several newsgroup tend to
3419 be fragmented and very difficult to follow.
3420
3421 Also, some source/announcement newsgroups are not indented for discussion;
3422 responses here are directed to other newsgroups."))
3423                   (cons 'Newsgroups followup-to)
3424                 (cons 'Newsgroups newsgroups))))))
3425           (posted-to
3426            `((Newsgroups . ,posted-to)))
3427           (t
3428            `((Newsgroups . ,newsgroups))))
3429        ,@(and distribution (list (cons 'Distribution distribution)))
3430        ,@(if (or references message-id)
3431              `((References . ,(concat (or references "") (and references " ")
3432                                       (or message-id "")))))
3433        ,@(when (and mct
3434                     (not (equal (downcase mct) "never")))
3435            (list (cons 'Cc (if (equal (downcase mct) "always")
3436                                (or reply-to from "")
3437                              mct)))))
3438
3439      cur)
3440
3441     (setq message-reply-headers
3442           (vector 0 subject from date message-id references 0 0 ""))))
3443
3444
3445 ;;;###autoload
3446 (defun message-cancel-news ()
3447   "Cancel an article you posted."
3448   (interactive)
3449   (unless (message-news-p)
3450     (error "This is not a news article; canceling is impossible"))
3451   (when (yes-or-no-p "Do you really want to cancel this article? ")
3452     (let (from newsgroups message-id distribution buf sender)
3453       (save-excursion
3454         ;; Get header info. from original article.
3455         (save-restriction
3456           (message-narrow-to-head)
3457           (setq from (message-fetch-field "from")
3458                 sender (message-fetch-field "sender")
3459                 newsgroups (message-fetch-field "newsgroups")
3460                 message-id (message-fetch-field "message-id" t)
3461                 distribution (message-fetch-field "distribution")))
3462         ;; Make sure that this article was written by the user.
3463         (unless (or (and sender
3464                          (string-equal
3465                           (downcase sender)
3466                           (downcase (message-make-sender))))
3467                     (string-equal
3468                      (downcase (cadr (mail-extract-address-components from)))
3469                      (downcase (cadr (mail-extract-address-components
3470                                       (message-make-from))))))
3471           (error "This article is not yours"))
3472         ;; Make control message.
3473         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
3474         (buffer-disable-undo (current-buffer))
3475         (erase-buffer)
3476         (insert "Newsgroups: " newsgroups "\n"
3477                 "From: " (message-make-from) "\n"
3478                 "Subject: cmsg cancel " message-id "\n"
3479                 "Control: cancel " message-id "\n"
3480                 (if distribution
3481                     (concat "Distribution: " distribution "\n")
3482                   "")
3483                 mail-header-separator "\n"
3484                 message-cancel-message)
3485         (message "Canceling your article...")
3486         (if (let ((message-syntax-checks
3487                    'dont-check-for-anything-just-trust-me))
3488               (funcall message-send-news-function))
3489             (message "Canceling your article...done"))
3490         (kill-buffer buf)))))
3491
3492 ;;;###autoload
3493 (defun message-supersede ()
3494   "Start composing a message to supersede the current message.
3495 This is done simply by taking the old article and adding a Supersedes
3496 header line with the old Message-ID."
3497   (interactive)
3498   (let ((cur (current-buffer)))
3499     ;; Check whether the user owns the article that is to be superseded.
3500     (unless (string-equal
3501              (downcase (or (message-fetch-field "sender")
3502                            (cadr (mail-extract-address-components
3503                                   (message-fetch-field "from")))))
3504              (downcase (message-make-sender)))
3505       (error "This article is not yours"))
3506     ;; Get a normal message buffer.
3507     (message-pop-to-buffer (message-buffer-name "supersede"))
3508     (insert-buffer-substring cur)
3509     (message-narrow-to-head)
3510     ;; Remove unwanted headers.
3511     (when message-ignored-supersedes-headers
3512       (message-remove-header message-ignored-supersedes-headers t))
3513     (goto-char (point-min))
3514     (if (not (re-search-forward "^Message-ID: " nil t))
3515         (error "No Message-ID in this article")
3516       (replace-match "Supersedes: " t t))
3517     (goto-char (point-max))
3518     (insert mail-header-separator)
3519     (widen)
3520     (forward-line 1)))
3521
3522 ;;;###autoload
3523 (defun message-recover ()
3524   "Reread contents of current buffer from its last auto-save file."
3525   (interactive)
3526   (let ((file-name (make-auto-save-file-name)))
3527     (cond ((save-window-excursion
3528              (if (not (eq system-type 'vax-vms))
3529                  (with-output-to-temp-buffer "*Directory*"
3530                    (buffer-disable-undo standard-output)
3531                    (let ((default-directory "/"))
3532                      (call-process
3533                       "ls" nil standard-output nil "-l" file-name))))
3534              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3535            (let ((buffer-read-only nil))
3536              (erase-buffer)
3537              (insert-file-contents file-name nil)))
3538           (t (error "message-recover cancelled")))))
3539
3540 ;;; Forwarding messages.
3541
3542 (defun message-make-forward-subject ()
3543   "Return a Subject header suitable for the message in the current buffer."
3544   (save-excursion
3545     (save-restriction
3546       (current-buffer)
3547       (message-narrow-to-head)
3548       (concat "[" (or (message-fetch-field
3549                        (if (message-news-p) "newsgroups" "from"))
3550                       "(nowhere)")
3551               "] " (or (message-fetch-field "Subject") "")))))
3552
3553 ;;;###autoload
3554 (defun message-forward (&optional news)
3555   "Forward the current message via mail.
3556 Optional NEWS will use news to forward instead of mail."
3557   (interactive "P")
3558   (let ((cur (current-buffer))
3559         (subject (message-make-forward-subject))
3560         art-beg)
3561     (if news (message-news nil subject) (message-mail nil subject))
3562     ;; Put point where we want it before inserting the forwarded
3563     ;; message.
3564     (if message-signature-before-forwarded-message
3565         (goto-char (point-max))
3566       (message-goto-body))
3567     ;; Make sure we're at the start of the line.
3568     (unless (eolp)
3569       (insert "\n"))
3570     ;; Narrow to the area we are to insert.
3571     (narrow-to-region (point) (point))
3572     ;; Insert the separators and the forwarded buffer.
3573     (insert message-forward-start-separator)
3574     (setq art-beg (point))
3575     (insert-buffer-substring cur)
3576     (goto-char (point-max))
3577     (insert message-forward-end-separator)
3578     (set-text-properties (point-min) (point-max) nil)
3579     ;; Remove all unwanted headers.
3580     (goto-char art-beg)
3581     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
3582                                   (1- (point))
3583                                 (point)))
3584     (goto-char (point-min))
3585     (message-remove-header message-included-forward-headers t nil t)
3586     (widen)
3587     (message-position-point)))
3588
3589 ;;;###autoload
3590 (defun message-resend (address)
3591   "Resend the current article to ADDRESS."
3592   (interactive "sResend message to: ")
3593   (message "Resending message to %s..." address)
3594   (save-excursion
3595     (let ((cur (current-buffer))
3596           beg)
3597       ;; We first set up a normal mail buffer.
3598       (set-buffer (get-buffer-create " *message resend*"))
3599       (buffer-disable-undo (current-buffer))
3600       (erase-buffer)
3601       (message-setup `((To . ,address)))
3602       ;; Insert our usual headers.
3603       (message-generate-headers '(From Date To))
3604       (message-narrow-to-headers)
3605       ;; Rename them all to "Resent-*".
3606       (while (re-search-forward "^[A-Za-z]" nil t)
3607         (forward-char -1)
3608         (insert "Resent-"))
3609       (widen)
3610       (forward-line)
3611       (delete-region (point) (point-max))
3612       (setq beg (point))
3613       ;; Insert the message to be resent.
3614       (insert-buffer-substring cur)
3615       (goto-char (point-min))
3616       (search-forward "\n\n")
3617       (forward-char -1)
3618       (save-restriction
3619         (narrow-to-region beg (point))
3620         (message-remove-header message-ignored-resent-headers t)
3621         (goto-char (point-max)))
3622       (insert mail-header-separator)
3623       ;; Rename all old ("Also-")Resent headers.
3624       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
3625         (beginning-of-line)
3626         (insert "Also-"))
3627       ;; Quote any "From " lines at the beginning.
3628       (goto-char beg)
3629       (when (looking-at "From ")
3630         (replace-match "X-From-Line: "))
3631       ;; Send it.
3632       (message-send-mail)
3633       (kill-buffer (current-buffer)))
3634     (message "Resending message to %s...done" address)))
3635
3636 ;;;###autoload
3637 (defun message-bounce ()
3638   "Re-mail the current message.
3639 This only makes sense if the current message is a bounce message than
3640 contains some mail you have written which has been bounced back to
3641 you."
3642   (interactive)
3643   (let ((cur (current-buffer))
3644         boundary)
3645     (message-pop-to-buffer (message-buffer-name "bounce"))
3646     (insert-buffer-substring cur)
3647     (undo-boundary)
3648     (message-narrow-to-head)
3649     (if (and (message-fetch-field "Mime-Version")
3650              (setq boundary (message-fetch-field "Content-Type")))
3651         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
3652             (setq boundary (concat (match-string 1 boundary) " *\n"
3653                                    "Content-Type: message/rfc822"))
3654           (setq boundary nil)))
3655     (widen)
3656     (goto-char (point-min))
3657     (search-forward "\n\n" nil t)
3658     (or (and boundary
3659              (re-search-forward boundary nil t)
3660              (forward-line 2))
3661         (and (re-search-forward message-unsent-separator nil t)
3662              (forward-line 1))
3663         (re-search-forward "^Return-Path:.*\n" nil t))
3664     ;; We remove everything before the bounced mail.
3665     (delete-region
3666      (point-min)
3667      (if (re-search-forward "^[^ \n\t]+:" nil t)
3668          (match-beginning 0)
3669        (point)))
3670     (save-restriction
3671       (message-narrow-to-head)
3672       (message-remove-header message-ignored-bounced-headers t)
3673       (goto-char (point-max))
3674       (insert mail-header-separator))
3675     (message-position-point)))
3676
3677 ;;;
3678 ;;; Interactive entry points for new message buffers.
3679 ;;;
3680
3681 ;;;###autoload
3682 (defun message-mail-other-window (&optional to subject)
3683   "Like `message-mail' command, but display mail buffer in another window."
3684   (interactive)
3685   (let ((pop-up-windows t)
3686         (special-display-buffer-names nil)
3687         (special-display-regexps nil)
3688         (same-window-buffer-names nil)
3689         (same-window-regexps nil))
3690     (message-pop-to-buffer (message-buffer-name "mail" to)))
3691   (let ((message-this-is-mail t))
3692     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
3693
3694 ;;;###autoload
3695 (defun message-mail-other-frame (&optional to subject)
3696   "Like `message-mail' command, but display mail buffer in another frame."
3697   (interactive)
3698   (let ((pop-up-frames t)
3699         (special-display-buffer-names nil)
3700         (special-display-regexps nil)
3701         (same-window-buffer-names nil)
3702         (same-window-regexps nil))
3703     (message-pop-to-buffer (message-buffer-name "mail" to)))
3704   (let ((message-this-is-mail t))
3705     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
3706
3707 ;;;###autoload
3708 (defun message-news-other-window (&optional newsgroups subject)
3709   "Start editing a news article to be sent."
3710   (interactive)
3711   (let ((pop-up-windows t)
3712         (special-display-buffer-names nil)
3713         (special-display-regexps nil)
3714         (same-window-buffer-names nil)
3715         (same-window-regexps nil))
3716     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3717   (let ((message-this-is-news t))
3718     (message-setup `((Newsgroups . ,(or newsgroups ""))
3719                      (Subject . ,(or subject ""))))))
3720
3721 ;;;###autoload
3722 (defun message-news-other-frame (&optional newsgroups subject)
3723   "Start editing a news article to be sent."
3724   (interactive)
3725   (let ((pop-up-frames t)
3726         (special-display-buffer-names nil)
3727         (special-display-regexps nil)
3728         (same-window-buffer-names nil)
3729         (same-window-regexps nil))
3730     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3731   (let ((message-this-is-news t))
3732     (message-setup `((Newsgroups . ,(or newsgroups ""))
3733                      (Subject . ,(or subject ""))))))
3734
3735 ;;; underline.el
3736
3737 ;; This code should be moved to underline.el (from which it is stolen).
3738
3739 ;;;###autoload
3740 (defun bold-region (start end)
3741   "Bold all nonblank characters in the region.
3742 Works by overstriking characters.
3743 Called from program, takes two arguments START and END
3744 which specify the range to operate on."
3745   (interactive "r")
3746   (save-excursion
3747     (let ((end1 (make-marker)))
3748       (move-marker end1 (max start end))
3749       (goto-char (min start end))
3750       (while (< (point) end1)
3751         (or (looking-at "[_\^@- ]")
3752             (insert (following-char) "\b"))
3753         (forward-char 1)))))
3754
3755 ;;;###autoload
3756 (defun unbold-region (start end)
3757   "Remove all boldness (overstruck characters) in the region.
3758 Called from program, takes two arguments START and END
3759 which specify the range to operate on."
3760   (interactive "r")
3761   (save-excursion
3762     (let ((end1 (make-marker)))
3763       (move-marker end1 (max start end))
3764       (goto-char (min start end))
3765       (while (re-search-forward "\b" end1 t)
3766         (if (eq (following-char) (char-after (- (point) 2)))
3767             (delete-char -2))))))
3768
3769 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
3770
3771 ;; Support for toolbar
3772 (when (string-match "XEmacs\\|Lucid" emacs-version)
3773   (require 'messagexmas))
3774
3775 ;;; Group name completion.
3776
3777 (defvar message-newgroups-header-regexp
3778   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
3779   "Regexp that match headers that lists groups.")
3780
3781 (defun message-tab ()
3782   "Expand group names in Newsgroups and Followup-To headers.
3783 Do a `tab-to-tab-stop' if not in those headers."
3784   (interactive)
3785   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
3786         (mail-abbrev-in-expansion-header-p))
3787       (message-expand-group)
3788     (tab-to-tab-stop)))
3789
3790 (defvar gnus-active-hashtb)
3791 (defun message-expand-group ()
3792   "Expand the group name under point."
3793   (let* ((b (save-excursion
3794               (save-restriction
3795                 (narrow-to-region
3796                  (save-excursion
3797                    (beginning-of-line)
3798                    (skip-chars-forward "^:")
3799                    (1+ (point)))
3800                  (point))
3801                 (skip-chars-backward "^, \t\n") (point))))
3802          (completion-ignore-case t)
3803          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
3804                                             (point))))
3805          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
3806          (completions (all-completions string hashtb))
3807          (cur (current-buffer))
3808          comp)
3809     (delete-region b (point))
3810     (cond
3811      ((= (length completions) 1)
3812       (if (string= (car completions) string)
3813           (progn
3814             (insert string)
3815             (message "Only matching group"))
3816         (insert (car completions))))
3817      ((and (setq comp (try-completion string hashtb))
3818            (not (string= comp string)))
3819       (insert comp))
3820      (t
3821       (insert string)
3822       (if (not comp)
3823           (message "No matching groups")
3824         (save-selected-window
3825           (pop-to-buffer "*Completions*")
3826           (buffer-disable-undo (current-buffer))
3827           (let ((buffer-read-only nil))
3828             (erase-buffer)
3829             (let ((standard-output (current-buffer)))
3830               (display-completion-list (sort completions 'string<)))
3831             (goto-char (point-min))
3832             (delete-region (point) (progn (forward-line 3) (point))))))))))
3833
3834 ;;; Help stuff.
3835
3836 (defun message-talkative-question (ask question show &rest text)
3837   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
3838 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
3839 The following arguments may contain lists of values."
3840   (if (and show
3841            (setq text (message-flatten-list text)))
3842       (save-window-excursion
3843         (save-excursion
3844           (with-output-to-temp-buffer " *MESSAGE information message*"
3845             (set-buffer " *MESSAGE information message*")
3846             (mapcar 'princ text)
3847             (goto-char (point-min))))
3848         (funcall ask question))
3849     (funcall ask question)))
3850
3851 (defun message-flatten-list (list)
3852   "Return a new, flat list that contains all elements of LIST.
3853
3854 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
3855 => (1 2 3 4 5 6 7)"
3856   (cond ((consp list)
3857          (apply 'append (mapcar 'message-flatten-list list)))
3858         (list
3859          (list list))))
3860
3861 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
3862   "Create and return a buffer with a name based on NAME using generate-new-buffer.
3863 Then clone the local variables and values from the old buffer to the
3864 new one, cloning only the locals having a substring matching the
3865 regexp varstr."
3866   (let ((oldbuf (current-buffer)))
3867     (save-excursion
3868       (set-buffer (generate-new-buffer name))
3869       (message-clone-locals oldbuf)
3870       (current-buffer))))
3871
3872 (defun message-clone-locals (buffer)
3873   "Clone the local variables from BUFFER to the current buffer."
3874   (let ((locals (save-excursion
3875                   (set-buffer buffer)
3876                   (buffer-local-variables)))
3877         (regexp "^gnus\\|^nn\\|^message"))
3878     (mapcar
3879      (lambda (local)
3880        (when (and (consp local)
3881                   (car local)
3882                   (string-match regexp (symbol-name (car local))))
3883          (ignore-errors
3884            (set (make-local-variable (car local))
3885                 (cdr local)))))
3886      locals)))
3887
3888 ;;; Miscellaneous functions
3889
3890 ;; stolen (and renamed) from nnheader.el
3891 (defun message-replace-chars-in-string (string from to)
3892   "Replace characters in STRING from FROM to TO."
3893   (let ((string (substring string 0))   ;Copy string.
3894         (len (length string))
3895         (idx 0))
3896     ;; Replace all occurrences of FROM with TO.
3897     (while (< idx len)
3898       (when (= (aref string idx) from)
3899         (aset string idx to))
3900       (setq idx (1+ idx)))
3901     string))
3902
3903 (run-hooks 'message-load-hook)
3904
3905 (provide 'message)
3906
3907 ;;; message.el ends here