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