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