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