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