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