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