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