0eea71c41bfd063d654b48b17b834c3fbd989a15
[gnus] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: mail, news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; This mode provides mail-sending facilities from within Emacs.  It
28 ;; consists mainly of large chunks of code from the sendmail.el,
29 ;; gnus-msg.el and rnewspost.el files.
30
31 ;;; Code:
32
33 (eval-when-compile
34   (require 'cl)
35   (defvar gnus-list-identifiers)) ; gnus-sum is required where necessary
36 (require 'canlock)
37 (require 'mailheader)
38 (require 'nnheader)
39 ;; This is apparently necessary even though things are autoloaded.
40 ;; Because we dynamically bind mail-abbrev-mode-regexp, we'd better
41 ;; require mailabbrev here.
42 (if (featurep 'xemacs)
43     (require 'mail-abbrevs)
44   (require 'mailabbrev))
45 (require 'mail-parse)
46 (require 'mml)
47 (require 'rfc822)
48 (eval-and-compile
49   (autoload 'sha1 "sha1-el"))
50
51 (defgroup message '((user-mail-address custom-variable)
52                     (user-full-name custom-variable))
53   "Mail and news message composing."
54   :link '(custom-manual "(message)Top")
55   :group 'mail
56   :group 'news)
57
58 (put 'user-mail-address 'custom-type 'string)
59 (put 'user-full-name 'custom-type 'string)
60
61 (defgroup message-various nil
62   "Various Message Variables"
63   :link '(custom-manual "(message)Various Message Variables")
64   :group 'message)
65
66 (defgroup message-buffers nil
67   "Message Buffers"
68   :link '(custom-manual "(message)Message Buffers")
69   :group 'message)
70
71 (defgroup message-sending nil
72   "Message Sending"
73   :link '(custom-manual "(message)Sending Variables")
74   :group 'message)
75
76 (defgroup message-interface nil
77   "Message Interface"
78   :link '(custom-manual "(message)Interface")
79   :group 'message)
80
81 (defgroup message-forwarding nil
82   "Message Forwarding"
83   :link '(custom-manual "(message)Forwarding")
84   :group 'message-interface)
85
86 (defgroup message-insertion nil
87   "Message Insertion"
88   :link '(custom-manual "(message)Insertion")
89   :group 'message)
90
91 (defgroup message-headers nil
92   "Message Headers"
93   :link '(custom-manual "(message)Message Headers")
94   :group 'message)
95
96 (defgroup message-news nil
97   "Composing News Messages"
98   :group 'message)
99
100 (defgroup message-mail nil
101   "Composing Mail Messages"
102   :group 'message)
103
104 (defgroup message-faces nil
105   "Faces used for message composing."
106   :group 'message
107   :group 'faces)
108
109 (defcustom message-directory "~/Mail/"
110   "*Directory from which all other mail file variables are derived."
111   :group 'message-various
112   :type 'directory)
113
114 (defcustom message-max-buffers 10
115   "*How many buffers to keep before starting to kill them off."
116   :group 'message-buffers
117   :type 'integer)
118
119 (defcustom message-send-rename-function nil
120   "Function called to rename the buffer after sending it."
121   :group 'message-buffers
122   :type '(choice function (const nil)))
123
124 (defcustom message-fcc-handler-function 'message-output
125   "*A function called to save outgoing articles.
126 This function will be called with the name of the file to store the
127 article in.  The default function is `message-output' which saves in Unix
128 mailbox format."
129   :type '(radio (function-item message-output)
130                 (function :tag "Other"))
131   :group 'message-sending)
132
133 (defcustom message-fcc-externalize-attachments nil
134   "If non-nil, attachments are included as external parts in Fcc copies."
135   :type 'boolean
136   :group 'message-sending)
137
138 (defcustom message-courtesy-message
139   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
140   "*This is inserted at the start of a mailed copy of a posted message.
141 If the string contains the format spec \"%s\", the Newsgroups
142 the article has been posted to will be inserted there.
143 If this variable is nil, no such courtesy message will be added."
144   :group 'message-sending
145   :type 'string)
146
147 (defcustom message-ignored-bounced-headers "^\\(Received\\|Return-Path\\):"
148   "*Regexp that matches headers to be removed in resent bounced mail."
149   :group 'message-interface
150   :type 'regexp)
151
152 ;;;###autoload
153 (defcustom message-from-style 'default
154   "*Specifies how \"From\" headers look.
155
156 If nil, they contain just the return address like:
157         king@grassland.com
158 If `parens', they look like:
159         king@grassland.com (Elvis Parsley)
160 If `angles', they look like:
161         Elvis Parsley <king@grassland.com>
162
163 Otherwise, most addresses look like `angles', but they look like
164 `parens' if `angles' would need quoting and `parens' would not."
165   :type '(choice (const :tag "simple" nil)
166                  (const parens)
167                  (const angles)
168                  (const default))
169   :group 'message-headers)
170
171 (defcustom message-insert-canlock t
172   "Whether to insert a Cancel-Lock header in news postings."
173   :version "21.3"
174   :group 'message-headers
175   :type 'boolean)
176
177 (defcustom message-syntax-checks 
178   (if message-insert-canlock '((sender . disabled)) nil)
179   ;; Guess this one shouldn't be easy to customize...
180   "*Controls what syntax checks should not be performed on outgoing posts.
181 To disable checking of long signatures, for instance, add
182  `(signature . disabled)' to this list.
183
184 Don't touch this variable unless you really know what you're doing.
185
186 Checks include `subject-cmsg', `multiple-headers', `sendsys',
187 `message-id', `from', `long-lines', `control-chars', `size',
188 `new-text', `quoting-style', `redirected-followup', `signature',
189 `approved', `sender', `empty', `empty-headers', `message-id', `from',
190 `subject', `shorten-followup-to', `existing-newsgroups',
191 `buffer-file-name', `unchanged', `newsgroups', `reply-to'."
192   :group 'message-news
193   :type '(repeat sexp))                 ; Fixme: improve this
194
195 (defcustom message-required-headers '((optional . References))
196   "*Headers to be generated or promted for when sending a message.
197 Also see `message-required-news-headers' and
198 1message-required-mail-headers'."
199   :group 'message-news
200   :group 'message-headers
201   :type '(repeat sexp))
202
203 (defcustom message-required-news-headers
204   '(From Newsgroups Subject Date Message-ID
205          (optional . Organization)
206          (optional . User-Agent))
207   "*Headers to be generated or prompted for when posting an article.
208 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
209 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
210 User-Agent are optional.  If don't you want message to insert some
211 header, remove it from this list."
212   :group 'message-news
213   :group 'message-headers
214   :type '(repeat sexp))
215
216 (defcustom message-required-mail-headers
217   '(From Subject Date (optional . In-Reply-To) Message-ID
218          (optional . User-Agent))
219   "*Headers to be generated or prompted for when mailing a message.
220 It is recommended that From, Date, To, Subject and Message-ID be
221 included.  Organization and User-Agent are optional."
222   :group 'message-mail
223   :group 'message-headers
224   :type '(repeat sexp))
225
226 (defcustom message-deletable-headers '(Message-ID Date Lines)
227   "Headers to be deleted if they already exist and were generated by message previously."
228   :group 'message-headers
229   :type 'sexp)
230
231 (defcustom message-ignored-news-headers
232   "^NNTP-Posting-Host:\\|^Xref:\\|^[BGF]cc:\\|^Resent-Fcc:\\|^X-Draft-From:\\|^X-Gnus-Agent-Meta-Information:"
233   "*Regexp of headers to be removed unconditionally before posting."
234   :group 'message-news
235   :group 'message-headers
236   :type 'regexp)
237
238 (defcustom message-ignored-mail-headers
239   "^[GF]cc:\\|^Resent-Fcc:\\|^Xref:\\|^X-Draft-From:\\|^X-Gnus-Agent-Meta-Information:"
240   "*Regexp of headers to be removed unconditionally before mailing."
241   :group 'message-mail
242   :group 'message-headers
243   :type 'regexp)
244
245 (defcustom message-ignored-supersedes-headers "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|^X-Trace:\\|^X-Complaints-To:\\|Return-Path:\\|^Supersedes:\\|^NNTP-Posting-Date:\\|^X-Trace:\\|^X-Complaints-To:\\|^Cancel-Lock:\\|^Cancel-Key:\\|^X-Hashcash:"
246   "*Header lines matching this regexp will be deleted before posting.
247 It's best to delete old Path and Date headers before posting to avoid
248 any confusion."
249   :group 'message-interface
250   :type 'regexp)
251
252 (defcustom message-subject-re-regexp
253   "^[ \t]*\\([Rr][Ee]\\(\\[[0-9]*\\]\\)*:[ \t]*\\)*[ \t]*"
254   "*Regexp matching \"Re: \" in the subject line."
255   :group 'message-various
256   :type 'regexp)
257
258 ;;; Start of variables adopted from `message-utils.el'.
259
260 (defcustom message-subject-trailing-was-query 'ask
261   ;; should it default to nil or ask?
262   "*What to do with trailing \"(was: <old subject>)\" in subject lines.
263 If nil, leave the subject unchanged.  If it is the symbol `ask', query
264 the user what do do.  In this case, the subject is matched against
265 `message-subject-trailing-was-ask-regexp'.  If
266 `message-subject-trailing-was-query' is t, always strip the trailing
267 old subject.  In this case, `message-subject-trailing-was-regexp' is
268 used."
269   :type '(choice (const :tag "never" nil)
270                  (const :tag "always strip" t)
271                  (const ask))
272   :group 'message-various)
273
274 (defcustom message-subject-trailing-was-ask-regexp
275   "[ \t]*\\([[(]+[Ww][Aa][Ss][ \t]*.*[\])]+\\)"
276   "*Regexp matching \"(was: <old subject>)\" in the subject line.
277
278 The function `message-strip-subject-trailing-was' uses this regexp if
279 `message-subject-trailing-was-query' is set to the symbol `ask'.  If
280 the variable is t instead of `ask', use
281 `message-subject-trailing-was-regexp' instead.
282
283 It is okay to create some false positives here, as the user is asked."
284   :group 'message-various
285   :type 'regexp)
286
287 (defcustom message-subject-trailing-was-regexp
288   "[ \t]*\\((*[Ww][Aa][Ss]:[ \t]*.*)\\)"
289   "*Regexp matching \"(was: <old subject>)\" in the subject line.
290
291 If `message-subject-trailing-was-query' is set to t, the subject is
292 matched against `message-subject-trailing-was-regexp' in
293 `message-strip-subject-trailing-was'.  You should use a regexp creating very
294 few false positives here."
295   :group 'message-various
296   :type 'regexp)
297
298 ;;; marking inserted text
299
300 ;;;###autoload
301 (defcustom message-mark-insert-begin
302   "--8<---------------cut here---------------start------------->8---\n"
303   "How to mark the beginning of some inserted text."
304   :type 'string
305   :group 'message-various)
306
307 ;;;###autoload
308 (defcustom message-mark-insert-end
309   "--8<---------------cut here---------------end--------------->8---\n"
310   "How to mark the end of some inserted text."
311   :type 'string
312   :group 'message-various)
313
314 ;;;###autoload
315 (defcustom message-archive-header
316   "X-No-Archive: Yes\n"
317   "Header to insert when you don't want your article to be archived.
318 Archives \(such as groups.googgle.com\) respect this header."
319   :type 'string
320   :group 'message-various)
321
322 ;;;###autoload
323 (defcustom message-archive-note
324   "X-No-Archive: Yes - save http://groups.google.com/"
325   "Note to insert why you wouldn't want this posting archived. 
326 If nil, don't insert any text in the body."
327   :type 'string
328   :group 'message-various)
329
330 ;;; Crossposts and Followups
331 ;; inspired by JoH-followup-to by Jochem Huhman <joh  at gmx.de>
332 ;; new suggestions by R. Weikusat <rw at another.de>
333
334 (defvar message-xpost-old-target nil
335   "Old target for cross-posts or follow-ups.")
336 (make-variable-buffer-local 'message-xpost-old-target)
337
338 ;;;###autoload
339 (defcustom message-xpost-default t
340   "When non-nil `message-xpost-fup2' will normally perform a crosspost.
341 If nil, `message-xpost-fup2' will only do a followup.  Note that you
342 can explicitly override this setting by calling `message-xpost-fup2'
343 with a prefix."
344   :type 'boolean
345   :group 'message-various)
346
347 ;;;###autoload
348 (defcustom message-xpost-note
349   "Crosspost & Followup-To: "
350   "Note to insert before signature to notify of xpost and follow-up."
351   :type 'string
352   :group 'message-various)
353
354 ;;;###autoload
355 (defcustom message-fup2-note
356   "Followup-To: "
357   "Note to insert before signature to notify of follow-up only."
358   :type 'string
359   :group 'message-various)
360
361 ;;;###autoload
362 (defcustom message-xpost-note-function
363   'message-xpost-insert-note
364   "Function to use to insert note about Crosspost or Followup-To.  
365 The function will be called with four arguments.  The function should not only
366 insert a note, but also ensure old notes are deleted.  See the documentation
367 for `message-xpost-insert-note'. "
368   :type 'function
369   :group 'message-various)
370
371 ;;; End of variables adopted from `message-utils.el'.
372
373 ;;;###autoload
374 (defcustom message-signature-separator "^-- *$"
375   "Regexp matching the signature separator."
376   :type 'regexp
377   :group 'message-various)
378
379 (defcustom message-elide-ellipsis "\n[...]\n\n"
380   "*The string which is inserted for elided text."
381   :type 'string
382   :group 'message-various)
383
384 (defcustom message-interactive t
385   "Non-nil means when sending a message wait for and display errors.
386 nil means let mailer mail back a message to report errors."
387   :group 'message-sending
388   :group 'message-mail
389   :type 'boolean)
390
391 (defcustom message-generate-new-buffers 'unique
392   "*Non-nil means create a new message buffer whenever `message-setup' is called.
393 If this is a function, call that function with three parameters:  The type,
394 the to address and the group name.  (Any of these may be nil.)  The function
395 should return the new buffer name."
396   :group 'message-buffers
397   :type '(choice (const :tag "off" nil)
398                  (const :tag "unique" unique)
399                  (const :tag "unsent" unsent)
400                  (function fun)))
401
402 (defcustom message-kill-buffer-on-exit nil
403   "*Non-nil means that the message buffer will be killed after sending a message."
404   :group 'message-buffers
405   :type 'boolean)
406
407 (eval-when-compile
408   (defvar gnus-local-organization))
409 (defcustom message-user-organization
410   (or (and (boundp 'gnus-local-organization)
411            (stringp gnus-local-organization)
412            gnus-local-organization)
413       (getenv "ORGANIZATION")
414       t)
415   "*String to be used as an Organization header.
416 If t, use `message-user-organization-file'."
417   :group 'message-headers
418   :type '(choice string
419                  (const :tag "consult file" t)))
420
421 ;;;###autoload
422 (defcustom message-user-organization-file "/usr/lib/news/organization"
423   "*Local news organization file."
424   :type 'file
425   :group 'message-headers)
426
427 (defcustom message-make-forward-subject-function
428   'message-forward-subject-author-subject
429   "*List of functions called to generate subject headers for forwarded messages.
430 The subject generated by the previous function is passed into each
431 successive function.
432
433 The provided functions are:
434
435 * `message-forward-subject-author-subject' (Source of article (author or
436       newsgroup)), in brackets followed by the subject
437 * `message-forward-subject-fwd' (Subject of article with 'Fwd:' prepended
438       to it."
439   :group 'message-forwarding
440   :type '(radio (function-item message-forward-subject-author-subject)
441                 (function-item message-forward-subject-fwd)
442                 (repeat :tag "List of functions" function)))
443
444 (defcustom message-forward-as-mime t
445   "*If non-nil, forward messages as an inline/rfc822 MIME section.  Otherwise, directly inline the old message in the forwarded message."
446   :version "21.1"
447   :group 'message-forwarding
448   :type 'boolean)
449
450 (defcustom message-forward-show-mml t
451   "*If non-nil, forward messages are shown as mml.  Otherwise, forward messages are unchanged."
452   :version "21.1"
453   :group 'message-forwarding
454   :type 'boolean)
455
456 (defcustom message-forward-before-signature t
457   "*If non-nil, put forwarded message before signature, else after."
458   :group 'message-forwarding
459   :type 'boolean)
460
461 (defcustom message-wash-forwarded-subjects nil
462   "*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."
463   :group 'message-forwarding
464   :type 'boolean)
465
466 (defcustom message-ignored-resent-headers "^Return-receipt\\|^X-Gnus\\|^Gnus-Warning:\\|^>?From "
467   "*All headers that match this regexp will be deleted when resending a message."
468   :group 'message-interface
469   :type 'regexp)
470
471 (defcustom message-forward-ignored-headers "^Content-Transfer-Encoding:\\|^X-Gnus"
472   "*All headers that match this regexp will be deleted when forwarding a message."
473   :version "21.1"
474   :group 'message-forwarding
475   :type '(choice (const :tag "None" nil)
476                  regexp))
477
478 (defcustom message-ignored-cited-headers "."
479   "*Delete these headers from the messages you yank."
480   :group 'message-insertion
481   :type 'regexp)
482
483 (defcustom message-cite-prefix-regexp
484   (if (string-match "[[:digit:]]" "1") ;; support POSIX?
485       "\\([ \t]*[-_.[:word:]]+>+\\|[ \t]*[]>|}+]\\)+"
486     ;; ?-, ?_ or ?. MUST NOT be in syntax entry w.
487     (let ((old-table (syntax-table))
488           non-word-constituents)
489       (set-syntax-table text-mode-syntax-table)
490       (setq non-word-constituents
491             (concat
492              (if (string-match "\\w" "-")  "" "-")
493              (if (string-match "\\w" "_")  "" "_")
494              (if (string-match "\\w" ".")  "" ".")))
495       (set-syntax-table old-table)
496       (if (equal non-word-constituents "")
497           "\\([ \t]*\\(\\w\\)+>+\\|[ \t]*[]>|}+]\\)+"
498         (concat "\\([ \t]*\\(\\w\\|["
499                 non-word-constituents
500                 "]\\)+>+\\|[ \t]*[]>|}+]\\)+"))))
501   "*Regexp matching the longest possible citation prefix on a line."
502   :group 'message-insertion
503   :type 'regexp)
504
505 (defcustom message-cancel-message "I am canceling my own article.\n"
506   "Message to be inserted in the cancel message."
507   :group 'message-interface
508   :type 'string)
509
510 ;; Useful to set in site-init.el
511 ;;;###autoload
512 (defcustom message-send-mail-function 'message-send-mail-with-sendmail
513   "Function to call to send the current buffer as mail.
514 The headers should be delimited by a line whose contents match the
515 variable `mail-header-separator'.
516
517 Valid values include `message-send-mail-with-sendmail' (the default),
518 `message-send-mail-with-mh', `message-send-mail-with-qmail',
519 `message-smtpmail-send-it', `smtpmail-send-it' and `feedmail-send-it'.
520
521 See also `send-mail-function'."
522   :type '(radio (function-item message-send-mail-with-sendmail)
523                 (function-item message-send-mail-with-mh)
524                 (function-item message-send-mail-with-qmail)
525                 (function-item message-smtpmail-send-it)
526                 (function-item smtpmail-send-it)
527                 (function-item feedmail-send-it)
528                 (function :tag "Other"))
529   :group 'message-sending
530   :group 'message-mail)
531
532 (defcustom message-send-news-function 'message-send-news
533   "Function to call to send the current buffer as news.
534 The headers should be delimited by a line whose contents match the
535 variable `mail-header-separator'."
536   :group 'message-sending
537   :group 'message-news
538   :type 'function)
539
540 (defcustom message-reply-to-function nil
541   "If non-nil, function that should return a list of headers.
542 This function should pick out addresses from the To, Cc, and From headers
543 and respond with new To and Cc headers."
544   :group 'message-interface
545   :type '(choice function (const nil)))
546
547 (defcustom message-wide-reply-to-function nil
548   "If non-nil, function that should return a list of headers.
549 This function should pick out addresses from the To, Cc, and From headers
550 and respond with new To and Cc headers."
551   :group 'message-interface
552   :type '(choice function (const nil)))
553
554 (defcustom message-followup-to-function nil
555   "If non-nil, function that should return a list of headers.
556 This function should pick out addresses from the To, Cc, and From headers
557 and respond with new To and Cc headers."
558   :group 'message-interface
559   :type '(choice function (const nil)))
560
561 (defcustom message-use-followup-to 'ask
562   "*Specifies what to do with Followup-To header.
563 If nil, always ignore the header.  If it is t, use its value, but
564 query before using the \"poster\" value.  If it is the symbol `ask',
565 always query the user whether to use the value.  If it is the symbol
566 `use', always use the value."
567   :group 'message-interface
568   :type '(choice (const :tag "ignore" nil)
569                  (const :tag "use & query" t)
570                  (const use)
571                  (const ask)))
572
573 (defcustom message-use-mail-followup-to 'use
574   "*Specifies what to do with Mail-Followup-To header.
575 If nil, always ignore the header.  If it is the symbol `ask', always
576 query the user whether to use the value.  If it is the symbol `use',
577 always use the value."
578   :group 'message-interface
579   :type '(choice (const :tag "ignore" nil)
580                  (const use)
581                  (const ask)))
582
583 (defcustom message-subscribed-address-functions nil
584   "*Specifies functions for determining list subscription.
585 If nil, do not attempt to determine list subscribtion with functions.
586 If non-nil, this variable contains a list of functions which return
587 regular expressions to match lists.  These functions can be used in
588 conjunction with `message-subscribed-regexps' and
589 `message-subscribed-addresses'."
590   :group 'message-interface
591   :type '(repeat sexp))
592
593 (defcustom message-subscribed-address-file nil
594   "*A file containing addresses the user is subscribed to.
595 If nil, do not look at any files to determine list subscriptions.  If
596 non-nil, each line of this file should be a mailing list address."
597   :group 'message-interface
598   :type 'string)
599
600 (defcustom message-subscribed-addresses nil
601   "*Specifies a list of addresses the user is subscribed to.
602 If nil, do not use any predefined list subscriptions.  This list of
603 addresses can be used in conjuction with
604 `message-subscribed-address-functions' and `message-subscribed-regexps'."
605   :group 'message-interface
606   :type '(repeat string))
607
608 (defcustom message-subscribed-regexps nil
609   "*Specifies a list of addresses the user is subscribed to.
610 If nil, do not use any predefined list subscriptions.  This list of
611 regular expressions can be used in conjuction with
612 `message-subscribed-address-functions' and `message-subscribed-addresses'."
613   :group 'message-interface
614   :type '(repeat regexp))
615
616 (defcustom message-allow-no-recipients 'ask
617   "Specifies what to do when there are no recipients other than Gcc/Fcc.
618 If it is the symbol `always', the posting is allowed.  If it is the
619 symbol `never', the posting is not allowed.  If it is the symbol
620 `ask', you are prompted."
621   :group 'message-interface
622   :type '(choice (const always)
623                  (const never)
624                  (const ask)))
625
626 (defcustom message-sendmail-f-is-evil nil
627   "*Non-nil means don't add \"-f username\" to the sendmail command line.
628 Doing so would be even more evil than leaving it out."
629   :group 'message-sending
630   :type 'boolean)
631
632 ;; qmail-related stuff
633 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
634   "Location of the qmail-inject program."
635   :group 'message-sending
636   :type 'file)
637
638 (defcustom message-qmail-inject-args nil
639   "Arguments passed to qmail-inject programs.
640 This should be a list of strings, one string for each argument.  It
641 may also be a function.
642
643 For e.g., if you wish to set the envelope sender address so that bounces
644 go to the right place or to deal with listserv's usage of that address, you
645 might set this variable to '(\"-f\" \"you@some.where\")."
646   :group 'message-sending
647   :type '(choice (function)
648                  (repeat string)))
649
650 (defvar message-cater-to-broken-inn t
651   "Non-nil means Gnus should not fold the `References' header.
652 Folding `References' makes ancient versions of INN create incorrect
653 NOV lines.")
654
655 (eval-when-compile
656   (defvar gnus-post-method)
657   (defvar gnus-select-method))
658 (defcustom message-post-method
659   (cond ((and (boundp 'gnus-post-method)
660               (listp gnus-post-method)
661               gnus-post-method)
662          gnus-post-method)
663         ((boundp 'gnus-select-method)
664          gnus-select-method)
665         (t '(nnspool "")))
666   "*Method used to post news.
667 Note that when posting from inside Gnus, for instance, this
668 variable isn't used."
669   :group 'message-news
670   :group 'message-sending
671   ;; This should be the `gnus-select-method' widget, but that might
672   ;; create a dependence to `gnus.el'.
673   :type 'sexp)
674
675 (defcustom message-generate-headers-first nil
676   "*If non-nil, generate all required headers before composing.
677 The variables `message-required-news-headers' and
678 `message-required-mail-headers' specify which headers to generate.
679
680 Note that the variable `message-deletable-headers' specifies headers which
681 are to be deleted and then re-generated before sending, so this variable
682 will not have a visible effect for those headers."
683   :group 'message-headers
684   :type 'boolean)
685
686 (defcustom message-setup-hook nil
687   "Normal hook, run each time a new outgoing message is initialized.
688 The function `message-setup' runs this hook."
689   :group 'message-various
690   :type 'hook)
691
692 (defcustom message-cancel-hook nil
693   "Hook run when cancelling articles."
694   :group 'message-various
695   :type 'hook)
696
697 (defcustom message-signature-setup-hook nil
698   "Normal hook, run each time a new outgoing message is initialized.
699 It is run after the headers have been inserted and before
700 the signature is inserted."
701   :group 'message-various
702   :type 'hook)
703
704 (defcustom message-mode-hook nil
705   "Hook run in message mode buffers."
706   :group 'message-various
707   :type 'hook)
708
709 (defcustom message-header-hook nil
710   "Hook run in a message mode buffer narrowed to the headers."
711   :group 'message-various
712   :type 'hook)
713
714 (defcustom message-header-setup-hook nil
715   "Hook called narrowed to the headers when setting up a message buffer."
716   :group 'message-various
717   :type 'hook)
718
719 (defcustom message-minibuffer-local-map
720   (let ((map (make-sparse-keymap 'message-minibuffer-local-map)))
721     (set-keymap-parent map minibuffer-local-map)
722     map)
723   "Keymap for `message-read-from-minibuffer'.")
724
725 ;;;###autoload
726 (defcustom message-citation-line-function 'message-insert-citation-line
727   "*Function called to insert the \"Whomever writes:\" line.
728
729 Note that Gnus provides a feature where the reader can click on
730 `writes:' to hide the cited text.  If you change this line too much,
731 people who read your message will have to change their Gnus
732 configuration.  See the variable `gnus-cite-attribution-suffix'."
733   :type 'function
734   :group 'message-insertion)
735
736 ;;;###autoload
737 (defcustom message-yank-prefix "> "
738   "*Prefix inserted on the lines of yanked messages.
739 Fix `message-cite-prefix-regexp' if it is set to an abnormal value.
740 See also `message-yank-cited-prefix'."
741   :type 'string
742   :group 'message-insertion)
743
744 (defcustom message-yank-cited-prefix ">"
745   "*Prefix inserted on cited or empty lines of yanked messages.
746 Fix `message-cite-prefix-regexp' if it is set to an abnormal value.
747 See also `message-yank-prefix'."
748   :type 'string
749   :group 'message-insertion)
750
751 (defcustom message-indentation-spaces 3
752   "*Number of spaces to insert at the beginning of each cited line.
753 Used by `message-yank-original' via `message-yank-cite'."
754   :group 'message-insertion
755   :type 'integer)
756
757 ;;;###autoload
758 (defcustom message-cite-function 'message-cite-original
759   "*Function for citing an original message.
760 Predefined functions include `message-cite-original' and
761 `message-cite-original-without-signature'.
762 Note that `message-cite-original' uses `mail-citation-hook' if that is non-nil."
763   :type '(radio (function-item message-cite-original)
764                 (function-item message-cite-original-without-signature)
765                 (function-item sc-cite-original)
766                 (function :tag "Other"))
767   :group 'message-insertion)
768
769 ;;;###autoload
770 (defcustom message-indent-citation-function 'message-indent-citation
771   "*Function for modifying a citation just inserted in the mail buffer.
772 This can also be a list of functions.  Each function can find the
773 citation between (point) and (mark t).  And each function should leave
774 point and mark around the citation text as modified."
775   :type 'function
776   :group 'message-insertion)
777
778 ;;;###autoload
779 (defcustom message-signature t
780   "*String to be inserted at the end of the message buffer.
781 If t, the `message-signature-file' file will be inserted instead.
782 If a function, the result from the function will be used instead.
783 If a form, the result from the form will be used instead."
784   :type 'sexp
785   :group 'message-insertion)
786
787 ;;;###autoload
788 (defcustom message-signature-file "~/.signature"
789   "*Name of file containing the text inserted at end of message buffer.
790 Ignored if the named file doesn't exist.
791 If nil, don't insert a signature."
792   :type '(choice file (const :tags "None" nil))
793   :group 'message-insertion)
794
795 (defcustom message-distribution-function nil
796   "*Function called to return a Distribution header."
797   :group 'message-news
798   :group 'message-headers
799   :type '(choice function (const nil)))
800
801 (defcustom message-expires 14
802   "Number of days before your article expires."
803   :group 'message-news
804   :group 'message-headers
805   :link '(custom-manual "(message)News Headers")
806   :type 'integer)
807
808 (defcustom message-user-path nil
809   "If nil, use the NNTP server name in the Path header.
810 If stringp, use this; if non-nil, use no host name (user name only)."
811   :group 'message-news
812   :group 'message-headers
813   :link '(custom-manual "(message)News Headers")
814   :type '(choice (const :tag "nntp" nil)
815                  (string :tag "name")
816                  (sexp :tag "none" :format "%t" t)))
817
818 (defvar message-reply-buffer nil)
819 (defvar message-reply-headers nil
820   "The headers of the current replied article.
821 It is a vector of the following headers:
822 \[number subject from date id references chars lines xref extra].")
823 (defvar message-newsreader nil)
824 (defvar message-mailer nil)
825 (defvar message-sent-message-via nil)
826 (defvar message-checksum nil)
827 (defvar message-send-actions nil
828   "A list of actions to be performed upon successful sending of a message.")
829 (defvar message-exit-actions nil
830   "A list of actions to be performed upon exiting after sending a message.")
831 (defvar message-kill-actions nil
832   "A list of actions to be performed before killing a message buffer.")
833 (defvar message-postpone-actions nil
834   "A list of actions to be performed after postponing a message.")
835
836 (define-widget 'message-header-lines 'text
837   "All header lines must be LFD terminated."
838   :format "%{%t%}:%n%v"
839   :valid-regexp "^\\'"
840   :error "All header lines must be newline terminated")
841
842 (defcustom message-default-headers ""
843   "*A string containing header lines to be inserted in outgoing messages.
844 It is inserted before you edit the message, so you can edit or delete
845 these lines."
846   :group 'message-headers
847   :type 'message-header-lines)
848
849 (defcustom message-default-mail-headers ""
850   "*A string of header lines to be inserted in outgoing mails."
851   :group 'message-headers
852   :group 'message-mail
853   :type 'message-header-lines)
854
855 (defcustom message-default-news-headers ""
856   "*A string of header lines to be inserted in outgoing news articles."
857   :group 'message-headers
858   :group 'message-news
859   :type 'message-header-lines)
860
861 ;; Note: could use /usr/ucb/mail instead of sendmail;
862 ;; options -t, and -v if not interactive.
863 (defcustom message-mailer-swallows-blank-line
864   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)"
865                          system-configuration)
866            (file-readable-p "/etc/sendmail.cf")
867            (let ((buffer (get-buffer-create " *temp*")))
868              (unwind-protect
869                  (save-excursion
870                    (set-buffer buffer)
871                    (insert-file-contents "/etc/sendmail.cf")
872                    (goto-char (point-min))
873                    (let ((case-fold-search nil))
874                      (re-search-forward "^OR\\>" nil t)))
875                (kill-buffer buffer))))
876       ;; According to RFC822, "The field-name must be composed of printable
877       ;; ASCII characters (i. e., characters that have decimal values between
878       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
879       ;; space, or colon.
880       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
881   "*Set this non-nil if the system's mailer runs the header and body together.
882 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
883 The value should be an expression to test whether the problem will
884 actually occur."
885   :group 'message-sending
886   :type 'sexp)
887
888 ;;;###autoload
889 (define-mail-user-agent 'message-user-agent
890   'message-mail 'message-send-and-exit
891   'message-kill-buffer 'message-send-hook)
892
893 (defvar message-mh-deletable-headers '(Message-ID Date Lines Sender)
894   "If non-nil, delete the deletable headers before feeding to mh.")
895
896 (defvar message-send-method-alist
897   '((news message-news-p message-send-via-news)
898     (mail message-mail-p message-send-via-mail))
899   "Alist of ways to send outgoing messages.
900 Each element has the form
901
902   \(TYPE PREDICATE FUNCTION)
903
904 where TYPE is a symbol that names the method; PREDICATE is a function
905 called without any parameters to determine whether the message is
906 a message of type TYPE; and FUNCTION is a function to be called if
907 PREDICATE returns non-nil.  FUNCTION is called with one parameter --
908 the prefix.")
909
910 (defcustom message-mail-alias-type 'abbrev
911   "*What alias expansion type to use in Message buffers.
912 The default is `abbrev', which uses mailabbrev.  nil switches
913 mail aliases off."
914   :group 'message
915   :link '(custom-manual "(message)Mail Aliases")
916   :type '(choice (const :tag "Use Mailabbrev" abbrev)
917                  (const :tag "No expansion" nil)))
918
919 (defcustom message-auto-save-directory
920   (file-name-as-directory (nnheader-concat message-directory "drafts"))
921   "*Directory where Message auto-saves buffers if Gnus isn't running.
922 If nil, Message won't auto-save."
923   :group 'message-buffers
924   :type '(choice directory (const :tag "Don't auto-save" nil)))
925
926 (defcustom message-default-charset
927   (and (not (mm-multibyte-p)) 'iso-8859-1)
928   "Default charset used in non-MULE Emacsen.
929 If nil, you might be asked to input the charset."
930   :version "21.1"
931   :group 'message
932   :type 'symbol)
933
934 (defcustom message-dont-reply-to-names
935   (and (boundp 'rmail-dont-reply-to-names) rmail-dont-reply-to-names)
936   "*A regexp specifying addresses to prune when doing wide replies.
937 A value of nil means exclude your own user name only."
938   :version "21.1"
939   :group 'message
940   :type '(choice (const :tag "Yourself" nil)
941                  regexp))
942
943 (defvar message-shoot-gnksa-feet nil
944   "*A list of GNKSA feet you are allowed to shoot.
945 Gnus gives you all the opportunity you could possibly want for
946 shooting yourself in the foot.  Also, Gnus allows you to shoot the
947 feet of Good Net-Keeping Seal of Approval. The following are foot
948 candidates:
949 `empty-article'     Allow you to post an empty article;
950 `quoted-text-only'  Allow you to post quoted text only;
951 `multiple-copies'   Allow you to post multiple copies;
952 `cancel-messages'   Allow you to cancel or supersede messages from 
953                     your other email addresses.")
954
955 (defsubst message-gnksa-enable-p (feature)
956   (or (not (listp message-shoot-gnksa-feet))
957       (memq feature message-shoot-gnksa-feet)))
958
959 ;;; Internal variables.
960 ;;; Well, not really internal.
961
962 (defvar message-mode-syntax-table
963   (let ((table (copy-syntax-table text-mode-syntax-table)))
964     (modify-syntax-entry ?% ". " table)
965     (modify-syntax-entry ?> ". " table)
966     (modify-syntax-entry ?< ". " table)
967     table)
968   "Syntax table used while in Message mode.")
969
970 (defface message-header-to-face
971   '((((class color)
972       (background dark))
973      (:foreground "green2" :bold t))
974     (((class color)
975       (background light))
976      (:foreground "MidnightBlue" :bold t))
977     (t
978      (:bold t :italic t)))
979   "Face used for displaying From headers."
980   :group 'message-faces)
981
982 (defface message-header-cc-face
983   '((((class color)
984       (background dark))
985      (:foreground "green4" :bold t))
986     (((class color)
987       (background light))
988      (:foreground "MidnightBlue"))
989     (t
990      (:bold t)))
991   "Face used for displaying Cc headers."
992   :group 'message-faces)
993
994 (defface message-header-subject-face
995   '((((class color)
996       (background dark))
997      (:foreground "green3"))
998     (((class color)
999       (background light))
1000      (:foreground "navy blue" :bold t))
1001     (t
1002      (:bold t)))
1003   "Face used for displaying subject headers."
1004   :group 'message-faces)
1005
1006 (defface message-header-newsgroups-face
1007   '((((class color)
1008       (background dark))
1009      (:foreground "yellow" :bold t :italic t))
1010     (((class color)
1011       (background light))
1012      (:foreground "blue4" :bold t :italic t))
1013     (t
1014      (:bold t :italic t)))
1015   "Face used for displaying newsgroups headers."
1016   :group 'message-faces)
1017
1018 (defface message-header-other-face
1019   '((((class color)
1020       (background dark))
1021      (:foreground "#b00000"))
1022     (((class color)
1023       (background light))
1024      (:foreground "steel blue"))
1025     (t
1026      (:bold t :italic t)))
1027   "Face used for displaying newsgroups headers."
1028   :group 'message-faces)
1029
1030 (defface message-header-name-face
1031   '((((class color)
1032       (background dark))
1033      (:foreground "DarkGreen"))
1034     (((class color)
1035       (background light))
1036      (:foreground "cornflower blue"))
1037     (t
1038      (:bold t)))
1039   "Face used for displaying header names."
1040   :group 'message-faces)
1041
1042 (defface message-header-xheader-face
1043   '((((class color)
1044       (background dark))
1045      (:foreground "blue"))
1046     (((class color)
1047       (background light))
1048      (:foreground "blue"))
1049     (t
1050      (:bold t)))
1051   "Face used for displaying X-Header headers."
1052   :group 'message-faces)
1053
1054 (defface message-separator-face
1055   '((((class color)
1056       (background dark))
1057      (:foreground "blue3"))
1058     (((class color)
1059       (background light))
1060      (:foreground "brown"))
1061     (t
1062      (:bold t)))
1063   "Face used for displaying the separator."
1064   :group 'message-faces)
1065
1066 (defface message-cited-text-face
1067   '((((class color)
1068       (background dark))
1069      (:foreground "red"))
1070     (((class color)
1071       (background light))
1072      (:foreground "red"))
1073     (t
1074      (:bold t)))
1075   "Face used for displaying cited text names."
1076   :group 'message-faces)
1077
1078 (defface message-mml-face
1079   '((((class color)
1080       (background dark))
1081      (:foreground "ForestGreen"))
1082     (((class color)
1083       (background light))
1084      (:foreground "ForestGreen"))
1085     (t
1086      (:bold t)))
1087   "Face used for displaying MML."
1088   :group 'message-faces)
1089
1090 (defun message-font-lock-make-header-matcher (regexp)
1091   (let ((form
1092          `(lambda (limit)
1093             (let ((start (point)))
1094               (save-restriction
1095                 (widen)
1096                 (goto-char (point-min))
1097                 (if (re-search-forward
1098                      (concat "^" (regexp-quote mail-header-separator) "$")
1099                      nil t)
1100                     (setq limit (min limit (match-beginning 0))))
1101                 (goto-char start))
1102               (and (< start limit)
1103                    (re-search-forward ,regexp limit t))))))
1104     (if (featurep 'bytecomp)
1105         (byte-compile form)
1106       form)))
1107
1108 (defvar message-font-lock-keywords
1109   (let ((content "[ \t]*\\(.+\\(\n[ \t].*\\)*\\)\n?"))
1110     `((,(message-font-lock-make-header-matcher
1111          (concat "^\\([Tt]o:\\)" content))
1112        (1 'message-header-name-face)
1113        (2 'message-header-to-face nil t))
1114       (,(message-font-lock-make-header-matcher
1115          (concat "^\\(^[GBF]?[Cc][Cc]:\\|^[Rr]eply-[Tt]o:\\)" content))
1116        (1 'message-header-name-face)
1117        (2 'message-header-cc-face nil t))
1118       (,(message-font-lock-make-header-matcher
1119          (concat "^\\([Ss]ubject:\\)" content))
1120        (1 'message-header-name-face)
1121        (2 'message-header-subject-face nil t))
1122       (,(message-font-lock-make-header-matcher
1123          (concat "^\\([Nn]ewsgroups:\\|Followup-[Tt]o:\\)" content))
1124        (1 'message-header-name-face)
1125        (2 'message-header-newsgroups-face nil t))
1126       (,(message-font-lock-make-header-matcher
1127          (concat "^\\([A-Z][^: \n\t]+:\\)" content))
1128        (1 'message-header-name-face)
1129        (2 'message-header-other-face nil t))
1130       (,(message-font-lock-make-header-matcher
1131          (concat "^\\(X-[A-Za-z0-9-]+:\\|In-Reply-To:\\)" content))
1132        (1 'message-header-name-face)
1133        (2 'message-header-name-face))
1134       ,@(if (and mail-header-separator
1135                  (not (equal mail-header-separator "")))
1136             `((,(concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
1137                1 'message-separator-face))
1138           nil)
1139       ((lambda (limit)
1140          (re-search-forward (concat "^\\("
1141                                     message-cite-prefix-regexp
1142                                     "\\).*")
1143                             limit t))
1144        (0 'message-cited-text-face))
1145       ("<#/?\\(multipart\\|part\\|external\\|mml\\|secure\\)[^>]*>"
1146        (0 'message-mml-face))))
1147   "Additional expressions to highlight in Message mode.")
1148
1149
1150 ;; XEmacs does it like this.  For Emacs, we have to set the
1151 ;; `font-lock-defaults' buffer-local variable.
1152 (put 'message-mode 'font-lock-defaults '(message-font-lock-keywords t))
1153
1154 (defvar message-face-alist
1155   '((bold . bold-region)
1156     (underline . underline-region)
1157     (default . (lambda (b e)
1158                  (unbold-region b e)
1159                  (ununderline-region b e))))
1160   "Alist of mail and news faces for facemenu.
1161 The cdr of each entry is a function for applying the face to a region.")
1162
1163 (defcustom message-send-hook nil
1164   "Hook run before sending messages."
1165   :group 'message-various
1166   :options '(ispell-message)
1167   :type 'hook)
1168
1169 (defcustom message-send-mail-hook nil
1170   "Hook run before sending mail messages."
1171   :group 'message-various
1172   :type 'hook)
1173
1174 (defcustom message-send-news-hook nil
1175   "Hook run before sending news messages."
1176   :group 'message-various
1177   :type 'hook)
1178
1179 (defcustom message-sent-hook nil
1180   "Hook run after sending messages."
1181   :group 'message-various
1182   :type 'hook)
1183
1184 (defvar message-send-coding-system 'binary
1185   "Coding system to encode outgoing mail.")
1186
1187 (defvar message-draft-coding-system
1188   mm-auto-save-coding-system
1189   "*Coding system to compose mail.
1190 If you'd like to make it possible to share draft files between XEmacs
1191 and Emacs, you may use `iso-2022-7bit' for this value at your own risk.
1192 Note that the coding-system `iso-2022-7bit' isn't suitable to all data.")
1193
1194 (defcustom message-send-mail-partially-limit 1000000
1195   "The limitation of messages sent as message/partial.
1196 The lower bound of message size in characters, beyond which the message
1197 should be sent in several parts.  If it is nil, the size is unlimited."
1198   :version "21.1"
1199   :group 'message-buffers
1200   :type '(choice (const :tag "unlimited" nil)
1201                  (integer 1000000)))
1202
1203 (defcustom message-alternative-emails nil
1204   "A regexp to match the alternative email addresses.
1205 The first matched address (not primary one) is used in the From field."
1206   :group 'message-headers
1207   :type '(choice (const :tag "Always use primary" nil)
1208                  regexp))
1209
1210 (defcustom message-hierarchical-addresses nil
1211   "A list of hierarchical mail address definitions.
1212
1213 Inside each entry, the first address is the \"top\" address, and
1214 subsequent addresses are subaddresses; this is used to indicate that
1215 mail sent to the first address will automatically be delivered to the
1216 subaddresses.  So if the first address appears in the recipient list
1217 for a message, the subaddresses will be removed (if present) before
1218 the mail is sent.  All addresses in this structure should be
1219 downcased."
1220   :group 'message-headers
1221   :type '(repeat (repeat string)))
1222
1223 (defcustom message-mail-user-agent nil
1224   "Like `mail-user-agent'.
1225 Except if it is nil, use Gnus native MUA; if it is t, use
1226 `mail-user-agent'."
1227   :type '(radio (const :tag "Gnus native"
1228                        :format "%t\n"
1229                        nil)
1230                 (const :tag "`mail-user-agent'"
1231                        :format "%t\n"
1232                        t)
1233                 (function-item :tag "Default Emacs mail"
1234                                :format "%t\n"
1235                                sendmail-user-agent)
1236                 (function-item :tag "Emacs interface to MH"
1237                                :format "%t\n"
1238                                mh-e-user-agent)
1239                 (function :tag "Other"))
1240   :version "21.1"
1241   :group 'message)
1242
1243 (defcustom message-wide-reply-confirm-recipients nil
1244   "Whether to confirm a wide reply to multiple email recipients.
1245 If this variable is nil, don't ask whether to reply to all recipients.
1246 If this variable is non-nil, pose the question \"Reply to all
1247 recipients?\" before a wide reply to multiple recipients.  If the user
1248 answers yes, reply to all recipients as usual.  If the user answers
1249 no, only reply back to the author."
1250   :version "21.3"
1251   :group 'message-headers
1252   :type 'boolean)
1253
1254 ;;; Internal variables.
1255
1256 (defvar message-sending-message "Sending...")
1257 (defvar message-buffer-list nil)
1258 (defvar message-this-is-news nil)
1259 (defvar message-this-is-mail nil)
1260 (defvar message-draft-article nil)
1261 (defvar message-mime-part nil)
1262 (defvar message-posting-charset nil)
1263
1264 ;; Byte-compiler warning
1265 (eval-when-compile
1266   (defvar gnus-active-hashtb)
1267   (defvar gnus-read-active-file))
1268
1269 ;;; Regexp matching the delimiter of messages in UNIX mail format
1270 ;;; (UNIX From lines), minus the initial ^.  It should be a copy
1271 ;;; of rmail.el's rmail-unix-mail-delimiter.
1272 (defvar message-unix-mail-delimiter
1273   (let ((time-zone-regexp
1274          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
1275                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
1276                  "\\|"
1277                  "\\) *")))
1278     (concat
1279      "From "
1280
1281      ;; Many things can happen to an RFC 822 mailbox before it is put into
1282      ;; a `From' line.  The leading phrase can be stripped, e.g.
1283      ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
1284      ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
1285      ;; can be removed, e.g.
1286      ;;         From: joe@y.z (Joe      K
1287      ;;                 User)
1288      ;; can yield `From joe@y.z (Joe    K Fri Mar 22 08:11:15 1996', and
1289      ;;         From: Joe User
1290      ;;                 <joe@y.z>
1291      ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
1292      ;; The mailbox can be removed or be replaced by white space, e.g.
1293      ;;         From: "Joe User"{space}{tab}
1294      ;;                 <joe@y.z>
1295      ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
1296      ;; where {space} and {tab} represent the Ascii space and tab characters.
1297      ;; We want to match the results of any of these manglings.
1298      ;; The following regexp rejects names whose first characters are
1299      ;; obviously bogus, but after that anything goes.
1300      "\\([^\0-\b\n-\r\^?].*\\)? "
1301
1302      ;; The time the message was sent.
1303      "\\([^\0-\r \^?]+\\) +"            ; day of the week
1304      "\\([^\0-\r \^?]+\\) +"            ; month
1305      "\\([0-3]?[0-9]\\) +"              ; day of month
1306      "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *" ; time of day
1307
1308      ;; Perhaps a time zone, specified by an abbreviation, or by a
1309      ;; numeric offset.
1310      time-zone-regexp
1311
1312      ;; The year.
1313      " \\([0-9][0-9]+\\) *"
1314
1315      ;; On some systems the time zone can appear after the year, too.
1316      time-zone-regexp
1317
1318      ;; Old uucp cruft.
1319      "\\(remote from .*\\)?"
1320
1321      "\n"))
1322   "Regexp matching the delimiter of messages in UNIX mail format.")
1323
1324 (defvar message-unsent-separator
1325   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
1326           "^ *---+ +Returned message +---+ *$\\|"
1327           "^Start of returned message$\\|"
1328           "^ *---+ +Original message +---+ *$\\|"
1329           "^ *--+ +begin message +--+ *$\\|"
1330           "^ *---+ +Original message follows +---+ *$\\|"
1331           "^ *---+ +Undelivered message follows +---+ *$\\|"
1332           "^|? *---+ +Message text follows: +---+ *|?$")
1333   "A regexp that matches the separator before the text of a failed message.")
1334
1335 (defvar message-header-format-alist
1336   `((Newsgroups)
1337     (To . message-fill-address)
1338     (Cc . message-fill-address)
1339     (Subject)
1340     (In-Reply-To)
1341     (Fcc)
1342     (Bcc)
1343     (Date)
1344     (Organization)
1345     (Distribution)
1346     (Lines)
1347     (Expires)
1348     (Message-ID)
1349     (References . message-shorten-references)
1350     (User-Agent))
1351   "Alist used for formatting headers.")
1352
1353 (defvar message-options nil
1354   "Some saved answers when sending message.")
1355
1356 (defvar message-send-mail-real-function nil
1357   "Internal send mail function.")
1358
1359 (defvar message-bogus-system-names "^localhost\\."
1360   "The regexp of bogus system names.")
1361
1362 (eval-and-compile
1363   (autoload 'message-setup-toolbar "messagexmas")
1364   (autoload 'mh-new-draft-name "mh-comp")
1365   (autoload 'mh-send-letter "mh-comp")
1366   (autoload 'gnus-point-at-eol "gnus-util")
1367   (autoload 'gnus-point-at-bol "gnus-util")
1368   (autoload 'gnus-output-to-rmail "gnus-util")
1369   (autoload 'gnus-output-to-mail "gnus-util")
1370   (autoload 'nndraft-request-associate-buffer "nndraft")
1371   (autoload 'nndraft-request-expire-articles "nndraft")
1372   (autoload 'gnus-open-server "gnus-int")
1373   (autoload 'gnus-request-post "gnus-int")
1374   (autoload 'gnus-alive-p "gnus-util")
1375   (autoload 'gnus-server-string "gnus")
1376   (autoload 'gnus-group-name-charset "gnus-group")
1377   (autoload 'gnus-group-name-decode "gnus-group")
1378   (autoload 'gnus-groups-from-server "gnus")
1379   (autoload 'rmail-output "rmailout")
1380   (autoload 'gnus-delay-article "gnus-delay"))
1381
1382 \f
1383
1384 ;;;
1385 ;;; Utility functions.
1386 ;;;
1387
1388 (defmacro message-y-or-n-p (question show &rest text)
1389   "Ask QUESTION, displaying remaining args in a temporary buffer if SHOW."
1390   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1391
1392 (defmacro message-delete-line (&optional n)
1393   "Delete the current line (and the next N lines)."
1394   `(delete-region (progn (beginning-of-line) (point))
1395                   (progn (forward-line ,(or n 1)) (point))))
1396
1397 (defun message-unquote-tokens (elems)
1398   "Remove double quotes (\") from strings in list ELEMS."
1399   (mapcar (lambda (item)
1400             (while (string-match "^\\(.*\\)\"\\(.*\\)$" item)
1401               (setq item (concat (match-string 1 item)
1402                                  (match-string 2 item))))
1403             item)
1404           elems))
1405
1406 (defun message-tokenize-header (header &optional separator)
1407   "Split HEADER into a list of header elements.
1408 SEPARATOR is a string of characters to be used as separators.  \",\"
1409 is used by default."
1410   (if (not header)
1411       nil
1412     (let ((regexp (format "[%s]+" (or separator ",")))
1413           (beg 1)
1414           (first t)
1415           quoted elems paren)
1416       (save-excursion
1417         (message-set-work-buffer)
1418         (insert header)
1419         (goto-char (point-min))
1420         (while (not (eobp))
1421           (if first
1422               (setq first nil)
1423             (forward-char 1))
1424           (cond ((and (> (point) beg)
1425                       (or (eobp)
1426                           (and (looking-at regexp)
1427                                (not quoted)
1428                                (not paren))))
1429                  (push (buffer-substring beg (point)) elems)
1430                  (setq beg (match-end 0)))
1431                 ((eq (char-after) ?\")
1432                  (setq quoted (not quoted)))
1433                 ((and (eq (char-after) ?\()
1434                       (not quoted))
1435                  (setq paren t))
1436                 ((and (eq (char-after) ?\))
1437                       (not quoted))
1438                  (setq paren nil))))
1439         (nreverse elems)))))
1440
1441 (defun message-mail-file-mbox-p (file)
1442   "Say whether FILE looks like a Unix mbox file."
1443   (when (and (file-exists-p file)
1444              (file-readable-p file)
1445              (file-regular-p file))
1446     (with-temp-buffer
1447       (nnheader-insert-file-contents file)
1448       (goto-char (point-min))
1449       (looking-at message-unix-mail-delimiter))))
1450
1451 (defun message-fetch-field (header &optional not-all)
1452   "The same as `mail-fetch-field', only remove all newlines."
1453   (let* ((inhibit-point-motion-hooks t)
1454          (case-fold-search t)
1455          (value (mail-fetch-field header nil (not not-all))))
1456     (when value
1457       (while (string-match "\n[\t ]+" value)
1458         (setq value (replace-match " " t t value)))
1459       (set-text-properties 0 (length value) nil value)
1460       value)))
1461
1462 (defun message-narrow-to-field ()
1463   "Narrow the buffer to the header on the current line."
1464   (beginning-of-line)
1465   (narrow-to-region
1466    (point)
1467    (progn
1468      (forward-line 1)
1469      (if (re-search-forward "^[^ \n\t]" nil t)
1470          (progn
1471            (beginning-of-line)
1472            (point))
1473        (point-max))))
1474   (goto-char (point-min)))
1475
1476 (defun message-add-header (&rest headers)
1477   "Add the HEADERS to the message header, skipping those already present."
1478   (while headers
1479     (let (hclean)
1480       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1481         (error "Invalid header `%s'" (car headers)))
1482       (setq hclean (match-string 1 (car headers)))
1483       (save-restriction
1484         (message-narrow-to-headers)
1485         (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1486           (goto-char (point-max))
1487           (if (string-match "\n$" (car headers))
1488               (insert (car headers))
1489             (insert (car headers) ?\n)))))
1490     (setq headers (cdr headers))))
1491
1492 (defmacro message-with-reply-buffer (&rest forms)
1493   "Evaluate FORMS in the reply buffer, if it exists."
1494   `(when (and message-reply-buffer
1495               (buffer-name message-reply-buffer))
1496      (save-excursion
1497        (set-buffer message-reply-buffer)
1498        ,@forms)))
1499
1500 (put 'message-with-reply-buffer 'lisp-indent-function 0)
1501 (put 'message-with-reply-buffer 'edebug-form-spec '(body))
1502
1503 (defun message-fetch-reply-field (header)
1504   "Fetch field HEADER from the message we're replying to."
1505   (message-with-reply-buffer
1506     (message-fetch-field header)))
1507
1508 (defun message-set-work-buffer ()
1509   (if (get-buffer " *message work*")
1510       (progn
1511         (set-buffer " *message work*")
1512         (erase-buffer))
1513     (set-buffer (get-buffer-create " *message work*"))
1514     (kill-all-local-variables)
1515     (mm-enable-multibyte)))
1516
1517 (defun message-functionp (form)
1518   "Return non-nil if FORM is funcallable."
1519   (or (and (symbolp form) (fboundp form))
1520       (and (listp form) (eq (car form) 'lambda))
1521       (byte-code-function-p form)))
1522
1523 (defun message-strip-list-identifiers (subject)
1524   "Remove list identifiers in `gnus-list-identifiers' from string SUBJECT."
1525   (require 'gnus-sum)                   ; for gnus-list-identifiers
1526   (let ((regexp (if (stringp gnus-list-identifiers)
1527                     gnus-list-identifiers
1528                   (mapconcat 'identity gnus-list-identifiers " *\\|"))))
1529     (if (string-match (concat "\\(\\(\\(Re: +\\)?\\(" regexp
1530                               " *\\)\\)+\\(Re: +\\)?\\)") subject)
1531         (concat (substring subject 0 (match-beginning 1))
1532                 (or (match-string 3 subject)
1533                     (match-string 5 subject))
1534                 (substring subject
1535                            (match-end 1)))
1536       subject)))
1537
1538 (defun message-strip-subject-re (subject)
1539   "Remove \"Re:\" from subject lines in string SUBJECT."
1540   (if (string-match message-subject-re-regexp subject)
1541       (substring subject (match-end 0))
1542     subject))
1543
1544 ;;; Start of functions adopted from `message-utils.el'.
1545
1546 (defun message-strip-subject-trailing-was (subject)
1547   "Remove trailing \"(Was: <old subject>)\" from subject lines.   
1548 Leading \"Re: \" is not stripped by this function.  Use the function
1549 `message-strip-subject-re' for this."
1550   (let* ((query message-subject-trailing-was-query)
1551          (new) (found))
1552     (setq found
1553           (string-match 
1554            (if (eq query 'ask)
1555                message-subject-trailing-was-ask-regexp
1556              message-subject-trailing-was-regexp)
1557            subject))
1558     (if found
1559         (setq new (substring subject 0 (match-beginning 0))))
1560     (if (or (not found) (eq query nil))
1561         subject
1562       (if (eq query 'ask)
1563           (if (message-y-or-n-p
1564                "Strip `(was: <old subject>)' in subject? " t
1565                (concat 
1566                 "Strip `(was: <old subject>)' in subject "
1567                 "and use the new one instead?\n\n"
1568                 "Current subject is:   \""
1569                 subject "\"\n\n"
1570                 "New subject would be: \""
1571                 new "\"\n\n"
1572                 "See the variable `message-subject-trailing-was-query' "
1573                 "to get rid of this query."
1574                 ))
1575               new subject)
1576         new))))
1577
1578 ;;; Suggested by Jonas Steverud  @  www.dtek.chalmers.se/~d4jonas/
1579
1580 ;;;###autoload
1581 (defun message-change-subject (new-subject)
1582   "Ask for new Subject: header, append (was: <Old Subject>)."
1583   (interactive
1584    (list
1585     (read-from-minibuffer "New subject: ")))
1586   (cond ((and (not (or (null new-subject) ; new subject not empty
1587                        (zerop (string-width new-subject))
1588                        (string-match "^[ \t]*$" new-subject))))
1589          (save-excursion
1590            (let ((old-subject (message-fetch-field "Subject")))
1591              (cond ((not old-subject)
1592                     (error "No current subject."))
1593                    ((not (string-match
1594                           (concat "^[ \t]*"
1595                                   (regexp-quote new-subject)
1596                                   " \t]*$")
1597                           old-subject))  ; yes, it really is a new subject
1598                     ;; delete eventual Re: prefix
1599                     (setq old-subject
1600                           (message-strip-subject-re old-subject))
1601                     (message-goto-subject)
1602                     (message-delete-line)
1603                     (insert (concat "Subject: "
1604                                     new-subject
1605                                     " (was: "
1606                                     old-subject ")\n")))))))))
1607
1608 ;;;###autoload
1609 (defun message-mark-inserted-region (beg end)
1610   "Mark some region in the current article with enclosing tags.
1611 See `message-mark-insert-begin' and `message-mark-insert-end'."
1612   (interactive "r")
1613   (save-excursion
1614     ; add to the end of the region first, otherwise end would be invalid
1615     (goto-char end)
1616     (insert message-mark-insert-end)
1617     (goto-char beg)
1618     (insert message-mark-insert-begin)))
1619
1620 ;;;###autoload
1621 (defun message-mark-insert-file (file)
1622   "Inserts FILE at point, marking it with enclosing tags.
1623 See `message-mark-insert-begin' and `message-mark-insert-end'."
1624   (interactive "fFile to insert: ")
1625     ;; reverse insertion to get correct result.
1626   (let ((p (point)))
1627     (insert message-mark-insert-end)
1628     (goto-char p)
1629     (insert-file-contents file)
1630     (goto-char p)
1631     (insert message-mark-insert-begin)))
1632
1633 ;;;###autoload
1634 (defun message-add-archive-header ()
1635   "Insert \"X-No-Archive: Yes\" in the header and a note in the body.
1636 The note can be customized using `message-archive-note'.  When called with a
1637 prefix argument, ask for a text to insert.  If you don't want the note in the
1638 body, set  `message-archive-note' to nil."
1639   (interactive)
1640   (if current-prefix-arg
1641       (setq message-archive-note
1642             (read-from-minibuffer "Reason for No-Archive: "
1643                                   (cons message-archive-note 0))))
1644     (save-excursion
1645       (if (message-goto-signature)
1646           (re-search-backward message-signature-separator))
1647       (when message-archive-note
1648         (insert message-archive-note)
1649         (newline))
1650       (message-add-header message-archive-header)
1651       (message-sort-headers)))
1652
1653 ;;;###autoload
1654 (defun message-xpost-fup2-header (target-group)
1655   "Mangles FollowUp-To and Newsgroups header to point to TARGET-GROUP.
1656 With prefix-argument just set Follow-Up, don't cross-post."
1657   (interactive
1658    (list ; Completion based on Gnus
1659     (completing-read "Followup To: "
1660                      (if (boundp 'gnus-newsrc-alist)
1661                          gnus-newsrc-alist)
1662                      nil nil '("poster" . 0)
1663                      (if (boundp 'gnus-group-history)
1664                          'gnus-group-history))))
1665   (message-remove-header "Follow[Uu]p-[Tt]o" t)
1666   (message-goto-newsgroups)
1667   (beginning-of-line)
1668   ;; if we already did a crosspost before, kill old target
1669   (if (and message-xpost-old-target
1670            (re-search-forward
1671             (regexp-quote (concat "," message-xpost-old-target))
1672             nil t))
1673       (replace-match ""))
1674   ;; unless (followup is to poster or user explicitly asked not
1675   ;; to cross-post, or target-group is already in Newsgroups)
1676   ;; add target-group to Newsgroups line.
1677   (cond ((and (or
1678                ;; def: xpost, req:no
1679                (and message-xpost-default (not current-prefix-arg))  
1680                ;; def: no-xpost, req:yes
1681                (and (not message-xpost-default) current-prefix-arg))
1682               (not (string-match "poster" target-group))
1683               (not (string-match (regexp-quote target-group)
1684                                  (message-fetch-field "Newsgroups"))))
1685          (end-of-line)
1686          (insert-string (concat "," target-group))))
1687   (end-of-line) ; ensure Followup: comes after Newsgroups:
1688   ;; unless new followup would be identical to Newsgroups line
1689   ;; make a new Followup-To line
1690   (if (not (string-match (concat "^[ \t]*"
1691                                  target-group
1692                                  "[ \t]*$")
1693                          (message-fetch-field "Newsgroups")))
1694       (insert (concat "\nFollowup-To: " target-group)))
1695   (setq message-xpost-old-target target-group))
1696
1697 ;;;###autoload
1698 (defun message-xpost-insert-note (target-group xpost in-old old-groups)
1699   "Insert a in message body note about a set Followup or Crosspost.
1700 If there have been previous notes, delete them.  TARGET-GROUP specifies the
1701 group to Followup-To.  When XPOST is t, insert note about
1702 crossposting.  IN-OLD specifies whether TARGET-GROUP is a member of
1703 OLD-GROUPS.  OLD-GROUPS lists the old-groups the posting would have
1704 been made to before the user asked for a Crosspost."
1705   ;; start scanning body for previous uses
1706   (message-goto-signature)
1707   (let ((head (re-search-backward
1708                (concat "^" mail-header-separator)
1709                nil t))) ; just search in body
1710     (message-goto-signature)
1711     (while (re-search-backward
1712             (concat "^" (regexp-quote message-xpost-note) ".*")
1713             head t)
1714       (message-delete-line))
1715     (message-goto-signature)
1716     (while (re-search-backward
1717             (concat "^" (regexp-quote message-fup2-note) ".*")
1718             head t)
1719       (message-delete-line))
1720     ;; insert new note
1721     (if (message-goto-signature)
1722         (re-search-backward message-signature-separator))
1723     (if (or in-old
1724             (not xpost)
1725             (string-match "^[ \t]*poster[ \t]*$" target-group))
1726         (insert (concat message-fup2-note target-group "\n"))
1727       (insert (concat message-xpost-note target-group "\n")))))
1728
1729 ;;;###autoload
1730 (defun message-xpost-fup2 (target-group)
1731   "Crossposts message and sets Followup-To to TARGET-GROUP.
1732 With prefix-argument just set Follow-Up, don't cross-post."
1733   (interactive
1734    (list ; Completion based on Gnus
1735     (completing-read "Followup To: "
1736                      (if (boundp 'gnus-newsrc-alist)
1737                          gnus-newsrc-alist)
1738                      nil nil '("poster" . 0)
1739                      (if (boundp 'gnus-group-history)
1740                          'gnus-group-history))))
1741   (cond ((not (or (null target-group) ; new subject not empty
1742                   (zerop (string-width target-group))
1743                   (string-match "^[ \t]*$" target-group)))
1744          (save-excursion
1745            (let* ((old-groups (message-fetch-field "Newsgroups"))
1746                   (in-old (string-match
1747                            (regexp-quote target-group) 
1748                            (or old-groups ""))))
1749              ;; check whether target exactly matches old Newsgroups
1750              (cond ((not old-groups)
1751                     (error "No current newsgroup."))
1752                    ((or (not in-old)
1753                         (not (string-match
1754                               (concat "^[ \t]*"
1755                                       (regexp-quote target-group)
1756                                       "[ \t]*$")
1757                               old-groups)))
1758                     ;; yes, Newsgroups line must change
1759                     (message-xpost-fup2-header target-group)
1760                     ;; insert note whether we do xpost or fup2
1761                     (funcall message-xpost-note-function
1762                              target-group
1763                              (if (or (and message-xpost-default
1764                                           (not current-prefix-arg))
1765                                      (and (not message-xpost-default)
1766                                           current-prefix-arg)) t)
1767                              in-old old-groups))))))))
1768
1769 ;;; Reduce To: to Cc: or Bcc: header
1770
1771 ;;;###autoload
1772 (defun message-reduce-to-to-cc ()
1773  "Replace contents of To: header with contents of Cc: or Bcc: header."
1774  (interactive)
1775  (let ((cc-content (message-fetch-field "cc"))
1776        (bcc nil))
1777    (if (and (not cc-content)
1778             (setq cc-content (message-fetch-field "bcc")))
1779        (setq bcc t))
1780    (cond (cc-content
1781           (save-excursion
1782             (message-goto-to)
1783             (message-delete-line)
1784             (insert (concat "To: " cc-content "\n"))
1785             (message-remove-header (if bcc
1786                                        "bcc"
1787                                      "cc")))))))
1788
1789 ;;; End of functions adopted from `message-utils.el'.
1790
1791 (defun message-remove-header (header &optional is-regexp first reverse)
1792   "Remove HEADER in the narrowed buffer.
1793 If IS-REGEXP, HEADER is a regular expression.
1794 If FIRST, only remove the first instance of the header.
1795 Return the number of headers removed."
1796   (goto-char (point-min))
1797   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1798         (number 0)
1799         (case-fold-search t)
1800         last)
1801     (while (and (not (eobp))
1802                 (not last))
1803       (if (if reverse
1804               (not (looking-at regexp))
1805             (looking-at regexp))
1806           (progn
1807             (incf number)
1808             (when first
1809               (setq last t))
1810             (delete-region
1811              (point)
1812              ;; There might be a continuation header, so we have to search
1813              ;; until we find a new non-continuation line.
1814              (progn
1815                (forward-line 1)
1816                (if (re-search-forward "^[^ \t]" nil t)
1817                    (goto-char (match-beginning 0))
1818                  (point-max)))))
1819         (forward-line 1)
1820         (if (re-search-forward "^[^ \t]" nil t)
1821             (goto-char (match-beginning 0))
1822           (goto-char (point-max)))))
1823     number))
1824
1825 (defun message-remove-first-header (header)
1826   "Remove the first instance of HEADER if there is more than one."
1827   (let ((count 0)
1828         (regexp (concat "^" (regexp-quote header) ":")))
1829     (save-excursion
1830       (goto-char (point-min))
1831       (while (re-search-forward regexp nil t)
1832         (incf count)))
1833     (while (> count 1)
1834       (message-remove-header header nil t)
1835       (decf count))))
1836
1837 (defun message-narrow-to-headers ()
1838   "Narrow the buffer to the head of the message."
1839   (widen)
1840   (narrow-to-region
1841    (goto-char (point-min))
1842    (if (re-search-forward
1843         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1844        (match-beginning 0)
1845      (point-max)))
1846   (goto-char (point-min)))
1847
1848 (defun message-narrow-to-head-1 ()
1849   "Like `message-narrow-to-head'.  Don't widen."
1850   (narrow-to-region
1851    (goto-char (point-min))
1852    (if (search-forward "\n\n" nil 1)
1853        (1- (point))
1854      (point-max)))
1855   (goto-char (point-min)))
1856
1857 (defun message-narrow-to-head ()
1858   "Narrow the buffer to the head of the message.
1859 Point is left at the beginning of the narrowed-to region."
1860   (widen)
1861   (message-narrow-to-head-1))
1862
1863 (defun message-narrow-to-headers-or-head ()
1864   "Narrow the buffer to the head of the message."
1865   (widen)
1866   (narrow-to-region
1867    (goto-char (point-min))
1868    (cond
1869     ((re-search-forward
1870       (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1871      (match-beginning 0))
1872     ((search-forward "\n\n" nil t)
1873      (1- (point)))
1874     (t
1875      (point-max))))
1876   (goto-char (point-min)))
1877
1878 (defun message-news-p ()
1879   "Say whether the current buffer contains a news message."
1880   (and (not message-this-is-mail)
1881        (or message-this-is-news
1882            (save-excursion
1883              (save-restriction
1884                (message-narrow-to-headers)
1885                (and (message-fetch-field "newsgroups")
1886                     (not (message-fetch-field "posted-to"))))))))
1887
1888 (defun message-mail-p ()
1889   "Say whether the current buffer contains a mail message."
1890   (and (not message-this-is-news)
1891        (or message-this-is-mail
1892            (save-excursion
1893              (save-restriction
1894                (message-narrow-to-headers)
1895                (or (message-fetch-field "to")
1896                    (message-fetch-field "cc")
1897                    (message-fetch-field "bcc")))))))
1898
1899 (defun message-next-header ()
1900   "Go to the beginning of the next header."
1901   (beginning-of-line)
1902   (or (eobp) (forward-char 1))
1903   (not (if (re-search-forward "^[^ \t]" nil t)
1904            (beginning-of-line)
1905          (goto-char (point-max)))))
1906
1907 (defun message-sort-headers-1 ()
1908   "Sort the buffer as headers using `message-rank' text props."
1909   (goto-char (point-min))
1910   (require 'sort)
1911   (sort-subr
1912    nil 'message-next-header
1913    (lambda ()
1914      (message-next-header)
1915      (unless (bobp)
1916        (forward-char -1)))
1917    (lambda ()
1918      (or (get-text-property (point) 'message-rank)
1919          10000))))
1920
1921 (defun message-sort-headers ()
1922   "Sort the headers of the current message according to `message-header-format-alist'."
1923   (interactive)
1924   (save-excursion
1925     (save-restriction
1926       (let ((max (1+ (length message-header-format-alist)))
1927             rank)
1928         (message-narrow-to-headers)
1929         (while (re-search-forward "^[^ \n]+:" nil t)
1930           (put-text-property
1931            (match-beginning 0) (1+ (match-beginning 0))
1932            'message-rank
1933            (if (setq rank (length (memq (assq (intern (buffer-substring
1934                                                        (match-beginning 0)
1935                                                        (1- (match-end 0))))
1936                                               message-header-format-alist)
1937                                         message-header-format-alist)))
1938                (- max rank)
1939              (1+ max)))))
1940       (message-sort-headers-1))))
1941
1942
1943 \f
1944
1945 ;;;
1946 ;;; Message mode
1947 ;;;
1948
1949 ;;; Set up keymap.
1950
1951 (defvar message-mode-map nil)
1952
1953 (unless message-mode-map
1954   (setq message-mode-map (make-keymap))
1955   (set-keymap-parent message-mode-map text-mode-map)
1956   (define-key message-mode-map "\C-c?" 'describe-mode)
1957
1958   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1959   (define-key message-mode-map "\C-c\C-f\C-o" 'message-goto-from)
1960   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1961   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1962   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1963   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1964   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1965   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1966   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1967   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1968   (define-key message-mode-map "\C-c\C-f\C-m" 'message-goto-mail-followup-to)
1969   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1970   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1971   (define-key message-mode-map "\C-c\C-f\C-i" 'message-insert-or-toggle-importance)
1972   (define-key message-mode-map "\C-c\C-f\C-a" 'message-gen-unsubscribed-mft)
1973
1974   ;; modify headers (and insert notes in body)
1975   (define-key message-mode-map "\C-c\C-fs"    'message-change-subject)
1976   ;;
1977   (define-key message-mode-map "\C-c\C-fx"    'message-xpost-fup2)
1978   ;; prefix+message-xpost-fup2 = same w/o xpost
1979   (define-key message-mode-map "\C-c\C-ft"    'message-reduce-to-to-cc)
1980   (define-key message-mode-map "\C-c\C-fa"    'message-add-archive-header)
1981   ;; mark inserted text
1982   (define-key message-mode-map "\C-c\M-m" 'message-mark-inserted-region)
1983   (define-key message-mode-map "\C-c\M-f" 'message-mark-insert-file)
1984   
1985   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1986   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1987
1988   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1989   (define-key message-mode-map "\C-c\C-p" 'message-insert-wide-reply)
1990   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1991   (define-key message-mode-map "\C-c\C-l" 'message-to-list-only)
1992
1993   (define-key message-mode-map "\C-c\C-u" 'message-insert-or-toggle-importance)
1994   (define-key message-mode-map "\C-c\M-n" 'message-insert-disposition-notification-to)
1995
1996   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1997   (define-key message-mode-map "\C-c\M-\C-y" 'message-yank-buffer)
1998   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1999   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
2000   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
2001   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
2002   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
2003   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
2004
2005   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
2006   (define-key message-mode-map "\C-c\C-s" 'message-send)
2007   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
2008   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
2009   (define-key message-mode-map "\C-c\n" 'gnus-delay-article)
2010
2011   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
2012   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
2013   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
2014   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
2015   ;;(define-key message-mode-map "\M-q" 'message-fill-paragraph)
2016
2017   (define-key message-mode-map "\C-c\C-a" 'mml-attach-file)
2018
2019   (define-key message-mode-map "\C-a" 'message-beginning-of-line)
2020   (define-key message-mode-map "\t" 'message-tab)
2021   (define-key message-mode-map "\M-;" 'comment-region))
2022
2023 (easy-menu-define
2024   message-mode-menu message-mode-map "Message Menu."
2025   `("Message"
2026     ["Sort Headers" message-sort-headers t]
2027     ["Yank Original" message-yank-original t]
2028     ["Fill Yanked Message" message-fill-yanked-message t]
2029     ["Insert Signature" message-insert-signature t]
2030     ["Caesar (rot13) Message" message-caesar-buffer-body t]
2031     ["Caesar (rot13) Region" message-caesar-region (mark t)]
2032     ["Elide Region" message-elide-region (mark t)]
2033     ["Delete Outside Region" message-delete-not-region (mark t)]
2034     ["Kill To Signature" message-kill-to-signature t]
2035     ["Newline and Reformat" message-newline-and-reformat t]
2036     ["Rename buffer" message-rename-buffer t]
2037     ["Flag As Important" message-insert-importance-high
2038      ,@(if (featurep 'xemacs) '(t)
2039          '(:help "Mark this message as important"))]
2040     ["Flag As Unimportant" message-insert-importance-low
2041      ,@(if (featurep 'xemacs) '(t)
2042          '(:help "Mark this message as unimportant"))]
2043     ["Request Receipt"
2044      message-insert-disposition-notification-to
2045      ,@(if (featurep 'xemacs) '(t)
2046          '(:help "Request a Disposition Notification of this article"))]
2047     ["Spellcheck" ispell-message
2048      ,@(if (featurep 'xemacs) '(t)
2049          '(:help "Spellcheck this message"))]
2050     "----"
2051     ["Insert Region Marked" message-mark-inserted-region 
2052      ,@(if (featurep 'xemacs) '(t)
2053          '(:help "Mark region with enclosing tags"))]
2054     ["Insert File Marked..." message-mark-insert-file 
2055      ,@(if (featurep 'xemacs) '(t)
2056          '(:help "Insert file at point marked with enclosing tags"))]
2057     "----"
2058     ["Send Message" message-send-and-exit
2059      ,@(if (featurep 'xemacs) '(t)
2060          '(:help "Send this message"))]
2061     ["Postpone Message" message-dont-send
2062      ,@(if (featurep 'xemacs) '(t)
2063          '(:help "File this draft message and exit"))]
2064     ["Send at Specific Time..." gnus-delay-article
2065      ,@(if (featurep 'xemacs) '(t)
2066          '(:help "Ask, then arrange to send message at that time"))]
2067     ["Kill Message" message-kill-buffer
2068      ,@(if (featurep 'xemacs) '(t)
2069          '(:help "Delete this message without sending"))]))
2070
2071 (easy-menu-define
2072   message-mode-field-menu message-mode-map ""
2073   '("Field"
2074     ["Fetch To" message-insert-to t]
2075     ["Fetch Newsgroups" message-insert-newsgroups t]
2076     "----"
2077     ["To" message-goto-to t]
2078     ["From" message-goto-from t]
2079     ["Subject" message-goto-subject t]
2080     ["Change subject..." message-change-subject t]
2081     ["Cc" message-goto-cc t]
2082     ["Bcc" message-goto-bcc t]
2083     ["Fcc" message-goto-fcc t]
2084     ["Reply-To" message-goto-reply-to t]
2085     "----"
2086     ;; (typical) news stuff
2087     ["Summary" message-goto-summary t]
2088     ["Keywords" message-goto-keywords t]
2089     ["Newsgroups" message-goto-newsgroups t]
2090     ["Followup-To" message-goto-followup-to t]
2091     ;; ["Followup-To (with note in body)" message-xpost-fup2 t]
2092     ["Crosspost / Followup-To..." message-xpost-fup2 t]
2093     ["Distribution" message-goto-distribution t]
2094     ["X-No-Archive:" message-add-archive-header t ]
2095     "----"
2096     ;; (typical) mailing-lists stuff
2097     ["Send to list only" message-to-list-only t]
2098     ["Mail-Followup-To" message-goto-mail-followup-to t]
2099     ["Reduce To: to Cc:" message-reduce-to-to-cc t]
2100     "----"
2101     ["Body" message-goto-body t]
2102     ["Signature" message-goto-signature t]))
2103
2104 (defvar message-tool-bar-map nil)
2105
2106 (eval-when-compile
2107   (defvar facemenu-add-face-function)
2108   (defvar facemenu-remove-face-function))
2109
2110 ;;; Forbidden properties
2111 ;;
2112 ;; We use `after-change-functions' to keep special text properties
2113 ;; that interfer with the normal function of message mode out of the
2114 ;; buffer.
2115
2116 (defcustom message-strip-special-text-properties t
2117   "Strip special properties from the message buffer.
2118
2119 Emacs has a number of special text properties which can break message
2120 composing in various ways.  If this option is set, message will strip
2121 these properties from the message composition buffer.  However, some
2122 packages requires these properties to be present in order to work.
2123 If you use one of these packages, turn this option off, and hope the
2124 message composition doesn't break too bad."
2125   :group 'message-various
2126   :type 'boolean)
2127
2128 (defconst message-forbidden-properties
2129   ;; No reason this should be clutter up customize.  We make it a
2130   ;; property list (rather than a list of property symbols), to be
2131   ;; directly useful for `remove-text-properties'.
2132   '(field nil read-only nil intangible nil invisible nil
2133           mouse-face nil modification-hooks nil insert-in-front-hooks nil
2134           insert-behind-hooks nil point-entered nil point-left nil)
2135   ;; Other special properties:
2136   ;; category, face, display: probably doesn't do any harm.
2137   ;; fontified: is used by font-lock.
2138   ;; syntax-table, local-map: I dunno.
2139   ;; We need to add XEmacs names to the list.
2140   "Property list of with properties.forbidden in message buffers.
2141 The values of the properties are ignored, only the property names are used.")
2142
2143 (defun message-tamago-not-in-use-p (pos)
2144   "Return t when tamago version 4 is not in use at the cursor position.
2145 Tamago version 4 is a popular input method for writing Japanese text.
2146 It uses the properties `intangible', `invisible', `modification-hooks'
2147 and `read-only' when translating ascii or kana text to kanji text.
2148 These properties are essential to work, so we should never strip them."
2149   (not (and (boundp 'egg-modefull-mode)
2150             (symbol-value 'egg-modefull-mode)
2151             (or (memq (get-text-property pos 'intangible)
2152                       '(its-part-1 its-part-2))
2153                 (get-text-property pos 'egg-end)
2154                 (get-text-property pos 'egg-lang)
2155                 (get-text-property pos 'egg-start)))))
2156
2157 (defun message-strip-forbidden-properties (begin end &optional old-length)
2158   "Strip forbidden properties between BEGIN and END, ignoring the third arg.
2159 This function is intended to be called from `after-change-functions'.
2160 See also `message-forbidden-properties'."
2161   (when (and message-strip-special-text-properties
2162              (message-tamago-not-in-use-p begin))
2163     (remove-text-properties begin end message-forbidden-properties)))
2164
2165 ;;;###autoload
2166 (define-derived-mode message-mode text-mode "Message"
2167   "Major mode for editing mail and news to be sent.
2168 Like Text Mode but with these additional commands:\\<message-mode-map>
2169 C-c C-s  `message-send' (send the message)  C-c C-c  `message-send-and-exit'
2170 C-c C-d  Postpone sending the message       C-c C-k  Kill the message
2171 C-c C-f  move to a header field (and create it if there isn't):
2172          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
2173          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
2174          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
2175          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
2176          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
2177          C-c C-f C-o  move to From (\"Originator\")
2178          C-c C-f C-f  move to Followup-To
2179          C-c C-f C-m  move to Mail-Followup-To
2180          C-c C-f C-i  cycle through Importance values
2181          C-c C-f s    change subject and append \"(was: <Old Subject>)\"
2182          C-c C-f x    crossposting with FollowUp-To header and note in body
2183          C-c C-f t    replace To: header with contents of Cc: or Bcc:
2184          C-c C-f a    Insert X-No-Archive: header and a note in the body
2185 C-c C-t  `message-insert-to' (add a To header to a news followup)
2186 C-c C-l  `message-to-list-only' (removes all but list address in to/cc)
2187 C-c C-n  `message-insert-newsgroups' (add a Newsgroup header to a news reply)
2188 C-c C-b  `message-goto-body' (move to beginning of message text).
2189 C-c C-i  `message-goto-signature' (move to the beginning of the signature).
2190 C-c C-w  `message-insert-signature' (insert `message-signature-file' file).
2191 C-c C-y  `message-yank-original' (insert current message, if any).
2192 C-c C-q  `message-fill-yanked-message' (fill what was yanked).
2193 C-c C-e  `message-elide-region' (elide the text between point and mark).
2194 C-c C-v  `message-delete-not-region' (remove the text outside the region).
2195 C-c C-z  `message-kill-to-signature' (kill the text up to the signature).
2196 C-c C-r  `message-caesar-buffer-body' (rot13 the message body).
2197 C-c C-a  `mml-attach-file' (attach a file as MIME).
2198 C-c C-u  `message-insert-or-toggle-importance'  (insert or cycle importance).
2199 C-c M-n  `message-insert-disposition-notification-to'  (request receipt).
2200 C-c M-m  `message-mark-inserted-region' (mark region with enclosing tags).
2201 C-c M-f  `message-mark-insert-file' (insert file marked with enclosing tags).
2202 M-RET    `message-newline-and-reformat' (break the line and reformat)."
2203   (setq local-abbrev-table text-mode-abbrev-table)
2204   (set (make-local-variable 'message-reply-buffer) nil)
2205   (make-local-variable 'message-send-actions)
2206   (make-local-variable 'message-exit-actions)
2207   (make-local-variable 'message-kill-actions)
2208   (make-local-variable 'message-postpone-actions)
2209   (make-local-variable 'message-draft-article)
2210   (setq buffer-offer-save t)
2211   (set (make-local-variable 'facemenu-add-face-function)
2212        (lambda (face end)
2213          (let ((face-fun (cdr (assq face message-face-alist))))
2214            (if face-fun
2215                (funcall face-fun (point) end)
2216              (error "Face %s not configured for %s mode" face mode-name)))
2217          ""))
2218   (set (make-local-variable 'facemenu-remove-face-function) t)
2219   (set (make-local-variable 'message-reply-headers) nil)
2220   (make-local-variable 'message-newsreader)
2221   (make-local-variable 'message-mailer)
2222   (make-local-variable 'message-post-method)
2223   (set (make-local-variable 'message-sent-message-via) nil)
2224   (set (make-local-variable 'message-checksum) nil)
2225   (set (make-local-variable 'message-mime-part) 0)
2226   (message-setup-fill-variables)
2227   ;; Allow using comment commands to add/remove quoting.
2228   (set (make-local-variable 'comment-start) message-yank-prefix)
2229   (if (featurep 'xemacs)
2230       (message-setup-toolbar)
2231     (set (make-local-variable 'font-lock-defaults)
2232          '(message-font-lock-keywords t))
2233     (if (boundp 'tool-bar-map)
2234         (set (make-local-variable 'tool-bar-map) (message-tool-bar-map))))
2235   (easy-menu-add message-mode-menu message-mode-map)
2236   (easy-menu-add message-mode-field-menu message-mode-map)
2237   ;; make-local-hook is harmless though obsolete in Emacs 21.
2238   ;; Emacs 20 and XEmacs need make-local-hook.
2239   (make-local-hook 'after-change-functions)
2240   ;; Mmmm... Forbidden properties...
2241   (add-hook 'after-change-functions 'message-strip-forbidden-properties
2242             nil 'local)
2243   ;; Allow mail alias things.
2244   (when (eq message-mail-alias-type 'abbrev)
2245     (if (fboundp 'mail-abbrevs-setup)
2246         (mail-abbrevs-setup)
2247       (mail-aliases-setup)))
2248   (unless buffer-file-name
2249     (message-set-auto-save-file-name))
2250   (unless (buffer-base-buffer)
2251     ;; Don't enable multibyte on an indirect buffer.  Maybe enabling
2252     ;; multibyte is not necessary at all. -- zsh
2253     (mm-enable-multibyte))
2254   (set (make-local-variable 'indent-tabs-mode) nil) ;No tabs for indentation.
2255   (mml-mode))
2256
2257 (defun message-setup-fill-variables ()
2258   "Setup message fill variables."
2259   (set (make-local-variable 'fill-paragraph-function)
2260        'message-fill-paragraph)
2261   (make-local-variable 'paragraph-separate)
2262   (make-local-variable 'paragraph-start)
2263   (make-local-variable 'adaptive-fill-regexp)
2264   (unless (boundp 'adaptive-fill-first-line-regexp)
2265     (setq adaptive-fill-first-line-regexp nil))
2266   (make-local-variable 'adaptive-fill-first-line-regexp)
2267   (let ((quote-prefix-regexp
2268          ;; User should change message-cite-prefix-regexp if
2269          ;; message-yank-prefix is set to an abnormal value.
2270          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))
2271     (setq paragraph-start
2272           (concat
2273            (regexp-quote mail-header-separator) "$\\|"
2274            "[ \t]*$\\|"                 ; blank lines
2275            "-- $\\|"                    ; signature delimiter
2276            "---+$\\|"              ; delimiters for forwarded messages
2277            page-delimiter "$\\|"        ; spoiler warnings
2278            ".*wrote:$\\|"               ; attribution lines
2279            quote-prefix-regexp "$"))    ; empty lines in quoted text
2280     (setq paragraph-separate paragraph-start)
2281     (setq adaptive-fill-regexp
2282           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
2283     (setq adaptive-fill-first-line-regexp
2284           (concat quote-prefix-regexp "\\|"
2285                   adaptive-fill-first-line-regexp)))
2286   (make-local-variable 'auto-fill-inhibit-regexp)
2287   ;;(setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
2288   (setq auto-fill-inhibit-regexp nil)
2289   (make-local-variable 'normal-auto-fill-function)
2290   (setq normal-auto-fill-function 'message-do-auto-fill)
2291   ;; KLUDGE: auto fill might already be turned on in `text-mode-hook'.
2292   ;; In that case, ensure that it uses the right function.  The real
2293   ;; solution would be not to use `define-derived-mode', and run
2294   ;; `text-mode-hook' ourself at the end of the mode.
2295   ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-19.
2296   (when auto-fill-function
2297     (setq auto-fill-function normal-auto-fill-function)))
2298
2299 \f
2300
2301 ;;;
2302 ;;; Message mode commands
2303 ;;;
2304
2305 ;;; Movement commands
2306
2307 (defun message-goto-to ()
2308   "Move point to the To header."
2309   (interactive)
2310   (message-position-on-field "To"))
2311
2312 (defun message-goto-from ()
2313   "Move point to the From header."
2314   (interactive)
2315   (message-position-on-field "From"))
2316
2317 (defun message-goto-subject ()
2318   "Move point to the Subject header."
2319   (interactive)
2320   (message-position-on-field "Subject"))
2321
2322 (defun message-goto-cc ()
2323   "Move point to the Cc header."
2324   (interactive)
2325   (message-position-on-field "Cc" "To"))
2326
2327 (defun message-goto-bcc ()
2328   "Move point to the Bcc  header."
2329   (interactive)
2330   (message-position-on-field "Bcc" "Cc" "To"))
2331
2332 (defun message-goto-fcc ()
2333   "Move point to the Fcc header."
2334   (interactive)
2335   (message-position-on-field "Fcc" "To" "Newsgroups"))
2336
2337 (defun message-goto-reply-to ()
2338   "Move point to the Reply-To header."
2339   (interactive)
2340   (message-position-on-field "Reply-To" "Subject"))
2341
2342 (defun message-goto-newsgroups ()
2343   "Move point to the Newsgroups header."
2344   (interactive)
2345   (message-position-on-field "Newsgroups"))
2346
2347 (defun message-goto-distribution ()
2348   "Move point to the Distribution header."
2349   (interactive)
2350   (message-position-on-field "Distribution"))
2351
2352 (defun message-goto-followup-to ()
2353   "Move point to the Followup-To header."
2354   (interactive)
2355   (message-position-on-field "Followup-To" "Newsgroups"))
2356
2357 (defun message-goto-mail-followup-to ()
2358   "Move point to the Mail-Followup-To header."
2359   (interactive)
2360   (message-position-on-field "Mail-Followup-To" "From"))
2361
2362 (defun message-goto-keywords ()
2363   "Move point to the Keywords header."
2364   (interactive)
2365   (message-position-on-field "Keywords" "Subject"))
2366
2367 (defun message-goto-summary ()
2368   "Move point to the Summary header."
2369   (interactive)
2370   (message-position-on-field "Summary" "Subject"))
2371
2372 (defun message-goto-body (&optional interactivep)
2373   "Move point to the beginning of the message body."
2374   (interactive (list t))
2375   (when (and interactivep
2376              (looking-at "[ \t]*\n"))
2377     (expand-abbrev))
2378   (goto-char (point-min))
2379   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
2380       (search-forward-regexp "[^:]+:\\([^\n]\\|\n[ \t]\\)+\n\n" nil t)))
2381
2382 (defun message-goto-eoh ()
2383   "Move point to the end of the headers."
2384   (interactive)
2385   (message-goto-body)
2386   (forward-line -1))
2387
2388 (defun message-goto-signature ()
2389   "Move point to the beginning of the message signature.
2390 If there is no signature in the article, go to the end and
2391 return nil."
2392   (interactive)
2393   (goto-char (point-min))
2394   (if (re-search-forward message-signature-separator nil t)
2395       (forward-line 1)
2396     (goto-char (point-max))
2397     nil))
2398
2399 (defun message-gen-unsubscribed-mft (&optional include-cc)
2400   "Insert a reasonable MFT header in a post to an unsubscribed list.
2401 When making original posts to a mailing list you are not subscribed to,
2402 you have to type in a MFT header by hand.  The contents, usually, are
2403 the addresses of the list and your own address.  This function inserts
2404 such a header automatically.  It fetches the contents of the To: header
2405 in the current mail buffer, and appends the current user-mail-address.
2406
2407 If the optional argument `include-cc' is non-nil, the addresses in the
2408 Cc: header are also put into the MFT."
2409
2410   (interactive "P")
2411   (message-remove-header "Mail-Followup-To")
2412   (let* ((cc (and include-cc (message-fetch-field "Cc")))
2413          (tos (if cc
2414                   (concat (message-fetch-field "To") "," cc)
2415                 (message-fetch-field "To"))))
2416     (message-goto-mail-followup-to)
2417     (insert (concat tos ", " user-mail-address))))
2418
2419 \f
2420
2421 (defun message-insert-to (&optional force)
2422   "Insert a To header that points to the author of the article being replied to.
2423 If the original author requested not to be sent mail, the function signals
2424 an error.
2425 With the prefix argument FORCE, insert the header anyway."
2426   (interactive "P")
2427   (let ((co (message-fetch-reply-field "mail-copies-to")))
2428     (when (and (null force)
2429                co
2430                (or (equal (downcase co) "never")
2431                    (equal (downcase co) "nobody")))
2432       (error "The user has requested not to have copies sent via mail")))
2433   (message-carefully-insert-headers
2434    (list (cons 'To
2435                (or (message-fetch-reply-field "mail-reply-to")
2436                    (message-fetch-reply-field "reply-to")
2437                    (message-fetch-reply-field "from")
2438                    "")))))
2439
2440 (defun message-insert-wide-reply ()
2441   "Insert To and Cc headers as if you were doing a wide reply."
2442   (interactive)
2443   (let ((headers (message-with-reply-buffer
2444                    (message-get-reply-headers t))))
2445     (message-carefully-insert-headers headers)))
2446
2447 (defun message-carefully-insert-headers (headers)
2448   (dolist (header headers)
2449     (let ((header-name (symbol-name (car header))))
2450       (when (and (message-position-on-field header-name)
2451                  (mail-fetch-field header-name)
2452                  (not (string-match "\\` *\\'"
2453                                     (mail-fetch-field header-name))))
2454         (insert ", "))
2455       (insert (cdr header)))))
2456
2457 (defun message-widen-reply ()
2458   "Widen the reply to include maximum recipients."
2459   (interactive)
2460   (let ((follow-to
2461          (and message-reply-buffer
2462               (buffer-name message-reply-buffer)
2463               (save-excursion
2464                 (set-buffer message-reply-buffer)
2465                 (message-get-reply-headers t)))))
2466     (save-excursion
2467       (save-restriction
2468         (message-narrow-to-headers)
2469         (dolist (elem follow-to)
2470           (message-remove-header (symbol-name (car elem)))
2471           (goto-char (point-min))
2472           (insert (symbol-name (car elem)) ": "
2473                   (cdr elem) "\n"))))))
2474
2475 (defun message-insert-newsgroups ()
2476   "Insert the Newsgroups header from the article being replied to."
2477   (interactive)
2478   (when (and (message-position-on-field "Newsgroups")
2479              (mail-fetch-field "newsgroups")
2480              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
2481     (insert ","))
2482   (insert (or (message-fetch-reply-field "newsgroups") "")))
2483
2484 \f
2485
2486 ;;; Various commands
2487
2488 (defun message-delete-not-region (beg end)
2489   "Delete everything in the body of the current message outside of the region."
2490   (interactive "r")
2491   (let (citeprefix)
2492     (save-excursion
2493       (goto-char beg)
2494       ;; snarf citation prefix, if appropriate
2495       (unless (eq (point) (progn (beginning-of-line) (point)))
2496         (when (looking-at message-cite-prefix-regexp)
2497           (setq citeprefix (match-string 0))))
2498       (goto-char end)
2499       (delete-region (point) (if (not (message-goto-signature))
2500                                  (point)
2501                                (forward-line -2)
2502                                (point)))
2503       (insert "\n")
2504       (goto-char beg)
2505       (delete-region beg (progn (message-goto-body)
2506                                 (forward-line 2)
2507                                 (point)))
2508       (when citeprefix
2509         (insert citeprefix))))
2510   (when (message-goto-signature)
2511     (forward-line -2)))
2512
2513 (defun message-kill-to-signature ()
2514   "Deletes all text up to the signature."
2515   (interactive)
2516   (let ((point (point)))
2517     (message-goto-signature)
2518     (unless (eobp)
2519       (forward-line -2))
2520     (kill-region point (point))
2521     (unless (bolp)
2522       (insert "\n"))))
2523
2524 (defun message-newline-and-reformat (&optional arg not-break)
2525   "Insert four newlines, and then reformat if inside quoted text.
2526 Prefix arg means justify as well."
2527   (interactive (list (if current-prefix-arg 'full)))
2528   (let (quoted point beg end leading-space bolp)
2529     (setq point (point))
2530     (beginning-of-line)
2531     (setq beg (point))
2532     (setq bolp (= beg point))
2533     ;; Find first line of the paragraph.
2534     (if not-break
2535         (while (and (not (eobp))
2536                     (not (looking-at message-cite-prefix-regexp))
2537                     (looking-at paragraph-start))
2538           (forward-line 1)))
2539     ;; Find the prefix
2540     (when (looking-at message-cite-prefix-regexp)
2541       (setq quoted (match-string 0))
2542       (goto-char (match-end 0))
2543       (looking-at "[ \t]*")
2544       (setq leading-space (match-string 0)))
2545     (if (and quoted
2546              (not not-break)
2547              (not bolp)
2548              (< (- point beg) (length quoted)))
2549         ;; break inside the cite prefix.
2550         (setq quoted nil
2551               end nil))
2552     (if quoted
2553         (progn
2554           (forward-line 1)
2555           (while (and (not (eobp))
2556                       (not (looking-at paragraph-separate))
2557                       (looking-at message-cite-prefix-regexp)
2558                       (equal quoted (match-string 0)))
2559             (goto-char (match-end 0))
2560             (looking-at "[ \t]*")
2561             (if (> (length leading-space) (length (match-string 0)))
2562                 (setq leading-space (match-string 0)))
2563             (forward-line 1))
2564           (setq end (point))
2565           (goto-char beg)
2566           (while (and (if (bobp) nil (forward-line -1) t)
2567                       (not (looking-at paragraph-start))
2568                       (looking-at message-cite-prefix-regexp)
2569                       (equal quoted (match-string 0)))
2570             (setq beg (point))
2571             (goto-char (match-end 0))
2572             (looking-at "[ \t]*")
2573             (if (> (length leading-space) (length (match-string 0)))
2574                 (setq leading-space (match-string 0)))))
2575       (while (and (not (eobp))
2576                   (not (looking-at paragraph-separate))
2577                   (not (looking-at message-cite-prefix-regexp)))
2578         (forward-line 1))
2579       (setq end (point))
2580       (goto-char beg)
2581       (while (and (if (bobp) nil (forward-line -1) t)
2582                   (not (looking-at paragraph-start))
2583                   (not (looking-at message-cite-prefix-regexp)))
2584         (setq beg (point))))
2585     (goto-char point)
2586     (save-restriction
2587       (narrow-to-region beg end)
2588       (if not-break
2589           (setq point nil)
2590         (if bolp
2591             (newline)
2592           (newline)
2593           (newline))
2594         (setq point (point))
2595         ;; (newline 2) doesn't mark both newline's as hard, so call
2596         ;; newline twice. -jas
2597         (newline)
2598         (newline)
2599         (delete-region (point) (re-search-forward "[ \t]*"))
2600         (when (and quoted (not bolp))
2601           (insert quoted leading-space)))
2602       (if quoted
2603           (let* ((adaptive-fill-regexp
2604                   (regexp-quote (concat quoted leading-space)))
2605                  (adaptive-fill-first-line-regexp
2606                   adaptive-fill-regexp ))
2607             (fill-paragraph arg))
2608         (fill-paragraph arg))
2609       (if point (goto-char point)))))
2610
2611 (defun message-fill-paragraph (&optional arg)
2612   "Like `fill-paragraph'."
2613   (interactive (list (if current-prefix-arg 'full)))
2614   (if (and (boundp 'filladapt-mode) filladapt-mode)
2615       nil
2616     (message-newline-and-reformat arg t)
2617     t))
2618
2619 ;; Is it better to use `mail-header-end'?
2620 (defun message-point-in-header-p ()
2621   "Return t if point is in the header."
2622   (save-excursion
2623     (let ((p (point)))
2624       (goto-char (point-min))
2625       (not (re-search-forward
2626             (concat "^" (regexp-quote mail-header-separator) "\n")
2627             p t)))))
2628
2629 (defun message-do-auto-fill ()
2630   "Like `do-auto-fill', but don't fill in message header."
2631   (unless (message-point-in-header-p)
2632     (do-auto-fill)))
2633
2634 (defun message-insert-signature (&optional force)
2635   "Insert a signature.  See documentation for variable `message-signature'."
2636   (interactive (list 0))
2637   (let* ((signature
2638           (cond
2639            ((and (null message-signature)
2640                  (eq force 0))
2641             (save-excursion
2642               (goto-char (point-max))
2643               (not (re-search-backward message-signature-separator nil t))))
2644            ((and (null message-signature)
2645                  force)
2646             t)
2647            ((message-functionp message-signature)
2648             (funcall message-signature))
2649            ((listp message-signature)
2650             (eval message-signature))
2651            (t message-signature)))
2652          (signature
2653           (cond ((stringp signature)
2654                  signature)
2655                 ((and (eq t signature)
2656                       message-signature-file
2657                       (file-exists-p message-signature-file))
2658                  signature))))
2659     (when signature
2660       (goto-char (point-max))
2661       ;; Insert the signature.
2662       (unless (bolp)
2663         (insert "\n"))
2664       (insert "\n-- \n")
2665       (if (eq signature t)
2666           (insert-file-contents message-signature-file)
2667         (insert signature))
2668       (goto-char (point-max))
2669       (or (bolp) (insert "\n")))))
2670
2671 (defun message-insert-importance-high ()
2672   "Insert header to mark message as important."
2673   (interactive)
2674   (save-excursion
2675     (message-remove-header "Importance")
2676     (message-goto-eoh)
2677     (insert "Importance: high\n")))
2678
2679 (defun message-insert-importance-low ()
2680   "Insert header to mark message as unimportant."
2681   (interactive)
2682   (save-excursion
2683     (message-remove-header "Importance")
2684     (message-goto-eoh)
2685     (insert "Importance: low\n")))
2686
2687 (defun message-insert-or-toggle-importance ()
2688   "Insert a \"Importance: high\" header, or cycle through the header values.
2689 The three allowed values according to RFC 1327 are `high', `normal'
2690 and `low'."
2691   (interactive)
2692   (save-excursion
2693     (let ((valid '("high" "normal" "low"))
2694           (new "high")
2695           cur)
2696       (when (setq cur (message-fetch-field "Importance"))
2697         (message-remove-header "Importance")
2698         (setq new (cond ((string= cur "high")
2699                          "low")
2700                         ((string= cur "low")
2701                          "normal")
2702                         (t
2703                          "high"))))
2704       (message-goto-eoh)
2705       (insert (format "Importance: %s\n" new)))))
2706
2707 (defun message-insert-disposition-notification-to ()
2708   "Request a disposition notification (return receipt) to this message.
2709 Note that this should not be used in newsgroups."
2710   (interactive)
2711   (save-excursion
2712     (message-remove-header "Disposition-Notification-To")
2713     (message-goto-eoh)
2714     (insert (format "Disposition-Notification-To: %s\n"
2715                     (or (message-fetch-field "From") (message-make-from))))))
2716
2717 (defun message-elide-region (b e)
2718   "Elide the text in the region.
2719 An ellipsis (from `message-elide-ellipsis') will be inserted where the
2720 text was killed."
2721   (interactive "r")
2722   (kill-region b e)
2723   (insert message-elide-ellipsis))
2724
2725 (defvar message-caesar-translation-table nil)
2726
2727 (defun message-caesar-region (b e &optional n)
2728   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
2729   (interactive
2730    (list
2731     (min (point) (or (mark t) (point)))
2732     (max (point) (or (mark t) (point)))
2733     (when current-prefix-arg
2734       (prefix-numeric-value current-prefix-arg))))
2735
2736   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
2737   (unless (or (zerop n)                 ; no action needed for a rot of 0
2738               (= b e))                  ; no region to rotate
2739     ;; We build the table, if necessary.
2740     (when (or (not message-caesar-translation-table)
2741               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
2742       (setq message-caesar-translation-table
2743             (message-make-caesar-translation-table n)))
2744     (translate-region b e message-caesar-translation-table)))
2745
2746 (defun message-make-caesar-translation-table (n)
2747   "Create a rot table with offset N."
2748   (let ((i -1)
2749         (table (make-string 256 0)))
2750     (while (< (incf i) 256)
2751       (aset table i i))
2752     (concat
2753      (substring table 0 ?A)
2754      (substring table (+ ?A n) (+ ?A n (- 26 n)))
2755      (substring table ?A (+ ?A n))
2756      (substring table (+ ?A 26) ?a)
2757      (substring table (+ ?a n) (+ ?a n (- 26 n)))
2758      (substring table ?a (+ ?a n))
2759      (substring table (+ ?a 26) 255))))
2760
2761 (defun message-caesar-buffer-body (&optional rotnum)
2762   "Caesar rotate all letters in the current buffer by 13 places.
2763 Used to encode/decode possibly offensive messages (commonly in rec.humor).
2764 With prefix arg, specifies the number of places to rotate each letter forward.
2765 Mail and USENET news headers are not rotated."
2766   (interactive (if current-prefix-arg
2767                    (list (prefix-numeric-value current-prefix-arg))
2768                  (list nil)))
2769   (save-excursion
2770     (save-restriction
2771       (when (message-goto-body)
2772         (narrow-to-region (point) (point-max)))
2773       (message-caesar-region (point-min) (point-max) rotnum))))
2774
2775 (defun message-pipe-buffer-body (program)
2776   "Pipe the message body in the current buffer through PROGRAM."
2777   (save-excursion
2778     (save-restriction
2779       (when (message-goto-body)
2780         (narrow-to-region (point) (point-max)))
2781       (shell-command-on-region
2782        (point-min) (point-max) program nil t))))
2783
2784 (defun message-rename-buffer (&optional enter-string)
2785   "Rename the *message* buffer to \"*message* RECIPIENT\".
2786 If the function is run with a prefix, it will ask for a new buffer
2787 name, rather than giving an automatic name."
2788   (interactive "Pbuffer name: ")
2789   (save-excursion
2790     (save-restriction
2791       (goto-char (point-min))
2792       (narrow-to-region (point)
2793                         (search-forward mail-header-separator nil 'end))
2794       (let* ((mail-to (or
2795                        (if (message-news-p) (message-fetch-field "Newsgroups")
2796                          (message-fetch-field "To"))
2797                        ""))
2798              (mail-trimmed-to
2799               (if (string-match "," mail-to)
2800                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
2801                 mail-to))
2802              (name-default (concat "*message* " mail-trimmed-to))
2803              (name (if enter-string
2804                        (read-string "New buffer name: " name-default)
2805                      name-default)))
2806         (rename-buffer name t)))))
2807
2808 (defun message-fill-yanked-message (&optional justifyp)
2809   "Fill the paragraphs of a message yanked into this one.
2810 Numeric argument means justify as well."
2811   (interactive "P")
2812   (save-excursion
2813     (goto-char (point-min))
2814     (search-forward (concat "\n" mail-header-separator "\n") nil t)
2815     (let ((fill-prefix message-yank-prefix))
2816       (fill-individual-paragraphs (point) (point-max) justifyp))))
2817
2818 (defun message-indent-citation ()
2819   "Modify text just inserted from a message to be cited.
2820 The inserted text should be the region.
2821 When this function returns, the region is again around the modified text.
2822
2823 Normally, indent each nonblank line `message-indentation-spaces' spaces.
2824 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
2825   (let ((start (point)))
2826     ;; Remove unwanted headers.
2827     (when message-ignored-cited-headers
2828       (let (all-removed)
2829         (save-restriction
2830           (narrow-to-region
2831            (goto-char start)
2832            (if (search-forward "\n\n" nil t)
2833                (1- (point))
2834              (point)))
2835           (message-remove-header message-ignored-cited-headers t)
2836           (when (= (point-min) (point-max))
2837             (setq all-removed t))
2838           (goto-char (point-max)))
2839         (if all-removed
2840             (goto-char start)
2841           (forward-line 1))))
2842     ;; Delete blank lines at the start of the buffer.
2843     (while (and (point-min)
2844                 (eolp)
2845                 (not (eobp)))
2846       (message-delete-line))
2847     ;; Delete blank lines at the end of the buffer.
2848     (goto-char (point-max))
2849     (unless (eolp)
2850       (insert "\n"))
2851     (while (and (zerop (forward-line -1))
2852                 (looking-at "$"))
2853       (message-delete-line))
2854     ;; Do the indentation.
2855     (if (null message-yank-prefix)
2856         (indent-rigidly start (mark t) message-indentation-spaces)
2857       (save-excursion
2858         (goto-char start)
2859         (while (< (point) (mark t))
2860           (if (or (looking-at ">") (looking-at "^$"))
2861               (insert message-yank-cited-prefix)
2862             (insert message-yank-prefix))
2863           (forward-line 1))))
2864     (goto-char start)))
2865
2866 (defun message-yank-original (&optional arg)
2867   "Insert the message being replied to, if any.
2868 Puts point before the text and mark after.
2869 Normally indents each nonblank line ARG spaces (default 3).  However,
2870 if `message-yank-prefix' is non-nil, insert that prefix on each line.
2871
2872 This function uses `message-cite-function' to do the actual citing.
2873
2874 Just \\[universal-argument] as argument means don't indent, insert no
2875 prefix, and don't delete any headers."
2876   (interactive "P")
2877   (let ((modified (buffer-modified-p)))
2878     (when (and message-reply-buffer
2879                message-cite-function)
2880       (delete-windows-on message-reply-buffer t)
2881       (insert-buffer message-reply-buffer)
2882       (unless arg
2883         (funcall message-cite-function))
2884       (message-exchange-point-and-mark)
2885       (unless (bolp)
2886         (insert ?\n))
2887       (unless modified
2888         (setq message-checksum (message-checksum))))))
2889
2890 (defun message-yank-buffer (buffer)
2891   "Insert BUFFER into the current buffer and quote it."
2892   (interactive "bYank buffer: ")
2893   (let ((message-reply-buffer buffer))
2894     (save-window-excursion
2895       (message-yank-original))))
2896
2897 (defun message-buffers ()
2898   "Return a list of active message buffers."
2899   (let (buffers)
2900     (save-excursion
2901       (dolist (buffer (buffer-list t))
2902         (set-buffer buffer)
2903         (when (and (eq major-mode 'message-mode)
2904                    (null message-sent-message-via))
2905           (push (buffer-name buffer) buffers))))
2906     (nreverse buffers)))
2907
2908 (defun message-cite-original-without-signature ()
2909   "Cite function in the standard Message manner."
2910   (let ((start (point))
2911         (end (mark t))
2912         (functions
2913          (when message-indent-citation-function
2914            (if (listp message-indent-citation-function)
2915                message-indent-citation-function
2916              (list message-indent-citation-function)))))
2917     (mml-quote-region start end)
2918     ;; Allow undoing.
2919     (undo-boundary)
2920     (goto-char end)
2921     (when (re-search-backward message-signature-separator start t)
2922       ;; Also peel off any blank lines before the signature.
2923       (forward-line -1)
2924       (while (looking-at "^[ \t]*$")
2925         (forward-line -1))
2926       (forward-line 1)
2927       (delete-region (point) end)
2928       (unless (search-backward "\n\n" start t)
2929         ;; Insert a blank line if it is peeled off.
2930         (insert "\n")))
2931     (goto-char start)
2932     (while functions
2933       (funcall (pop functions)))
2934     (when message-citation-line-function
2935       (unless (bolp)
2936         (insert "\n"))
2937       (funcall message-citation-line-function))))
2938
2939 (eval-when-compile (defvar mail-citation-hook)) ;Compiler directive
2940 (defun message-cite-original ()
2941   "Cite function in the standard Message manner."
2942   (if (and (boundp 'mail-citation-hook)
2943            mail-citation-hook)
2944       (run-hooks 'mail-citation-hook)
2945     (let ((start (point))
2946           (end (mark t))
2947           (functions
2948            (when message-indent-citation-function
2949              (if (listp message-indent-citation-function)
2950                  message-indent-citation-function
2951                (list message-indent-citation-function)))))
2952       (mml-quote-region start end)
2953       (goto-char start)
2954       (while functions
2955         (funcall (pop functions)))
2956       (when message-citation-line-function
2957         (unless (bolp)
2958           (insert "\n"))
2959         (funcall message-citation-line-function)))))
2960
2961 (defun message-insert-citation-line ()
2962   "Insert a simple citation line."
2963   (when message-reply-headers
2964     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
2965
2966 (defun message-position-on-field (header &rest afters)
2967   (let ((case-fold-search t))
2968     (save-restriction
2969       (narrow-to-region
2970        (goto-char (point-min))
2971        (progn
2972          (re-search-forward
2973           (concat "^" (regexp-quote mail-header-separator) "$"))
2974          (match-beginning 0)))
2975       (goto-char (point-min))
2976       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
2977           (progn
2978             (re-search-forward "^[^ \t]" nil 'move)
2979             (beginning-of-line)
2980             (skip-chars-backward "\n")
2981             t)
2982         (while (and afters
2983                     (not (re-search-forward
2984                           (concat "^" (regexp-quote (car afters)) ":")
2985                           nil t)))
2986           (pop afters))
2987         (when afters
2988           (re-search-forward "^[^ \t]" nil 'move)
2989           (beginning-of-line))
2990         (insert header ": \n")
2991         (forward-char -1)
2992         nil))))
2993
2994 (defun message-remove-signature ()
2995   "Remove the signature from the text between point and mark.
2996 The text will also be indented the normal way."
2997   (save-excursion
2998     (let ((start (point))
2999           mark)
3000       (if (not (re-search-forward message-signature-separator (mark t) t))
3001           ;; No signature here, so we just indent the cited text.
3002           (message-indent-citation)
3003         ;; Find the last non-empty line.
3004         (forward-line -1)
3005         (while (looking-at "[ \t]*$")
3006           (forward-line -1))
3007         (forward-line 1)
3008         (setq mark (set-marker (make-marker) (point)))
3009         (goto-char start)
3010         (message-indent-citation)
3011         ;; Enable undoing the deletion.
3012         (undo-boundary)
3013         (delete-region mark (mark t))
3014         (set-marker mark nil)))))
3015
3016 \f
3017
3018 ;;;
3019 ;;; Sending messages
3020 ;;;
3021
3022 (defun message-send-and-exit (&optional arg)
3023   "Send message like `message-send', then, if no errors, exit from mail buffer."
3024   (interactive "P")
3025   (let ((buf (current-buffer))
3026         (actions message-exit-actions))
3027     (when (and (message-send arg)
3028                (buffer-name buf))
3029       (if message-kill-buffer-on-exit
3030           (kill-buffer buf)
3031         (bury-buffer buf)
3032         (when (eq buf (current-buffer))
3033           (message-bury buf)))
3034       (message-do-actions actions)
3035       t)))
3036
3037 (defun message-dont-send ()
3038   "Don't send the message you have been editing.
3039 Instead, just auto-save the buffer and then bury it."
3040   (interactive)
3041   (set-buffer-modified-p t)
3042   (save-buffer)
3043   (let ((actions message-postpone-actions))
3044     (message-bury (current-buffer))
3045     (message-do-actions actions)))
3046
3047 (defun message-kill-buffer ()
3048   "Kill the current buffer."
3049   (interactive)
3050   (when (or (not (buffer-modified-p))
3051             (yes-or-no-p "Message modified; kill anyway? "))
3052     (let ((actions message-kill-actions)
3053           (draft-article message-draft-article)
3054           (auto-save-file-name buffer-auto-save-file-name)
3055           (file-name buffer-file-name)
3056           (modified (buffer-modified-p)))
3057       (setq buffer-file-name nil)
3058       (kill-buffer (current-buffer))
3059       (when (and (or (and auto-save-file-name
3060                           (file-exists-p auto-save-file-name))
3061                      (and file-name
3062                           (file-exists-p file-name)))
3063                (yes-or-no-p (format "Remove the backup file%s? "
3064                                     (if modified " too" ""))))
3065         (ignore-errors
3066           (delete-file auto-save-file-name))
3067         (let ((message-draft-article draft-article))
3068           (message-disassociate-draft)))
3069       (message-do-actions actions))))
3070
3071 (defun message-bury (buffer)
3072   "Bury this mail BUFFER."
3073   (let ((newbuf (other-buffer buffer)))
3074     (bury-buffer buffer)
3075     (if (and (fboundp 'frame-parameters)
3076              (cdr (assq 'dedicated (frame-parameters)))
3077              (not (null (delq (selected-frame) (visible-frame-list)))))
3078         (delete-frame (selected-frame))
3079       (switch-to-buffer newbuf))))
3080
3081 (defun message-send (&optional arg)
3082   "Send the message in the current buffer.
3083 If `message-interactive' is non-nil, wait for success indication or
3084 error messages, and inform user.
3085 Otherwise any failure is reported in a message back to the user from
3086 the mailer.
3087 The usage of ARG is defined by the instance that called Message.
3088 It should typically alter the sending method in some way or other."
3089   (interactive "P")
3090   ;; Make it possible to undo the coming changes.
3091   (undo-boundary)
3092   (let ((inhibit-read-only t))
3093     (put-text-property (point-min) (point-max) 'read-only nil))
3094   (message-fix-before-sending)
3095   (run-hooks 'message-send-hook)
3096   (message message-sending-message)
3097   (let ((alist message-send-method-alist)
3098         (success t)
3099         elem sent dont-barf-on-no-method
3100         (message-options message-options))
3101     (message-options-set-recipient)
3102     (while (and success
3103                 (setq elem (pop alist)))
3104       (when (funcall (cadr elem))
3105         (when (and (or (not (memq (car elem)
3106                                   message-sent-message-via))
3107                        (if (or (message-gnksa-enable-p 'multiple-copies)
3108                                (not (eq (car elem) 'news)))
3109                            (y-or-n-p
3110                             (format
3111                              "Already sent message via %s; resend? "
3112                              (car elem)))
3113                          (error "Denied posting -- multiple copies")))
3114                    (setq success (funcall (caddr elem) arg)))
3115           (setq sent t))))
3116     (unless (or sent
3117                 (not success)
3118                 (let ((fcc (message-fetch-field "Fcc"))
3119                       (gcc (message-fetch-field "Gcc")))
3120                   (when (or fcc gcc)
3121                     (or (eq message-allow-no-recipients 'always)
3122                         (and (not (eq message-allow-no-recipients 'never))
3123                              (setq dont-barf-on-no-method
3124                                    (gnus-y-or-n-p
3125                                     (format "No receiver, perform %s anyway? "
3126                                             (cond ((and fcc gcc) "Fcc and Gcc")
3127                                                   (fcc "Fcc")
3128                                                   (t "Gcc"))))))))))
3129       (error "No methods specified to send by"))
3130     (when (or dont-barf-on-no-method
3131               (and success sent))
3132       (message-do-fcc)
3133       (save-excursion
3134         (run-hooks 'message-sent-hook))
3135       (message "Sending...done")
3136       ;; Mark the buffer as unmodified and delete auto-save.
3137       (set-buffer-modified-p nil)
3138       (delete-auto-save-file-if-necessary t)
3139       (message-disassociate-draft)
3140       ;; Delete other mail buffers and stuff.
3141       (message-do-send-housekeeping)
3142       (message-do-actions message-send-actions)
3143       ;; Return success.
3144       t)))
3145
3146 (defun message-send-via-mail (arg)
3147   "Send the current message via mail."
3148   (message-send-mail arg))
3149
3150 (defun message-send-via-news (arg)
3151   "Send the current message via news."
3152   (funcall message-send-news-function arg))
3153
3154 (defmacro message-check (type &rest forms)
3155   "Eval FORMS if TYPE is to be checked."
3156   `(or (message-check-element ,type)
3157        (save-excursion
3158          ,@forms)))
3159
3160 (put 'message-check 'lisp-indent-function 1)
3161 (put 'message-check 'edebug-form-spec '(form body))
3162
3163 (defun message-text-with-property (prop)
3164   "Return a list of all points where the text has PROP."
3165   (let ((points nil)
3166         (point (point-min)))
3167     (save-excursion
3168       (while (< point (point-max))
3169         (when (get-text-property point prop)
3170           (push point points))
3171         (incf point)))
3172     (nreverse points)))
3173
3174 (defun message-fix-before-sending ()
3175   "Do various things to make the message nice before sending it."
3176   ;; Make sure there's a newline at the end of the message.
3177   (goto-char (point-max))
3178   (unless (bolp)
3179     (insert "\n"))
3180   ;; Delete all invisible text.
3181   (message-check 'invisible-text
3182     (let ((points (message-text-with-property 'invisible)))
3183       (when points
3184         (goto-char (car points))
3185         (dolist (point points)
3186           (add-text-properties point (1+ point)
3187                                '(invisible nil highlight t)))
3188         (unless (yes-or-no-p
3189                  "Invisible text found and made visible; continue posting? ")
3190           (error "Invisible text found and made visible")))))
3191   (message-check 'illegible-text
3192     (let (found choice)
3193       (message-goto-body)
3194       (skip-chars-forward mm-7bit-chars)
3195       (while (not (eobp))
3196         (when (let ((char (char-after)))
3197                 (or (< (mm-char-int char) 128)
3198                     (and (mm-multibyte-p)
3199                          (memq (char-charset char)
3200                                '(eight-bit-control eight-bit-graphic 
3201                                                    control-1)))))
3202           (add-text-properties (point) (1+ (point)) '(highlight t))
3203           (setq found t))
3204         (forward-char)
3205         (skip-chars-forward mm-7bit-chars))
3206       (when found
3207         (setq choice
3208               (gnus-multiple-choice 
3209                "Illegible text found. Continue posting? "
3210                '((?d "Remove and continue posting")
3211                  (?r "Replace with dots and continue posting")
3212                  (?i "Ignore and continue posting")
3213                  (?e "Continue editing"))))
3214         (if (eq choice ?e)
3215           (error "Illegible text found"))
3216         (message-goto-body)
3217         (skip-chars-forward mm-7bit-chars)
3218         (while (not (eobp))
3219           (when (let ((char (char-after)))
3220                   (or (< (mm-char-int char) 128)
3221                       (and (mm-multibyte-p)
3222                            (memq (char-charset char)
3223                                  '(eight-bit-control eight-bit-graphic
3224                                                      control-1)))))
3225             (if (eq choice ?i)
3226                 (remove-text-properties (point) (1+ (point)) '(highlight t))
3227               (delete-char 1)
3228               (if (eq choice ?r)
3229                   (insert "."))))
3230           (forward-char)
3231           (skip-chars-forward mm-7bit-chars))))))
3232
3233 (defun message-add-action (action &rest types)
3234   "Add ACTION to be performed when doing an exit of type TYPES."
3235   (while types
3236     (add-to-list (intern (format "message-%s-actions" (pop types)))
3237                  action)))
3238
3239 (defun message-delete-action (action &rest types)
3240   "Delete ACTION from lists of actions performed when doing an exit of type TYPES."
3241   (let (var)
3242     (while types
3243       (set (setq var (intern (format "message-%s-actions" (pop types))))
3244            (delq action (symbol-value var))))))
3245
3246 (defun message-do-actions (actions)
3247   "Perform all actions in ACTIONS."
3248   ;; Now perform actions on successful sending.
3249   (while actions
3250     (ignore-errors
3251       (cond
3252        ;; A simple function.
3253        ((message-functionp (car actions))
3254         (funcall (car actions)))
3255        ;; Something to be evaled.
3256        (t
3257         (eval (car actions)))))
3258     (pop actions)))
3259
3260 (defun message-send-mail-partially ()
3261   "Send mail as message/partial."
3262   ;; replace the header delimiter with a blank line
3263   (goto-char (point-min))
3264   (re-search-forward
3265    (concat "^" (regexp-quote mail-header-separator) "\n"))
3266   (replace-match "\n")
3267   (run-hooks 'message-send-mail-hook)
3268   (let ((p (goto-char (point-min)))
3269         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
3270         (curbuf (current-buffer))
3271         (id (message-make-message-id)) (n 1)
3272         plist total  header required-mail-headers)
3273     (while (not (eobp))
3274       (if (< (point-max) (+ p message-send-mail-partially-limit))
3275           (goto-char (point-max))
3276         (goto-char (+ p message-send-mail-partially-limit))
3277         (beginning-of-line)
3278         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
3279       (push p plist)
3280       (setq p (point)))
3281     (setq total (length plist))
3282     (push (point-max) plist)
3283     (setq plist (nreverse plist))
3284     (unwind-protect
3285         (save-excursion
3286           (setq p (pop plist))
3287           (while plist
3288             (set-buffer curbuf)
3289             (copy-to-buffer tembuf p (car plist))
3290             (set-buffer tembuf)
3291             (goto-char (point-min))
3292             (if header
3293                 (progn
3294                   (goto-char (point-min))
3295                   (narrow-to-region (point) (point))
3296                   (insert header))
3297               (message-goto-eoh)
3298               (setq header (buffer-substring (point-min) (point)))
3299               (goto-char (point-min))
3300               (narrow-to-region (point) (point))
3301               (insert header)
3302               (message-remove-header "Mime-Version")
3303               (message-remove-header "Content-Type")
3304               (message-remove-header "Content-Transfer-Encoding")
3305               (message-remove-header "Message-ID")
3306               (message-remove-header "Lines")
3307               (goto-char (point-max))
3308               (insert "Mime-Version: 1.0\n")
3309               (setq header (buffer-substring (point-min) (point-max))))
3310             (goto-char (point-max))
3311             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
3312                             id n total))
3313             (forward-char -1)
3314             (let ((mail-header-separator ""))
3315               (when (memq 'Message-ID message-required-mail-headers)
3316                 (insert "Message-ID: " (message-make-message-id) "\n"))
3317               (when (memq 'Lines message-required-mail-headers)
3318                 (insert "Lines: " (message-make-lines) "\n"))
3319               (message-goto-subject)
3320               (end-of-line)
3321               (insert (format " (%d/%d)" n total))
3322               (widen)
3323               (mm-with-unibyte-current-buffer
3324                 (funcall (or message-send-mail-real-function
3325                              message-send-mail-function))))
3326             (setq n (+ n 1))
3327             (setq p (pop plist))
3328             (erase-buffer)))
3329       (kill-buffer tembuf))))
3330
3331 (defun message-send-mail (&optional arg)
3332   (require 'mail-utils)
3333   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
3334          (case-fold-search nil)
3335          (news (message-news-p))
3336          (mailbuf (current-buffer))
3337          (message-this-is-mail t)
3338          (message-posting-charset
3339           (if (fboundp 'gnus-setup-posting-charset)
3340               (gnus-setup-posting-charset nil)
3341             message-posting-charset))
3342          (headers message-required-mail-headers))
3343     (save-restriction
3344       (message-narrow-to-headers)
3345       ;; Generate the Mail-Followup-To header if the header is not there...
3346       (if (and (or message-subscribed-regexps
3347                    message-subscribed-addresses
3348                    message-subscribed-address-file
3349                    message-subscribed-address-functions)
3350                (not (mail-fetch-field "mail-followup-to")))
3351           (setq headers
3352                 (cons
3353                  (cons "Mail-Followup-To" (message-make-mft))
3354                  message-required-mail-headers))
3355         ;; otherwise, delete the MFT header if the field is empty
3356         (when (equal "" (mail-fetch-field "mail-followup-to"))
3357           (message-remove-header "^Mail-Followup-To:")))
3358       ;; Insert some headers.
3359       (let ((message-deletable-headers
3360              (if news nil message-deletable-headers)))
3361         (message-generate-headers headers))
3362       ;; Let the user do all of the above.
3363       (run-hooks 'message-header-hook))
3364     (unwind-protect
3365         (save-excursion
3366           (set-buffer tembuf)
3367           (erase-buffer)
3368           ;; Avoid copying text props (except hard newlines).
3369           (insert (with-current-buffer mailbuf
3370                     (mml-buffer-substring-no-properties-except-hard-newlines
3371                      (point-min) (point-max))))
3372           ;; Remove some headers.
3373           (message-encode-message-body)
3374           (save-restriction
3375             (message-narrow-to-headers)
3376             ;; We (re)generate the Lines header.
3377             (when (memq 'Lines message-required-mail-headers)
3378               (message-generate-headers '(Lines)))
3379             ;; Remove some headers.
3380             (message-remove-header message-ignored-mail-headers t)
3381             (let ((mail-parse-charset message-default-charset))
3382               (mail-encode-encoded-word-buffer)))
3383           (goto-char (point-max))
3384           ;; require one newline at the end.
3385           (or (= (preceding-char) ?\n)
3386               (insert ?\n))
3387           (when
3388               (save-restriction
3389                 (message-narrow-to-headers)
3390                 (and news
3391                      (or (message-fetch-field "cc")
3392                          (message-fetch-field "to"))
3393                      (let ((content-type (message-fetch-field "content-type")))
3394                        (or
3395                         (not content-type)
3396                         (string= "text/plain"
3397                                  (car
3398                                   (mail-header-parse-content-type
3399                                    content-type)))))))
3400             (message-insert-courtesy-copy))
3401           (if (or (not message-send-mail-partially-limit)
3402                   (< (point-max) message-send-mail-partially-limit)
3403                   (not (message-y-or-n-p
3404                         "The message size is too large, split? "
3405                         t
3406                         "\
3407 The message size, "
3408                         (/ (point-max) 1000) "KB, is too large.
3409
3410 Some mail gateways (MTA's) bounce large messages.  To avoid the
3411 problem, answer `y', and the message will be split into several
3412 smaller pieces, the size of each is about "
3413                         (/ message-send-mail-partially-limit 1000)
3414                         "KB except the last
3415 one.
3416
3417 However, some mail readers (MUA's) can't read split messages, i.e.,
3418 mails in message/partially format. Answer `n', and the message will be
3419 sent in one piece.
3420
3421 The size limit is controlled by `message-send-mail-partially-limit'.
3422 If you always want Gnus to send messages in one piece, set
3423 `message-send-mail-partially-limit' to `nil'.
3424 ")))
3425               (mm-with-unibyte-current-buffer
3426                 (message "Sending via mail...")
3427                 (funcall (or message-send-mail-real-function
3428                              message-send-mail-function)))
3429             (message-send-mail-partially)))
3430       (kill-buffer tembuf))
3431     (set-buffer mailbuf)
3432     (push 'mail message-sent-message-via)))
3433
3434 (defun message-send-mail-with-sendmail ()
3435   "Send off the prepared buffer with sendmail."
3436   (let ((errbuf (if message-interactive
3437                     (message-generate-new-buffer-clone-locals
3438                      " sendmail errors")
3439                   0))
3440         resend-to-addresses delimline)
3441     (unwind-protect
3442         (progn
3443           (let ((case-fold-search t))
3444             (save-restriction
3445               (message-narrow-to-headers)
3446               (setq resend-to-addresses (message-fetch-field "resent-to")))
3447             ;; Change header-delimiter to be what sendmail expects.
3448             (goto-char (point-min))
3449             (re-search-forward
3450              (concat "^" (regexp-quote mail-header-separator) "\n"))
3451             (replace-match "\n")
3452             (backward-char 1)
3453             (setq delimline (point-marker))
3454             (run-hooks 'message-send-mail-hook)
3455             ;; Insert an extra newline if we need it to work around
3456             ;; Sun's bug that swallows newlines.
3457             (goto-char (1+ delimline))
3458             (when (eval message-mailer-swallows-blank-line)
3459               (newline))
3460             (when message-interactive
3461               (save-excursion
3462                 (set-buffer errbuf)
3463                 (erase-buffer))))
3464           (let* ((default-directory "/")
3465                  (coding-system-for-write message-send-coding-system)
3466                  (cpr (apply
3467                        'call-process-region
3468                        (append
3469                         (list (point-min) (point-max)
3470                               (if (boundp 'sendmail-program)
3471                                   sendmail-program
3472                                 "/usr/lib/sendmail")
3473                               nil errbuf nil "-oi")
3474                         ;; Always specify who from,
3475                         ;; since some systems have broken sendmails.
3476                         ;; But some systems are more broken with -f, so
3477                         ;; we'll let users override this.
3478                         (if (null message-sendmail-f-is-evil)
3479                             (list "-f" (message-make-address)))
3480                         ;; These mean "report errors by mail"
3481                         ;; and "deliver in background".
3482                         (if (null message-interactive) '("-oem" "-odb"))
3483                         ;; Get the addresses from the message
3484                         ;; unless this is a resend.
3485                         ;; We must not do that for a resend
3486                         ;; because we would find the original addresses.
3487                         ;; For a resend, include the specific addresses.
3488                         (if resend-to-addresses
3489                             (list resend-to-addresses)
3490                           '("-t"))))))
3491             (unless (or (null cpr) (zerop cpr))
3492               (error "Sending...failed with exit value %d" cpr)))
3493           (when message-interactive
3494             (save-excursion
3495               (set-buffer errbuf)
3496               (goto-char (point-min))
3497               (while (re-search-forward "\n\n* *" nil t)
3498                 (replace-match "; "))
3499               (if (not (zerop (buffer-size)))
3500                   (error "Sending...failed to %s"
3501                          (buffer-substring (point-min) (point-max)))))))
3502       (when (bufferp errbuf)
3503         (kill-buffer errbuf)))))
3504
3505 (defun message-send-mail-with-qmail ()
3506   "Pass the prepared message buffer to qmail-inject.
3507 Refer to the documentation for the variable `message-send-mail-function'
3508 to find out how to use this."
3509   ;; replace the header delimiter with a blank line
3510   (goto-char (point-min))
3511   (re-search-forward
3512    (concat "^" (regexp-quote mail-header-separator) "\n"))
3513   (replace-match "\n")
3514   (run-hooks 'message-send-mail-hook)
3515   ;; send the message
3516   (case
3517       (let ((coding-system-for-write message-send-coding-system))
3518         (apply
3519          'call-process-region 1 (point-max) message-qmail-inject-program
3520          nil nil nil
3521          ;; qmail-inject's default behaviour is to look for addresses on the
3522          ;; command line; if there're none, it scans the headers.
3523          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
3524          ;;
3525          ;; in general, ALL of qmail-inject's defaults are perfect for simply
3526          ;; reading a formatted (i. e., at least a To: or Resent-To header)
3527          ;; message from stdin.
3528          ;;
3529          ;; qmail also has the advantage of not having been raped by
3530          ;; various vendors, so we don't have to allow for that, either --
3531          ;; compare this with message-send-mail-with-sendmail and weep
3532          ;; for sendmail's lost innocence.
3533          ;;
3534          ;; all this is way cool coz it lets us keep the arguments entirely
3535          ;; free for -inject-arguments -- a big win for the user and for us
3536          ;; since we don't have to play that double-guessing game and the user
3537          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
3538          (if (message-functionp message-qmail-inject-args)
3539              (funcall message-qmail-inject-args)
3540            message-qmail-inject-args)))
3541     ;; qmail-inject doesn't say anything on it's stdout/stderr,
3542     ;; we have to look at the retval instead
3543     (0 nil)
3544     (100 (error "qmail-inject reported permanent failure"))
3545     (111 (error "qmail-inject reported transient failure"))
3546     ;; should never happen
3547     (t   (error "qmail-inject reported unknown failure"))))
3548
3549 (defun message-send-mail-with-mh ()
3550   "Send the prepared message buffer with mh."
3551   (let ((mh-previous-window-config nil)
3552         (name (mh-new-draft-name)))
3553     (setq buffer-file-name name)
3554     ;; MH wants to generate these headers itself.
3555     (when message-mh-deletable-headers
3556       (let ((headers message-mh-deletable-headers))
3557         (while headers
3558           (goto-char (point-min))
3559           (and (re-search-forward
3560                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3561                (message-delete-line))
3562           (pop headers))))
3563     (run-hooks 'message-send-mail-hook)
3564     ;; Pass it on to mh.
3565     (mh-send-letter)))
3566
3567 (defun message-smtpmail-send-it ()
3568   "Send the prepared message buffer with `smtpmail-send-it'.
3569 This only differs from `smtpmail-send-it' that this command evaluates
3570 `message-send-mail-hook' just before sending a message.  It is useful
3571 if your ISP requires the POP-before-SMTP authentication.  See the
3572 documentation for the function `mail-source-touch-pop'."
3573   (run-hooks 'message-send-mail-hook)
3574   (smtpmail-send-it))
3575
3576 (defun message-canlock-generate ()
3577   "Return a string that is non-trival to guess.
3578 Do not use this for anything important, it is cryptographically weak."
3579   (let (sha1-maximum-internal-length)
3580     (sha1 (concat (message-unique-id)
3581                   (format "%x%x%x" (random) (random t) (random))
3582                   (prin1-to-string (recent-keys))
3583                   (prin1-to-string (garbage-collect))))))
3584
3585 (defun message-canlock-password ()
3586   "The password used by message for cancel locks.
3587 This is the value of `canlock-password', if that option is non-nil.
3588 Otherwise, generate and save a value for `canlock-password' first."
3589   (unless canlock-password
3590     (customize-save-variable 'canlock-password (message-canlock-generate))
3591     (setq canlock-password-for-verify canlock-password))
3592   canlock-password)
3593
3594 (defun message-insert-canlock ()
3595   (when message-insert-canlock
3596     (message-canlock-password)
3597     (canlock-insert-header)))
3598
3599 (defun message-send-news (&optional arg)
3600   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
3601          (case-fold-search nil)
3602          (method (if (message-functionp message-post-method)
3603                      (funcall message-post-method arg)
3604                    message-post-method))
3605          (newsgroups-field (save-restriction
3606                             (message-narrow-to-headers-or-head)
3607                             (message-fetch-field "Newsgroups")))
3608          (followup-field (save-restriction
3609                            (message-narrow-to-headers-or-head)
3610                            (message-fetch-field "Followup-To")))
3611          ;; BUG: We really need to get the charset for each name in the
3612          ;; Newsgroups and Followup-To lines to allow crossposting
3613          ;; between group namess with incompatible character sets.
3614          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
3615          (group-field-charset
3616           (gnus-group-name-charset method newsgroups-field))
3617          (followup-field-charset
3618           (gnus-group-name-charset method (or followup-field "")))
3619          (rfc2047-header-encoding-alist
3620           (append (when group-field-charset
3621                     (list (cons "Newsgroups" group-field-charset)))
3622                   (when followup-field-charset
3623                     (list (cons "Followup-To" followup-field-charset)))
3624                   rfc2047-header-encoding-alist))
3625          (messbuf (current-buffer))
3626          (message-syntax-checks
3627           (if (and arg
3628                    (listp message-syntax-checks))
3629               (cons '(existing-newsgroups . disabled)
3630                     message-syntax-checks)
3631             message-syntax-checks))
3632          (message-this-is-news t)
3633          (message-posting-charset
3634           (gnus-setup-posting-charset newsgroups-field))
3635          result)
3636     (if (not (message-check-news-body-syntax))
3637         nil
3638       (save-restriction
3639         (message-narrow-to-headers)
3640         ;; Insert some headers.
3641         (message-generate-headers message-required-news-headers)
3642         (message-insert-canlock)
3643         ;; Let the user do all of the above.
3644         (run-hooks 'message-header-hook))
3645       ;; Note: This check will be disabled by the ".*" default value for
3646       ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
3647       (when (and group-field-charset
3648                  (listp message-syntax-checks))
3649         (setq message-syntax-checks
3650               (cons '(valid-newsgroups . disabled)
3651                     message-syntax-checks)))
3652       (message-cleanup-headers)
3653       (if (not (let ((message-post-method method))
3654                  (message-check-news-syntax)))
3655           nil
3656         (unwind-protect
3657             (save-excursion
3658               (set-buffer tembuf)
3659               (buffer-disable-undo)
3660               (erase-buffer)
3661               ;; Avoid copying text props (except hard newlines).
3662               (insert
3663                (with-current-buffer messbuf
3664                  (mml-buffer-substring-no-properties-except-hard-newlines
3665                   (point-min) (point-max))))
3666               (message-encode-message-body)
3667               ;; Remove some headers.
3668               (save-restriction
3669                 (message-narrow-to-headers)
3670                 ;; We (re)generate the Lines header.
3671                 (when (memq 'Lines message-required-mail-headers)
3672                   (message-generate-headers '(Lines)))
3673                 ;; Remove some headers.
3674                 (message-remove-header message-ignored-news-headers t)
3675                 (let ((mail-parse-charset message-default-charset))
3676                   (mail-encode-encoded-word-buffer)))
3677               (goto-char (point-max))
3678               ;; require one newline at the end.
3679               (or (= (preceding-char) ?\n)
3680                   (insert ?\n))
3681               (let ((case-fold-search t))
3682                 ;; Remove the delimiter.
3683                 (goto-char (point-min))
3684                 (re-search-forward
3685                  (concat "^" (regexp-quote mail-header-separator) "\n"))
3686                 (replace-match "\n")
3687                 (backward-char 1))
3688               (run-hooks 'message-send-news-hook)
3689               (gnus-open-server method)
3690               (message "Sending news via %s..." (gnus-server-string method))
3691               (setq result (let ((mail-header-separator ""))
3692                              (gnus-request-post method))))
3693           (kill-buffer tembuf))
3694         (set-buffer messbuf)
3695         (if result
3696             (push 'news message-sent-message-via)
3697           (message "Couldn't send message via news: %s"
3698                    (nnheader-get-report (car method)))
3699           nil)))))
3700
3701 ;;;
3702 ;;; Header generation & syntax checking.
3703 ;;;
3704
3705 (defun message-check-element (type)
3706   "Return non-nil if this TYPE is not to be checked."
3707   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
3708       t
3709     (let ((able (assq type message-syntax-checks)))
3710       (and (consp able)
3711            (eq (cdr able) 'disabled)))))
3712
3713 (defun message-check-news-syntax ()
3714   "Check the syntax of the message."
3715   (save-excursion
3716     (save-restriction
3717       (widen)
3718       ;; We narrow to the headers and check them first.
3719       (save-excursion
3720         (save-restriction
3721           (message-narrow-to-headers)
3722           (message-check-news-header-syntax))))))
3723
3724 (defun message-check-news-header-syntax ()
3725   (and
3726    ;; Check Newsgroups header.
3727    (message-check 'newsgroups
3728      (let ((group (message-fetch-field "newsgroups")))
3729        (or
3730         (and group
3731              (not (string-match "\\`[ \t]*\\'" group)))
3732         (ignore
3733          (message
3734           "The newsgroups field is empty or missing.  Posting is denied.")))))
3735    ;; Check the Subject header.
3736    (message-check 'subject
3737      (let* ((case-fold-search t)
3738             (subject (message-fetch-field "subject")))
3739        (or
3740         (and subject
3741              (not (string-match "\\`[ \t]*\\'" subject)))
3742         (ignore
3743          (message
3744           "The subject field is empty or missing.  Posting is denied.")))))
3745    ;; Check for commands in Subject.
3746    (message-check 'subject-cmsg
3747      (if (string-match "^cmsg " (message-fetch-field "subject"))
3748          (y-or-n-p
3749           "The control code \"cmsg\" is in the subject.  Really post? ")
3750        t))
3751    ;; Check for multiple identical headers.
3752    (message-check 'multiple-headers
3753      (let (found)
3754        (while (and (not found)
3755                    (re-search-forward "^[^ \t:]+: " nil t))
3756          (save-excursion
3757            (or (re-search-forward
3758                 (concat "^"
3759                         (regexp-quote
3760                          (setq found
3761                                (buffer-substring
3762                                 (match-beginning 0) (- (match-end 0) 2))))
3763                         ":")
3764                 nil t)
3765                (setq found nil))))
3766        (if found
3767            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
3768          t)))
3769    ;; Check for Version and Sendsys.
3770    (message-check 'sendsys
3771      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
3772          (y-or-n-p
3773           (format "The article contains a %s command.  Really post? "
3774                   (buffer-substring (match-beginning 0)
3775                                     (1- (match-end 0)))))
3776        t))
3777    ;; See whether we can shorten Followup-To.
3778    (message-check 'shorten-followup-to
3779      (let ((newsgroups (message-fetch-field "newsgroups"))
3780            (followup-to (message-fetch-field "followup-to"))
3781            to)
3782        (when (and newsgroups
3783                   (string-match "," newsgroups)
3784                   (not followup-to)
3785                   (not
3786                    (zerop
3787                     (length
3788                      (setq to (completing-read
3789                                "Followups to (default: no Followup-To header) "
3790                                (mapcar (lambda (g) (list g))
3791                                        (cons "poster"
3792                                              (message-tokenize-header
3793                                               newsgroups)))))))))
3794          (goto-char (point-min))
3795          (insert "Followup-To: " to "\n"))
3796        t))
3797    ;; Check "Shoot me".
3798    (message-check 'shoot
3799      (if (re-search-forward
3800           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
3801          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
3802        t))
3803    ;; Check for Approved.
3804    (message-check 'approved
3805      (if (re-search-forward "^Approved:" nil t)
3806          (y-or-n-p "The article contains an Approved header.  Really post? ")
3807        t))
3808    ;; Check the Message-ID header.
3809    (message-check 'message-id
3810      (let* ((case-fold-search t)
3811             (message-id (message-fetch-field "message-id" t)))
3812        (or (not message-id)
3813            ;; Is there an @ in the ID?
3814            (and (string-match "@" message-id)
3815                 ;; Is there a dot in the ID?
3816                 (string-match "@[^.]*\\." message-id)
3817                 ;; Does the ID end with a dot?
3818                 (not (string-match "\\.>" message-id)))
3819            (y-or-n-p
3820             (format "The Message-ID looks strange: \"%s\".  Really post? "
3821                     message-id)))))
3822    ;; Check the Newsgroups & Followup-To headers.
3823    (message-check 'existing-newsgroups
3824      (let* ((case-fold-search t)
3825             (newsgroups (message-fetch-field "newsgroups"))
3826             (followup-to (message-fetch-field "followup-to"))
3827             (groups (message-tokenize-header
3828                      (if followup-to
3829                          (concat newsgroups "," followup-to)
3830                        newsgroups)))
3831             (post-method (if (message-functionp message-post-method)
3832                              (funcall message-post-method)
3833                            message-post-method))
3834             ;; KLUDGE to handle nnvirtual groups.  Doing this right
3835             ;; would probably involve a new nnoo function.
3836             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
3837             (method (if (and (consp post-method)
3838                              (eq (car post-method) 'nnvirtual)
3839                              gnus-message-group-art)
3840                         (let ((group (car (nnvirtual-find-group-art
3841                                            (car gnus-message-group-art)
3842                                            (cdr gnus-message-group-art)))))
3843                           (gnus-find-method-for-group group))
3844                       post-method))
3845             (known-groups
3846              (mapcar (lambda (n)
3847                        (gnus-group-name-decode
3848                         (gnus-group-real-name n)
3849                         (gnus-group-name-charset method n)))
3850                      (gnus-groups-from-server method)))
3851             errors)
3852        (while groups
3853          (unless (or (equal (car groups) "poster")
3854                      (member (car groups) known-groups))
3855            (push (car groups) errors))
3856          (pop groups))
3857        (cond
3858         ;; Gnus is not running.
3859         ((or (not (and (boundp 'gnus-active-hashtb)
3860                        gnus-active-hashtb))
3861              (not (boundp 'gnus-read-active-file)))
3862          t)
3863         ;; We don't have all the group names.
3864         ((and (or (not gnus-read-active-file)
3865                   (eq gnus-read-active-file 'some))
3866               errors)
3867          (y-or-n-p
3868           (format
3869            "Really post to %s possibly unknown group%s: %s? "
3870            (if (= (length errors) 1) "this" "these")
3871            (if (= (length errors) 1) "" "s")
3872            (mapconcat 'identity errors ", "))))
3873         ;; There were no errors.
3874         ((not errors)
3875          t)
3876         ;; There are unknown groups.
3877         (t
3878          (y-or-n-p
3879           (format
3880            "Really post to %s unknown group%s: %s? "
3881            (if (= (length errors) 1) "this" "these")
3882            (if (= (length errors) 1) "" "s")
3883            (mapconcat 'identity errors ", ")))))))
3884    ;; Check the Newsgroups & Followup-To headers for syntax errors.
3885    (message-check 'valid-newsgroups
3886      (let ((case-fold-search t)
3887            (headers '("Newsgroups" "Followup-To"))
3888            header error)
3889        (while (and headers (not error))
3890          (when (setq header (mail-fetch-field (car headers)))
3891            (if (or
3892                 (not
3893                  (string-match
3894                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
3895                   header))
3896                 (memq
3897                  nil (mapcar
3898                       (lambda (g)
3899                         (not (string-match "\\.\\'\\|\\.\\." g)))
3900                       (message-tokenize-header header ","))))
3901                (setq error t)))
3902          (unless error
3903            (pop headers)))
3904        (if (not error)
3905            t
3906          (y-or-n-p
3907           (format "The %s header looks odd: \"%s\".  Really post? "
3908                   (car headers) header)))))
3909    (message-check 'repeated-newsgroups
3910      (let ((case-fold-search t)
3911            (headers '("Newsgroups" "Followup-To"))
3912            header error groups group)
3913        (while (and headers
3914                    (not error))
3915          (when (setq header (mail-fetch-field (pop headers)))
3916            (setq groups (message-tokenize-header header ","))
3917            (while (setq group (pop groups))
3918              (when (member group groups)
3919                (setq error group
3920                      groups nil)))))
3921        (if (not error)
3922            t
3923          (y-or-n-p
3924           (format "Group %s is repeated in headers.  Really post? " error)))))
3925    ;; Check the From header.
3926    (message-check 'from
3927      (let* ((case-fold-search t)
3928             (from (message-fetch-field "from"))
3929             ad)
3930        (cond
3931         ((not from)
3932          (message "There is no From line.  Posting is denied.")
3933          nil)
3934         ((or (not (string-match
3935                    "@[^\\.]*\\."
3936                    (setq ad (nth 1 (mail-extract-address-components
3937                                     from))))) ;larsi@ifi
3938              (string-match "\\.\\." ad) ;larsi@ifi..uio
3939              (string-match "@\\." ad)   ;larsi@.ifi.uio
3940              (string-match "\\.$" ad)   ;larsi@ifi.uio.
3941              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
3942              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
3943          (message
3944           "Denied posting -- the From looks strange: \"%s\"." from)
3945          nil)
3946         ((let ((addresses (rfc822-addresses from)))
3947            (while (and addresses
3948                        (not (eq (string-to-char (car addresses)) ?\()))
3949              (setq addresses (cdr addresses)))
3950            addresses)
3951          (message
3952           "Denied posting -- bad From address: \"%s\"." from)
3953          nil)
3954         (t t))))
3955    ;; Check the Reply-To header.
3956    (message-check 'reply-to
3957      (let* ((case-fold-search t)
3958             (reply-to (message-fetch-field "reply-to"))
3959             ad)
3960        (cond
3961         ((not reply-to)
3962          t)
3963         ((string-match "," reply-to)
3964          (y-or-n-p
3965           (format "Multiple Reply-To addresses: \"%s\". Really post? "
3966                   reply-to)))
3967         ((or (not (string-match
3968                    "@[^\\.]*\\."
3969                    (setq ad (nth 1 (mail-extract-address-components
3970                                     reply-to))))) ;larsi@ifi
3971              (string-match "\\.\\." ad) ;larsi@ifi..uio
3972              (string-match "@\\." ad)   ;larsi@.ifi.uio
3973              (string-match "\\.$" ad)   ;larsi@ifi.uio.
3974              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
3975              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
3976          (y-or-n-p
3977           (format
3978            "The Reply-To looks strange: \"%s\". Really post? "
3979            reply-to)))
3980         (t t))))))
3981
3982 (defun message-check-news-body-syntax ()
3983   (and
3984    ;; Check for long lines.
3985    (message-check 'long-lines
3986      (goto-char (point-min))
3987      (re-search-forward
3988       (concat "^" (regexp-quote mail-header-separator) "$"))
3989      (forward-line 1)
3990      (while (and
3991              (or (looking-at
3992                   "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)")
3993                  (let ((p (point)))
3994                    (end-of-line)
3995                    (< (- (point) p) 80)))
3996              (zerop (forward-line 1))))
3997      (or (bolp)
3998          (eobp)
3999          (y-or-n-p
4000           "You have lines longer than 79 characters.  Really post? ")))
4001    ;; Check whether the article is empty.
4002    (message-check 'empty
4003      (goto-char (point-min))
4004      (re-search-forward
4005       (concat "^" (regexp-quote mail-header-separator) "$"))
4006      (forward-line 1)
4007      (let ((b (point)))
4008        (goto-char (point-max))
4009        (re-search-backward message-signature-separator nil t)
4010        (beginning-of-line)
4011        (or (re-search-backward "[^ \n\t]" b t)
4012            (if (message-gnksa-enable-p 'empty-article)
4013                (y-or-n-p "Empty article.  Really post? ")
4014              (message "Denied posting -- Empty article.")
4015              nil))))
4016    ;; Check for control characters.
4017    (message-check 'control-chars
4018      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
4019          (y-or-n-p
4020           "The article contains control characters.  Really post? ")
4021        t))
4022    ;; Check excessive size.
4023    (message-check 'size
4024      (if (> (buffer-size) 60000)
4025          (y-or-n-p
4026           (format "The article is %d octets long.  Really post? "
4027                   (buffer-size)))
4028        t))
4029    ;; Check whether any new text has been added.
4030    (message-check 'new-text
4031      (or
4032       (not message-checksum)
4033       (not (eq (message-checksum) message-checksum))
4034       (if (message-gnksa-enable-p 'quoted-text-only)
4035           (y-or-n-p
4036            "It looks like no new text has been added.  Really post? ")
4037         (message "Denied posting -- no new text has been added.")
4038         nil)))
4039    ;; Check the length of the signature.
4040    (message-check 'signature
4041      (goto-char (point-max))
4042      (if (> (count-lines (point) (point-max)) 5)
4043          (y-or-n-p
4044           (format
4045            "Your .sig is %d lines; it should be max 4.  Really post? "
4046            (1- (count-lines (point) (point-max)))))
4047        t))
4048    ;; Ensure that text follows last quoted portion.
4049    (message-check 'quoting-style
4050      (goto-char (point-max))
4051      (let ((no-problem t))
4052        (when (search-backward-regexp "^>[^\n]*\n" nil t)
4053          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
4054        (if no-problem
4055            t
4056          (if (message-gnksa-enable-p 'quoted-text-only)
4057              (y-or-n-p "Your text should follow quoted text.  Really post? ")
4058            ;; Ensure that
4059            (goto-char (point-min))
4060            (re-search-forward
4061             (concat "^" (regexp-quote mail-header-separator) "$"))
4062            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
4063                (y-or-n-p "Your text should follow quoted text.  Really post? ")
4064              (message "Denied posting -- only quoted text.")
4065              nil)))))))
4066
4067 (defun message-checksum ()
4068   "Return a \"checksum\" for the current buffer."
4069   (let ((sum 0))
4070     (save-excursion
4071       (goto-char (point-min))
4072       (re-search-forward
4073        (concat "^" (regexp-quote mail-header-separator) "$"))
4074       (while (not (eobp))
4075         (when (not (looking-at "[ \t\n]"))
4076           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
4077                             (char-after))))
4078         (forward-char 1)))
4079     sum))
4080
4081 (defun message-do-fcc ()
4082   "Process Fcc headers in the current buffer."
4083   (let ((case-fold-search t)
4084         (buf (current-buffer))
4085         list file
4086         (mml-externalize-attachments message-fcc-externalize-attachments))
4087     (save-excursion
4088       (save-restriction
4089         (message-narrow-to-headers)
4090         (setq file (message-fetch-field "fcc" t)))
4091       (when file
4092         (set-buffer (get-buffer-create " *message temp*"))
4093         (erase-buffer)
4094         (insert-buffer-substring buf)
4095         (message-encode-message-body)
4096         (save-restriction
4097           (message-narrow-to-headers)
4098           (while (setq file (message-fetch-field "fcc" t))
4099             (push file list)
4100             (message-remove-header "fcc" nil t))
4101           (let ((mail-parse-charset message-default-charset)
4102                 (rfc2047-header-encoding-alist
4103                  (cons '("Newsgroups" . default)
4104                        rfc2047-header-encoding-alist)))
4105             (mail-encode-encoded-word-buffer)))
4106         (goto-char (point-min))
4107         (when (re-search-forward
4108                (concat "^" (regexp-quote mail-header-separator) "$")
4109                nil t)
4110           (replace-match "" t t ))
4111         ;; Process FCC operations.
4112         (while list
4113           (setq file (pop list))
4114           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
4115               ;; Pipe the article to the program in question.
4116               (call-process-region (point-min) (point-max) shell-file-name
4117                                    nil nil nil shell-command-switch
4118                                    (match-string 1 file))
4119             ;; Save the article.
4120             (setq file (expand-file-name file))
4121             (unless (file-exists-p (file-name-directory file))
4122               (make-directory (file-name-directory file) t))
4123             (if (and message-fcc-handler-function
4124                      (not (eq message-fcc-handler-function 'rmail-output)))
4125                 (funcall message-fcc-handler-function file)
4126               (if (and (file-readable-p file) (mail-file-babyl-p file))
4127                   (rmail-output file 1 nil t)
4128                 (let ((mail-use-rfc822 t))
4129                   (rmail-output file 1 t t))))))
4130         (kill-buffer (current-buffer))))))
4131
4132 (defun message-output (filename)
4133   "Append this article to Unix/babyl mail file FILENAME."
4134   (if (and (file-readable-p filename)
4135            (mail-file-babyl-p filename))
4136       (gnus-output-to-rmail filename t)
4137     (gnus-output-to-mail filename t)))
4138
4139 (defun message-cleanup-headers ()
4140   "Do various automatic cleanups of the headers."
4141   ;; Remove empty lines in the header.
4142   (save-restriction
4143     (message-narrow-to-headers)
4144     ;; Remove blank lines.
4145     (while (re-search-forward "^[ \t]*\n" nil t)
4146       (replace-match "" t t))
4147
4148     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
4149     ;; spaces to comma and eliminate spaces around commas.  Eliminate
4150     ;; embedded line breaks.
4151     (goto-char (point-min))
4152     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
4153       (save-restriction
4154         (narrow-to-region
4155          (point)
4156          (if (re-search-forward "^[^ \t]" nil t)
4157              (match-beginning 0)
4158            (forward-line 1)
4159            (point)))
4160         (goto-char (point-min))
4161         (while (re-search-forward "\n[ \t]+" nil t)
4162           (replace-match " " t t))     ;No line breaks (too confusing)
4163         (goto-char (point-min))
4164         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
4165           (replace-match "," t t))
4166         (goto-char (point-min))
4167         ;; Remove trailing commas.
4168         (when (re-search-forward ",+$" nil t)
4169           (replace-match "" t t))))))
4170
4171 (defun message-make-date (&optional now)
4172   "Make a valid data header.
4173 If NOW, use that time instead."
4174   (let* ((now (or now (current-time)))
4175          (zone (nth 8 (decode-time now)))
4176          (sign "+"))
4177     (when (< zone 0)
4178       (setq sign "-")
4179       (setq zone (- zone)))
4180     (concat
4181      ;; The day name of the %a spec is locale-specific.  Pfff.
4182      (format "%s, " (capitalize (car (rassoc (nth 6 (decode-time now))
4183                                              parse-time-weekdays))))
4184      (format-time-string "%d" now)
4185      ;; The month name of the %b spec is locale-specific.  Pfff.
4186      (format " %s "
4187              (capitalize (car (rassoc (nth 4 (decode-time now))
4188                                       parse-time-months))))
4189      (format-time-string "%Y %H:%M:%S " now)
4190      ;; We do all of this because XEmacs doesn't have the %z spec.
4191      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
4192
4193 (defun message-make-message-id ()
4194   "Make a unique Message-ID."
4195   (concat "<" (message-unique-id)
4196           (let ((psubject (save-excursion (message-fetch-field "subject")))
4197                 (psupersedes
4198                  (save-excursion (message-fetch-field "supersedes"))))
4199             (if (or
4200                  (and message-reply-headers
4201                       (mail-header-references message-reply-headers)
4202                       (mail-header-subject message-reply-headers)
4203                       psubject
4204                       (not (string=
4205                             (message-strip-subject-re
4206                              (mail-header-subject message-reply-headers))
4207                             (message-strip-subject-re psubject))))
4208                  (and psupersedes
4209                       (string-match "_-_@" psupersedes)))
4210                 "_-_" ""))
4211           "@" (message-make-fqdn) ">"))
4212
4213 (defvar message-unique-id-char nil)
4214
4215 ;; If you ever change this function, make sure the new version
4216 ;; cannot generate IDs that the old version could.
4217 ;; You might for example insert a "." somewhere (not next to another dot
4218 ;; or string boundary), or modify the "fsf" string.
4219 (defun message-unique-id ()
4220   ;; Don't use microseconds from (current-time), they may be unsupported.
4221   ;; Instead we use this randomly inited counter.
4222   (setq message-unique-id-char
4223         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
4224            ;; (current-time) returns 16-bit ints,
4225            ;; and 2^16*25 just fits into 4 digits i base 36.
4226            (* 25 25)))
4227   (let ((tm (current-time)))
4228     (concat
4229      (if (memq system-type '(ms-dos emx vax-vms))
4230          (let ((user (downcase (user-login-name))))
4231            (while (string-match "[^a-z0-9_]" user)
4232              (aset user (match-beginning 0) ?_))
4233            user)
4234        (message-number-base36 (user-uid) -1))
4235      (message-number-base36 (+ (car tm)
4236                                (lsh (% message-unique-id-char 25) 16)) 4)
4237      (message-number-base36 (+ (nth 1 tm)
4238                                (lsh (/ message-unique-id-char 25) 16)) 4)
4239      ;; Append the newsreader name, because while the generated
4240      ;; ID is unique to this newsreader, other newsreaders might
4241      ;; otherwise generate the same ID via another algorithm.
4242      ".fsf")))
4243
4244 (defun message-number-base36 (num len)
4245   (if (if (< len 0)
4246           (<= num 0)
4247         (= len 0))
4248       ""
4249     (concat (message-number-base36 (/ num 36) (1- len))
4250             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
4251                                   (% num 36))))))
4252
4253 (defun message-make-organization ()
4254   "Make an Organization header."
4255   (let* ((organization
4256           (when message-user-organization
4257             (if (message-functionp message-user-organization)
4258                 (funcall message-user-organization)
4259               message-user-organization))))
4260     (save-excursion
4261       (message-set-work-buffer)
4262       (cond ((stringp organization)
4263              (insert organization))
4264             ((and (eq t organization)
4265                   message-user-organization-file
4266                   (file-exists-p message-user-organization-file))
4267              (insert-file-contents message-user-organization-file)))
4268       (goto-char (point-min))
4269       (while (re-search-forward "[\t\n]+" nil t)
4270         (replace-match "" t t))
4271       (unless (zerop (buffer-size))
4272         (buffer-string)))))
4273
4274 (defun message-make-lines ()
4275   "Count the number of lines and return numeric string."
4276   (save-excursion
4277     (save-restriction
4278       (widen)
4279       (message-goto-body)
4280       (int-to-string (count-lines (point) (point-max))))))
4281
4282 (defun message-make-references ()
4283   "Return the References header for this message."
4284   (when message-reply-headers
4285     (let ((message-id (mail-header-message-id message-reply-headers))
4286           (references (mail-header-references message-reply-headers))
4287           new-references)
4288       (if (or references message-id)
4289           (concat (or references "") (and references " ")
4290                   (or message-id ""))
4291         nil))))
4292
4293 (defun message-make-in-reply-to ()
4294   "Return the In-Reply-To header for this message."
4295   (when message-reply-headers
4296     (let ((from (mail-header-from message-reply-headers))
4297           (date (mail-header-date message-reply-headers))
4298           (msg-id (mail-header-message-id message-reply-headers)))
4299       (when from
4300         (let ((stop-pos
4301                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
4302           (concat msg-id (if msg-id " (")
4303                   (if (and stop-pos
4304                            (not (zerop stop-pos)))
4305                       (substring from 0 stop-pos) from)
4306                   "'s message of \""
4307                   (if (or (not date) (string= date ""))
4308                       "(unknown date)" date)
4309                   "\"" (if msg-id ")")))))))
4310
4311 (defun message-make-distribution ()
4312   "Make a Distribution header."
4313   (let ((orig-distribution (message-fetch-reply-field "distribution")))
4314     (cond ((message-functionp message-distribution-function)
4315            (funcall message-distribution-function))
4316           (t orig-distribution))))
4317
4318 (defun message-make-expires ()
4319   "Return an Expires header based on `message-expires'."
4320   (let ((current (current-time))
4321         (future (* 1.0 message-expires 60 60 24)))
4322     ;; Add the future to current.
4323     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
4324     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
4325     (message-make-date current)))
4326
4327 (defun message-make-path ()
4328   "Return uucp path."
4329   (let ((login-name (user-login-name)))
4330     (cond ((null message-user-path)
4331            (concat (system-name) "!" login-name))
4332           ((stringp message-user-path)
4333            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
4334            (concat message-user-path "!" login-name))
4335           (t login-name))))
4336
4337 (defun message-make-from ()
4338   "Make a From header."
4339   (let* ((style message-from-style)
4340          (login (message-make-address))
4341          (fullname
4342           (or (and (boundp 'user-full-name)
4343                    user-full-name)
4344               (user-full-name))))
4345     (when (string= fullname "&")
4346       (setq fullname (user-login-name)))
4347     (save-excursion
4348       (message-set-work-buffer)
4349       (cond
4350        ((or (null style)
4351             (equal fullname ""))
4352         (insert login))
4353        ((or (eq style 'angles)
4354             (and (not (eq style 'parens))
4355                  ;; Use angles if no quoting is needed, or if parens would
4356                  ;; need quoting too.
4357                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
4358                      (let ((tmp (concat fullname nil)))
4359                        (while (string-match "([^()]*)" tmp)
4360                          (aset tmp (match-beginning 0) ?-)
4361                          (aset tmp (1- (match-end 0)) ?-))
4362                        (string-match "[\\()]" tmp)))))
4363         (insert fullname)
4364         (insert " <" login ">"))
4365        (t                               ; 'parens or default
4366         (insert login " (")
4367         (let ((fullname-start (point)))
4368           (insert fullname)
4369           (goto-char fullname-start)
4370           ;; RFC 822 says \ and nonmatching parentheses
4371           ;; must be escaped in comments.
4372           ;; Escape every instance of ()\ ...
4373           (while (re-search-forward "[()\\]" nil 1)
4374             (replace-match "\\\\\\&" t))
4375           ;; ... then undo escaping of matching parentheses,
4376           ;; including matching nested parentheses.
4377           (goto-char fullname-start)
4378           (while (re-search-forward
4379                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
4380                   nil 1)
4381             (replace-match "\\1(\\3)" t)
4382             (goto-char fullname-start)))
4383         (insert ")")))
4384       (buffer-string))))
4385
4386 (defun message-make-sender ()
4387   "Return the \"real\" user address.
4388 This function tries to ignore all user modifications, and
4389 give as trustworthy answer as possible."
4390   (concat (user-login-name) "@" (system-name)))
4391
4392 (defun message-make-address ()
4393   "Make the address of the user."
4394   (or (message-user-mail-address)
4395       (concat (user-login-name) "@" (message-make-domain))))
4396
4397 (defun message-user-mail-address ()
4398   "Return the pertinent part of `user-mail-address'."
4399   (when user-mail-address
4400     (if (string-match " " user-mail-address)
4401         (nth 1 (mail-extract-address-components user-mail-address))
4402       user-mail-address)))
4403
4404 (defun message-make-fqdn ()
4405   "Return user's fully qualified domain name."
4406   (let ((system-name (system-name))
4407         (user-mail (message-user-mail-address)))
4408     (cond
4409      ((and (string-match "[^.]\\.[^.]" system-name)
4410            (not (string-match message-bogus-system-names system-name)))
4411       ;; `system-name' returned the right result.
4412       system-name)
4413      ;; Try `mail-host-address'.
4414      ((and (boundp 'mail-host-address)
4415            (stringp mail-host-address)
4416            (string-match "\\." mail-host-address))
4417       mail-host-address)
4418      ;; We try `user-mail-address' as a backup.
4419      ((and user-mail
4420            (string-match "\\." user-mail)
4421            (string-match "@\\(.*\\)\\'" user-mail))
4422       (match-string 1 user-mail))
4423      ;; Default to this bogus thing.
4424      (t
4425       (concat system-name ".i-did-not-set--mail-host-address--so-tickle-me")))))
4426
4427 (defun message-make-host-name ()
4428   "Return the name of the host."
4429   (let ((fqdn (message-make-fqdn)))
4430     (string-match "^[^.]+\\." fqdn)
4431     (substring fqdn 0 (1- (match-end 0)))))
4432
4433 (defun message-make-domain ()
4434   "Return the domain name."
4435   (or mail-host-address
4436       (message-make-fqdn)))
4437
4438 (defun message-to-list-only ()
4439   "Send a message to the list only.
4440 Remove all addresses but the list address from To and Cc headers."
4441   (interactive)
4442   (let ((listaddr (message-make-mft t)))
4443     (when listaddr
4444       (save-excursion
4445         (message-remove-header "to")
4446         (message-remove-header "cc")
4447         (message-position-on-field "To" "X-Draft-From")
4448         (insert listaddr)))))
4449
4450 (defun message-make-mft (&optional only-show-subscribed)
4451   "Return the Mail-Followup-To header. If passed the optional
4452 argument `only-show-subscribed' only return the subscribed address (and
4453 not the additional To and Cc header contents)."
4454   (let* ((case-fold-search t)
4455          (to (message-fetch-field "To"))
4456          (cc (message-fetch-field "cc"))
4457          (msg-recipients (concat to (and to cc ", ") cc))
4458          (recipients
4459           (mapcar 'mail-strip-quoted-names
4460                   (message-tokenize-header msg-recipients)))
4461          (file-regexps
4462           (if message-subscribed-address-file
4463               (let (begin end item re)
4464                 (save-excursion
4465                   (with-temp-buffer
4466                     (insert-file-contents message-subscribed-address-file)
4467                     (while (not (eobp))
4468                       (setq begin (point))
4469                       (forward-line 1)
4470                       (setq end (point))
4471                       (if (bolp) (setq end (1- end)))
4472                       (setq item (regexp-quote (buffer-substring begin end)))
4473                       (if re (setq re (concat re "\\|" item))
4474                         (setq re (concat "\\`\\(" item))))
4475                     (and re (list (concat re "\\)\\'"))))))))
4476          (mft-regexps (apply 'append message-subscribed-regexps
4477                              (mapcar 'regexp-quote
4478                                      message-subscribed-addresses)
4479                              file-regexps
4480                              (mapcar 'funcall
4481                                      message-subscribed-address-functions))))
4482     (save-match-data
4483       (let ((subscribed-lists nil)
4484             (list
4485              (loop for recipient in recipients
4486                when (loop for regexp in mft-regexps
4487                       when (string-match regexp recipient) return t)
4488                return recipient)))
4489         (when list
4490           (if only-show-subscribed
4491               list
4492             msg-recipients))))))
4493
4494 (defun message-generate-headers (headers)
4495   "Prepare article HEADERS.
4496 Headers already prepared in the buffer are not modified."
4497   (setq headers (append headers message-required-headers))
4498   (save-restriction
4499     (message-narrow-to-headers)
4500     (let* ((Date (message-make-date))
4501            (Message-ID (message-make-message-id))
4502            (Organization (message-make-organization))
4503            (From (message-make-from))
4504            (Path (message-make-path))
4505            (Subject nil)
4506            (Newsgroups nil)
4507            (In-Reply-To (message-make-in-reply-to))
4508            (References (message-make-references))
4509            (To nil)
4510            (Distribution (message-make-distribution))
4511            (Lines (message-make-lines))
4512            (User-Agent message-newsreader)
4513            (Expires (message-make-expires))
4514            (case-fold-search t)
4515            header value elem)
4516       ;; First we remove any old generated headers.
4517       (let ((headers message-deletable-headers))
4518         (unless (buffer-modified-p)
4519           (setq headers (delq 'Message-ID (copy-sequence headers))))
4520         (while headers
4521           (goto-char (point-min))
4522           (and (re-search-forward
4523                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4524                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
4525                (message-delete-line))
4526           (pop headers)))
4527       ;; Go through all the required headers and see if they are in the
4528       ;; articles already.  If they are not, or are empty, they are
4529       ;; inserted automatically - except for Subject, Newsgroups and
4530       ;; Distribution.
4531       (while headers
4532         (goto-char (point-min))
4533         (setq elem (pop headers))
4534         (if (consp elem)
4535             (if (eq (car elem) 'optional)
4536                 (setq header (cdr elem))
4537               (setq header (car elem)))
4538           (setq header elem))
4539         (when (or (not (re-search-forward
4540                         (concat "^"
4541                                 (regexp-quote
4542                                  (downcase
4543                                   (if (stringp header)
4544                                       header
4545                                     (symbol-name header))))
4546                                 ":")
4547                         nil t))
4548                   (progn
4549                     ;; The header was found.  We insert a space after the
4550                     ;; colon, if there is none.
4551                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
4552                     ;; Find out whether the header is empty...
4553                     (looking-at "[ \t]*\n[^ \t]")))
4554           ;; So we find out what value we should insert.
4555           (setq value
4556                 (cond
4557                  ((and (consp elem) (eq (car elem) 'optional))
4558                   ;; This is an optional header.  If the cdr of this
4559                   ;; is something that is nil, then we do not insert
4560                   ;; this header.
4561                   (setq header (cdr elem))
4562                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
4563                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
4564                  ((consp elem)
4565                   ;; The element is a cons.  Either the cdr is a
4566                   ;; string to be inserted verbatim, or it is a
4567                   ;; function, and we insert the value returned from
4568                   ;; this function.
4569                   (or (and (stringp (cdr elem)) (cdr elem))
4570                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
4571                  ((and (boundp header) (symbol-value header))
4572                   ;; The element is a symbol.  We insert the value
4573                   ;; of this symbol, if any.
4574                   (symbol-value header))
4575                  ((not (message-check-element header))
4576                   ;; We couldn't generate a value for this header,
4577                   ;; so we just ask the user.
4578                   (read-from-minibuffer
4579                    (format "Empty header for %s; enter value: " header)))))
4580           ;; Finally insert the header.
4581           (when (and value
4582                      (not (equal value "")))
4583             (save-excursion
4584               (if (bolp)
4585                   (progn
4586                     ;; This header didn't exist, so we insert it.
4587                     (goto-char (point-max))
4588                     (insert (if (stringp header) header (symbol-name header))
4589                             ": " value)
4590                     ;; We check whether the value was ended by a
4591                     ;; newline.  If now, we insert one.
4592                     (unless (bolp)
4593                       (insert "\n"))
4594                     (forward-line -1))
4595                 ;; The value of this header was empty, so we clear
4596                 ;; totally and insert the new value.
4597                 (delete-region (point) (gnus-point-at-eol))
4598                 (insert value))
4599               ;; Add the deletable property to the headers that require it.
4600               (and (memq header message-deletable-headers)
4601                    (progn (beginning-of-line) (looking-at "[^:]+: "))
4602                    (add-text-properties
4603                     (point) (match-end 0)
4604                     '(message-deletable t face italic) (current-buffer)))))))
4605       ;; Insert new Sender if the From is strange.
4606       (let ((from (message-fetch-field "from"))
4607             (sender (message-fetch-field "sender"))
4608             (secure-sender (message-make-sender)))
4609         (when (and from
4610                    (not (message-check-element 'sender))
4611                    (not (string=
4612                          (downcase
4613                           (cadr (mail-extract-address-components from)))
4614                          (downcase secure-sender)))
4615                    (or (null sender)
4616                        (not
4617                         (string=
4618                          (downcase
4619                           (cadr (mail-extract-address-components sender)))
4620                          (downcase secure-sender)))))
4621           (goto-char (point-min))
4622           ;; Rename any old Sender headers to Original-Sender.
4623           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
4624             (beginning-of-line)
4625             (insert "Original-")
4626             (beginning-of-line))
4627           (when (or (message-news-p)
4628                     (string-match "@.+\\.." secure-sender))
4629             (insert "Sender: " secure-sender "\n")))))))
4630
4631 (defun message-insert-courtesy-copy ()
4632   "Insert a courtesy message in mail copies of combined messages."
4633   (let (newsgroups)
4634     (save-excursion
4635       (save-restriction
4636         (message-narrow-to-headers)
4637         (when (setq newsgroups (message-fetch-field "newsgroups"))
4638           (goto-char (point-max))
4639           (insert "Posted-To: " newsgroups "\n")))
4640       (forward-line 1)
4641       (when message-courtesy-message
4642         (cond
4643          ((string-match "%s" message-courtesy-message)
4644           (insert (format message-courtesy-message newsgroups)))
4645          (t
4646           (insert message-courtesy-message)))))))
4647
4648 ;;;
4649 ;;; Setting up a message buffer
4650 ;;;
4651
4652 (defun message-fill-address (header value)
4653   (save-restriction
4654     (narrow-to-region (point) (point))
4655     (insert (capitalize (symbol-name header))
4656             ": "
4657             (if (consp value) (car value) value)
4658             "\n")
4659     (narrow-to-region (point-min) (1- (point-max)))
4660     (let (quoted last)
4661       (goto-char (point-min))
4662       (while (not (eobp))
4663         (skip-chars-forward "^,\"" (point-max))
4664         (if (or (eq (char-after) ?,)
4665                 (eobp))
4666             (when (not quoted)
4667               (if (and (> (current-column) 78)
4668                        last)
4669                   (progn
4670                     (save-excursion
4671                       (goto-char last)
4672                       (insert "\n\t"))
4673                     (setq last (1+ (point))))
4674                 (setq last (1+ (point)))))
4675           (setq quoted (not quoted)))
4676         (unless (eobp)
4677           (forward-char 1))))
4678     (goto-char (point-max))
4679     (widen)
4680     (forward-line 1)))
4681
4682 (defun message-fill-header (header value)
4683   (let ((begin (point))
4684         (fill-column 78)
4685         (fill-prefix "\t"))
4686     (insert (capitalize (symbol-name header))
4687             ": "
4688             (if (consp value) (car value) value)
4689             "\n")
4690     (save-restriction
4691       (narrow-to-region begin (point))
4692       (fill-region-as-paragraph begin (point))
4693       ;; Tapdance around looong Message-IDs.
4694       (forward-line -1)
4695       (when (looking-at "[ \t]*$")
4696         (message-delete-line))
4697       (goto-char begin)
4698       (re-search-forward ":" nil t)
4699       (when (looking-at "\n[ \t]+")
4700         (replace-match " " t t))
4701       (goto-char (point-max)))))
4702
4703 (defun message-shorten-1 (list cut surplus)
4704   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
4705   (setcdr (nthcdr (- cut 2) list)
4706           (nthcdr (+ (- cut 2) surplus 1) list)))
4707
4708 (defun message-shorten-references (header references)
4709   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
4710 If folding is disallowed, also check that the REFERENCES are less
4711 than 988 characters long, and if they are not, trim them until they are."
4712   (let ((maxcount 21)
4713         (count 0)
4714         (cut 2)
4715         refs)
4716     (with-temp-buffer
4717       (insert references)
4718       (goto-char (point-min))
4719       ;; Cons a list of valid references.
4720       (while (re-search-forward "<[^>]+>" nil t)
4721         (push (match-string 0) refs))
4722       (setq refs (nreverse refs)
4723             count (length refs)))
4724
4725     ;; If the list has more than MAXCOUNT elements, trim it by
4726     ;; removing the CUTth element and the required number of
4727     ;; elements that follow.
4728     (when (> count maxcount)
4729       (let ((surplus (- count maxcount)))
4730         (message-shorten-1 refs cut surplus)
4731         (decf count surplus)))
4732
4733     ;; If folding is disallowed, make sure the total length (including
4734     ;; the spaces between) will be less than MAXSIZE characters.
4735     ;;
4736     ;; Only disallow folding for News messages. At this point the headers
4737     ;; have not been generated, thus we use message-this-is-news directly.
4738     (when (and message-this-is-news message-cater-to-broken-inn)
4739       (let ((maxsize 988)
4740             (totalsize (+ (apply #'+ (mapcar #'length refs))
4741                           (1- count)))
4742             (surplus 0)
4743             (ptr (nthcdr (1- cut) refs)))
4744         ;; Decide how many elements to cut off...
4745         (while (> totalsize maxsize)
4746           (decf totalsize (1+ (length (car ptr))))
4747           (incf surplus)
4748           (setq ptr (cdr ptr)))
4749         ;; ...and do it.
4750         (when (> surplus 0)
4751           (message-shorten-1 refs cut surplus))))
4752
4753     ;; Finally, collect the references back into a string and insert
4754     ;; it into the buffer.
4755     (let ((refstring (mapconcat #'identity refs " ")))
4756       (if (and message-this-is-news message-cater-to-broken-inn)
4757           (insert (capitalize (symbol-name header)) ": "
4758                   refstring "\n")
4759         (message-fill-header header refstring)))))
4760
4761 (defun message-position-point ()
4762   "Move point to where the user probably wants to find it."
4763   (message-narrow-to-headers)
4764   (cond
4765    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
4766     (search-backward ":" )
4767     (widen)
4768     (forward-char 1)
4769     (if (eq (char-after) ? )
4770         (forward-char 1)
4771       (insert " ")))
4772    (t
4773     (goto-char (point-max))
4774     (widen)
4775     (forward-line 1)
4776     (unless (looking-at "$")
4777       (forward-line 2)))
4778    (sit-for 0)))
4779
4780 (defcustom message-beginning-of-line t
4781   "Whether C-a goes to beginning of header values."
4782   :group 'message-buffers
4783   :type 'boolean)
4784
4785 (defun message-beginning-of-line (&optional n)
4786   "Move point to beginning of header value or to beginning of line."
4787   (interactive "p")
4788   (let ((zrs 'zmacs-region-stays))
4789     (when (and (interactive-p) (boundp zrs))
4790       (set zrs t)))
4791   (if (and message-beginning-of-line
4792            (message-point-in-header-p))
4793       (let* ((here (point))
4794              (bol (progn (beginning-of-line n) (point)))
4795              (eol (gnus-point-at-eol))
4796              (eoh (re-search-forward ": *" eol t)))
4797         (if (or (not eoh) (equal here eoh))
4798             (goto-char bol)
4799           (goto-char eoh)))
4800     (beginning-of-line n)))
4801
4802 (defun message-buffer-name (type &optional to group)
4803   "Return a new (unique) buffer name based on TYPE and TO."
4804   (cond
4805    ;; Generate a new buffer name The Message Way.
4806    ((eq message-generate-new-buffers 'unique)
4807     (generate-new-buffer-name
4808      (concat "*" type
4809              (if to
4810                  (concat " to "
4811                          (or (car (mail-extract-address-components to))
4812                              to) "")
4813                "")
4814              (if (and group (not (string= group ""))) (concat " on " group) "")
4815              "*")))
4816    ;; Check whether `message-generate-new-buffers' is a function,
4817    ;; and if so, call it.
4818    ((message-functionp message-generate-new-buffers)
4819     (funcall message-generate-new-buffers type to group))
4820    ((eq message-generate-new-buffers 'unsent)
4821     (generate-new-buffer-name
4822      (concat "*unsent " type
4823              (if to
4824                  (concat " to "
4825                          (or (car (mail-extract-address-components to))
4826                              to) "")
4827                "")
4828              (if (and group (not (string= group ""))) (concat " on " group) "")
4829              "*")))
4830    ;; Use standard name.
4831    (t
4832     (format "*%s message*" type))))
4833
4834 (defun message-pop-to-buffer (name)
4835   "Pop to buffer NAME, and warn if it already exists and is modified."
4836   (let ((buffer (get-buffer name)))
4837     (if (and buffer
4838              (buffer-name buffer))
4839         (progn
4840           (set-buffer (pop-to-buffer buffer))
4841           (when (and (buffer-modified-p)
4842                      (not (y-or-n-p
4843                            "Message already being composed; erase? ")))
4844             (error "Message being composed")))
4845       (set-buffer (pop-to-buffer name)))
4846     (erase-buffer)
4847     (message-mode)))
4848
4849 (defun message-do-send-housekeeping ()
4850   "Kill old message buffers."
4851   ;; We might have sent this buffer already.  Delete it from the
4852   ;; list of buffers.
4853   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
4854   (while (and message-max-buffers
4855               message-buffer-list
4856               (>= (length message-buffer-list) message-max-buffers))
4857     ;; Kill the oldest buffer -- unless it has been changed.
4858     (let ((buffer (pop message-buffer-list)))
4859       (when (and (buffer-name buffer)
4860                  (not (buffer-modified-p buffer)))
4861         (kill-buffer buffer))))
4862   ;; Rename the buffer.
4863   (if message-send-rename-function
4864       (funcall message-send-rename-function)
4865     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
4866     (when (string-match
4867            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
4868            (buffer-name))
4869       (let ((name (match-string 2 (buffer-name)))
4870             to group)
4871         (if (not (or (null name)
4872                      (string-equal name "mail")
4873                      (string-equal name "posting")))
4874             (setq name (concat "*sent " name "*"))
4875           (message-narrow-to-headers)
4876           (setq to (message-fetch-field "to"))
4877           (setq group (message-fetch-field "newsgroups"))
4878           (widen)
4879           (setq name
4880                 (cond
4881                  (to (concat "*sent mail to "
4882                              (or (car (mail-extract-address-components to))
4883                                  to) "*"))
4884                  ((and group (not (string= group "")))
4885                   (concat "*sent posting on " group "*"))
4886                  (t "*sent mail*"))))
4887         (unless (string-equal name (buffer-name))
4888           (rename-buffer name t)))))
4889   ;; Push the current buffer onto the list.
4890   (when message-max-buffers
4891     (setq message-buffer-list
4892           (nconc message-buffer-list (list (current-buffer))))))
4893
4894 (defun message-mail-user-agent ()
4895   (let ((mua (cond
4896               ((not message-mail-user-agent) nil)
4897               ((eq message-mail-user-agent t) mail-user-agent)
4898               (t message-mail-user-agent))))
4899     (if (memq mua '(message-user-agent gnus-user-agent))
4900         nil
4901       mua)))
4902
4903 (defun message-setup (headers &optional replybuffer actions switch-function)
4904   (let ((mua (message-mail-user-agent))
4905         subject to field yank-action)
4906     (if (not (and message-this-is-mail mua))
4907         (message-setup-1 headers replybuffer actions)
4908       (if replybuffer
4909           (setq yank-action (list 'insert-buffer replybuffer)))
4910       (setq headers (copy-sequence headers))
4911       (setq field (assq 'Subject headers))
4912       (when field
4913         (setq subject (cdr field))
4914         (setq headers (delq field headers)))
4915       (setq field (assq 'To headers))
4916       (when field
4917         (setq to (cdr field))
4918         (setq headers (delq field headers)))
4919       (let ((mail-user-agent mua))
4920         (compose-mail to subject
4921                       (mapcar (lambda (item)
4922                                 (cons
4923                                  (format "%s" (car item))
4924                                  (cdr item)))
4925                               headers)
4926                       nil switch-function yank-action actions)))))
4927
4928 (defun message-setup-1 (headers &optional replybuffer actions)
4929   (dolist (action actions)
4930     (condition-case nil
4931         (add-to-list 'message-send-actions
4932                      `(apply ',(car action) ',(cdr action)))))
4933   (setq message-reply-buffer replybuffer)
4934   (goto-char (point-min))
4935   ;; Insert all the headers.
4936   (mail-header-format
4937    (let ((h headers)
4938          (alist message-header-format-alist))
4939      (while h
4940        (unless (assq (caar h) message-header-format-alist)
4941          (push (list (caar h)) alist))
4942        (pop h))
4943      alist)
4944    headers)
4945   (delete-region (point) (progn (forward-line -1) (point)))
4946   (when message-default-headers
4947     (insert message-default-headers)
4948     (or (bolp) (insert ?\n)))
4949   (put-text-property
4950    (point)
4951    (progn
4952      (insert mail-header-separator "\n")
4953      (1- (point)))
4954    'read-only nil)
4955   (forward-line -1)
4956   (when (message-news-p)
4957     (when message-default-news-headers
4958       (insert message-default-news-headers)
4959       (or (bolp) (insert ?\n)))
4960     (when message-generate-headers-first
4961       (message-generate-headers
4962        (delq 'Lines
4963              (delq 'Subject
4964                    (copy-sequence message-required-news-headers))))))
4965   (when (message-mail-p)
4966     (when message-default-mail-headers
4967       (insert message-default-mail-headers)
4968       (or (bolp) (insert ?\n)))
4969     (when message-generate-headers-first
4970       (message-generate-headers
4971        (delq 'Lines
4972              (delq 'Subject
4973                    (copy-sequence message-required-mail-headers))))))
4974   (run-hooks 'message-signature-setup-hook)
4975   (message-insert-signature)
4976   (save-restriction
4977     (message-narrow-to-headers)
4978     (if message-alternative-emails
4979         (message-use-alternative-email-as-from))
4980     (run-hooks 'message-header-setup-hook))
4981   (set-buffer-modified-p nil)
4982   (setq buffer-undo-list nil)
4983   (run-hooks 'message-setup-hook)
4984   (message-position-point)
4985   (undo-boundary))
4986
4987 (defun message-set-auto-save-file-name ()
4988   "Associate the message buffer with a file in the drafts directory."
4989   (when message-auto-save-directory
4990     (unless (file-directory-p
4991              (directory-file-name message-auto-save-directory))
4992       (make-directory message-auto-save-directory t))
4993     (if (gnus-alive-p)
4994         (setq message-draft-article
4995               (nndraft-request-associate-buffer "drafts"))
4996       (setq buffer-file-name (expand-file-name
4997                               (if (memq system-type
4998                                         '(ms-dos ms-windows windows-nt
4999                                                  cygwin cygwin32 win32 w32
5000                                                  mswindows))
5001                                   "message"
5002                                 "*message*")
5003                               message-auto-save-directory))
5004       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
5005     (clear-visited-file-modtime)
5006     (setq buffer-file-coding-system message-draft-coding-system)))
5007
5008 (defun message-disassociate-draft ()
5009   "Disassociate the message buffer from the drafts directory."
5010   (when message-draft-article
5011     (nndraft-request-expire-articles
5012      (list message-draft-article) "drafts" nil t)))
5013
5014 (defun message-insert-headers ()
5015   "Generate the headers for the article."
5016   (interactive)
5017   (save-excursion
5018     (save-restriction
5019       (message-narrow-to-headers)
5020       (when (message-news-p)
5021         (message-generate-headers
5022          (delq 'Lines
5023                (delq 'Subject
5024                      (copy-sequence message-required-news-headers)))))
5025       (when (message-mail-p)
5026         (message-generate-headers
5027          (delq 'Lines
5028                (delq 'Subject
5029                      (copy-sequence message-required-mail-headers))))))))
5030
5031 \f
5032
5033 ;;;
5034 ;;; Commands for interfacing with message
5035 ;;;
5036
5037 ;;;###autoload
5038 (defun message-mail (&optional to subject
5039                                other-headers continue switch-function
5040                                yank-action send-actions)
5041   "Start editing a mail message to be sent.
5042 OTHER-HEADERS is an alist of header/value pairs."
5043   (interactive)
5044   (let ((message-this-is-mail t) replybuffer)
5045     (unless (message-mail-user-agent)
5046       (message-pop-to-buffer (message-buffer-name "mail" to)))
5047     ;; FIXME: message-mail should do something if YANK-ACTION is not
5048     ;; insert-buffer.
5049     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
5050          (setq replybuffer (nth 1 yank-action)))
5051     (message-setup
5052      (nconc
5053       `((To . ,(or to "")) (Subject . ,(or subject "")))
5054       (when other-headers other-headers))
5055      replybuffer send-actions)
5056     ;; FIXME: Should return nil if failure.
5057     t))
5058
5059 ;;;###autoload
5060 (defun message-news (&optional newsgroups subject)
5061   "Start editing a news article to be sent."
5062   (interactive)
5063   (let ((message-this-is-news t))
5064     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
5065     (message-setup `((Newsgroups . ,(or newsgroups ""))
5066                      (Subject . ,(or subject ""))))))
5067
5068 (defun message-get-reply-headers (wide &optional to-address address-headers)
5069   (let (follow-to mct never-mct to cc author mft recipients)
5070     ;; Find all relevant headers we need.
5071     (setq to (message-fetch-field "to")
5072           cc (message-fetch-field "cc")
5073           mct (message-fetch-field "mail-copies-to")
5074           author (or (message-fetch-field "mail-reply-to")
5075                      (message-fetch-field "reply-to")
5076                      (message-fetch-field "from")
5077                      "")
5078           mft (and message-use-mail-followup-to
5079                    (message-fetch-field "mail-followup-to")))
5080
5081     ;; Handle special values of Mail-Copies-To.
5082     (when mct
5083       (cond ((or (equal (downcase mct) "never")
5084                  (equal (downcase mct) "nobody"))
5085              (setq never-mct t)
5086              (setq mct nil))
5087             ((or (equal (downcase mct) "always")
5088                  (equal (downcase mct) "poster"))
5089              (setq mct author))))
5090
5091     (save-match-data
5092       ;; Build (textual) list of new recipient addresses.
5093       (cond
5094        ((not wide)
5095         (setq recipients (concat ", " author)))
5096        (address-headers
5097         (dolist (header address-headers)
5098           (let ((value (message-fetch-field header)))
5099             (when value
5100               (setq recipients (concat recipients ", " value))))))
5101        ((and mft
5102              (string-match "[^ \t,]" mft)
5103              (or (not (eq message-use-mail-followup-to 'ask))
5104                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
5105 You should normally obey the Mail-Followup-To: header.  In this
5106 article, it has the value of
5107
5108 " mft "
5109
5110 which directs your response to " (if (string-match "," mft)
5111                                      "the specified addresses"
5112                                    "that address only") ".
5113
5114 Most commonly, Mail-Followup-To is used by a mailing list poster to
5115 express that responses should be sent to just the list, and not the
5116 poster as well.
5117
5118 If a message is posted to several mailing lists, Mail-Followup-To may
5119 also be used to direct the following discussion to one list only,
5120 because discussions that are spread over several lists tend to be
5121 fragmented and very difficult to follow.
5122
5123 Also, some source/announcement lists are not intended for discussion;
5124 responses here are directed to other addresses.")))
5125         (setq recipients (concat ", " mft)))
5126        (to-address
5127         (setq recipients (concat ", " to-address))
5128         ;; If the author explicitly asked for a copy, we don't deny it to them.
5129         (if mct (setq recipients (concat recipients ", " mct))))
5130        (t
5131         (setq recipients (if never-mct "" (concat ", " author)))
5132         (if to  (setq recipients (concat recipients ", " to)))
5133         (if cc  (setq recipients (concat recipients ", " cc)))
5134         (if mct (setq recipients (concat recipients ", " mct)))))
5135       (if (>= (length recipients) 2)
5136           ;; Strip the leading ", ".
5137           (setq recipients (substring recipients 2)))
5138       ;; Squeeze whitespace.
5139       (while (string-match "[ \t][ \t]+" recipients)
5140         (setq recipients (replace-match " " t t recipients)))
5141       ;; Remove addresses that match `rmail-dont-reply-to-names'.
5142       (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
5143         (setq recipients (rmail-dont-reply-to recipients)))
5144       ;; Perhaps "Mail-Copies-To: never" removed the only address?
5145       (if (string-equal recipients "")
5146           (setq recipients author))
5147       ;; Convert string to a list of (("foo@bar" . "Name <Foo@BAR>") ...).
5148       (setq recipients
5149             (mapcar
5150              (lambda (addr)
5151                (cons (downcase (mail-strip-quoted-names addr)) addr))
5152              (message-tokenize-header recipients)))
5153       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
5154       (let ((s recipients))
5155         (while s
5156           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
5157
5158       ;; Remove hierarchical lists that are contained within each other,
5159       ;; if message-hierarchical-addresses is defined.
5160       (when message-hierarchical-addresses
5161         (let ((plain-addrs (mapcar 'car recipients))
5162               subaddrs recip)
5163           (while plain-addrs
5164             (setq subaddrs (assoc (car plain-addrs)
5165                                   message-hierarchical-addresses)
5166                   plain-addrs (cdr plain-addrs))
5167             (when subaddrs
5168               (setq subaddrs (cdr subaddrs))
5169               (while subaddrs
5170                 (setq recip (assoc (car subaddrs) recipients)
5171                       subaddrs (cdr subaddrs))
5172                 (if recip
5173                     (setq recipients (delq recip recipients))))))))
5174
5175       ;; Build the header alist.  Allow the user to be asked whether
5176       ;; or not to reply to all recipients in a wide reply.
5177       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
5178       (when (and recipients
5179                  (or (not message-wide-reply-confirm-recipients)
5180                      (y-or-n-p "Reply to all recipients? ")))
5181         (setq recipients (mapconcat
5182                           (lambda (addr) (cdr addr)) recipients ", "))
5183         (if (string-match "^ +" recipients)
5184             (setq recipients (substring recipients (match-end 0))))
5185         (push (cons 'Cc recipients) follow-to)))
5186     follow-to))
5187
5188 ;;;###autoload
5189 (defun message-reply (&optional to-address wide)
5190   "Start editing a reply to the article in the current buffer."
5191   (interactive)
5192   (require 'gnus-sum)                   ; for gnus-list-identifiers
5193   (let ((cur (current-buffer))
5194         from subject date reply-to to cc
5195         references message-id follow-to
5196         (inhibit-point-motion-hooks t)
5197         (message-this-is-mail t)
5198         gnus-warning)
5199     (save-restriction
5200       (message-narrow-to-head-1)
5201       ;; Allow customizations to have their say.
5202       (if (not wide)
5203           ;; This is a regular reply.
5204           (when (message-functionp message-reply-to-function)
5205             (save-excursion
5206               (setq follow-to (funcall message-reply-to-function))))
5207         ;; This is a followup.
5208         (when (message-functionp message-wide-reply-to-function)
5209           (save-excursion
5210             (setq follow-to
5211                   (funcall message-wide-reply-to-function)))))
5212       (setq message-id (message-fetch-field "message-id" t)
5213             references (message-fetch-field "references")
5214             date (message-fetch-field "date")
5215             from (message-fetch-field "from")
5216             subject (or (message-fetch-field "subject") "none"))
5217       (when gnus-list-identifiers
5218         (setq subject (message-strip-list-identifiers subject)))
5219       (setq subject (concat "Re: " (message-strip-subject-re subject)))
5220       (when message-subject-trailing-was-query
5221         (setq subject (message-strip-subject-trailing-was subject)))
5222
5223       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
5224                  (string-match "<[^>]+>" gnus-warning))
5225         (setq message-id (match-string 0 gnus-warning)))
5226
5227       (unless follow-to
5228         (setq follow-to (message-get-reply-headers wide to-address))))
5229
5230     (unless (message-mail-user-agent)
5231       (message-pop-to-buffer
5232        (message-buffer-name
5233         (if wide "wide reply" "reply") from
5234         (if wide to-address nil))))
5235
5236     (setq message-reply-headers
5237           (vector 0 subject from date message-id references 0 0 ""))
5238
5239     (message-setup
5240      `((Subject . ,subject)
5241        ,@follow-to)
5242      cur)))
5243
5244 ;;;###autoload
5245 (defun message-wide-reply (&optional to-address)
5246   "Make a \"wide\" reply to the message in the current buffer."
5247   (interactive)
5248   (message-reply to-address t))
5249
5250 ;;;###autoload
5251 (defun message-followup (&optional to-newsgroups)
5252   "Follow up to the message in the current buffer.
5253 If TO-NEWSGROUPS, use that as the new Newsgroups line."
5254   (interactive)
5255   (require 'gnus-sum)                   ; for gnus-list-identifiers
5256   (let ((cur (current-buffer))
5257         from subject date reply-to mrt mct
5258         references message-id follow-to
5259         (inhibit-point-motion-hooks t)
5260         (message-this-is-news t)
5261         followup-to distribution newsgroups gnus-warning posted-to)
5262     (save-restriction
5263       (narrow-to-region
5264        (goto-char (point-min))
5265        (if (search-forward "\n\n" nil t)
5266            (1- (point))
5267          (point-max)))
5268       (when (message-functionp message-followup-to-function)
5269         (setq follow-to
5270               (funcall message-followup-to-function)))
5271       (setq from (message-fetch-field "from")
5272             date (message-fetch-field "date")
5273             subject (or (message-fetch-field "subject") "none")
5274             references (message-fetch-field "references")
5275             message-id (message-fetch-field "message-id" t)
5276             followup-to (message-fetch-field "followup-to")
5277             newsgroups (message-fetch-field "newsgroups")
5278             posted-to (message-fetch-field "posted-to")
5279             reply-to (message-fetch-field "reply-to")
5280             mrt (message-fetch-field "mail-reply-to")
5281             distribution (message-fetch-field "distribution")
5282             mct (message-fetch-field "mail-copies-to"))
5283       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
5284                  (string-match "<[^>]+>" gnus-warning))
5285         (setq message-id (match-string 0 gnus-warning)))
5286       ;; Remove bogus distribution.
5287       (when (and (stringp distribution)
5288                  (let ((case-fold-search t))
5289                    (string-match "world" distribution)))
5290         (setq distribution nil))
5291       (if gnus-list-identifiers
5292           (setq subject (message-strip-list-identifiers subject)))
5293       (setq subject (concat "Re: " (message-strip-subject-re subject)))
5294       (when message-subject-trailing-was-query
5295         (setq subject (message-strip-subject-trailing-was subject)))
5296       (widen))
5297
5298     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
5299
5300     (setq message-reply-headers
5301           (vector 0 subject from date message-id references 0 0 ""))
5302     
5303     (message-setup
5304      `((Subject . ,subject)
5305        ,@(cond
5306           (to-newsgroups
5307            (list (cons 'Newsgroups to-newsgroups)))
5308           (follow-to follow-to)
5309           ((and followup-to message-use-followup-to)
5310            (list
5311             (cond
5312              ((equal (downcase followup-to) "poster")
5313               (if (or (eq message-use-followup-to 'use)
5314                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
5315 You should normally obey the Followup-To: header.
5316
5317 `Followup-To: poster' sends your response via e-mail instead of news.
5318
5319 A typical situation where `Followup-To: poster' is used is when the poster
5320 does not read the newsgroup, so he wouldn't see any replies sent to it."))
5321                   (progn
5322                     (setq message-this-is-news nil)
5323                     (cons 'To (or mrt reply-to from "")))
5324                 (cons 'Newsgroups newsgroups)))
5325              (t
5326               (if (or (equal followup-to newsgroups)
5327                       (not (eq message-use-followup-to 'ask))
5328                       (message-y-or-n-p
5329                        (concat "Obey Followup-To: " followup-to "? ") t "\
5330 You should normally obey the Followup-To: header.
5331
5332         `Followup-To: " followup-to "'
5333 directs your response to " (if (string-match "," followup-to)
5334                                "the specified newsgroups"
5335                              "that newsgroup only") ".
5336
5337 If a message is posted to several newsgroups, Followup-To is often
5338 used to direct the following discussion to one newsgroup only,
5339 because discussions that are spread over several newsgroup tend to
5340 be fragmented and very difficult to follow.
5341
5342 Also, some source/announcement newsgroups are not intended for discussion;
5343 responses here are directed to other newsgroups."))
5344                   (cons 'Newsgroups followup-to)
5345                 (cons 'Newsgroups newsgroups))))))
5346           (posted-to
5347            `((Newsgroups . ,posted-to)))
5348           (t
5349            `((Newsgroups . ,newsgroups))))
5350        ,@(and distribution (list (cons 'Distribution distribution)))
5351        ,@(when (and mct
5352                     (not (or (equal (downcase mct) "never")
5353                              (equal (downcase mct) "nobody"))))
5354            (list (cons 'Cc (if (or (equal (downcase mct) "always")
5355                                    (equal (downcase mct) "poster"))
5356                                (or mrt reply-to from "")
5357                              mct)))))
5358
5359      cur)))
5360
5361
5362 ;;;###autoload
5363 (defun message-cancel-news (&optional arg)
5364   "Cancel an article you posted.
5365 If ARG, allow editing of the cancellation message."
5366   (interactive "P")
5367   (unless (message-news-p)
5368     (error "This is not a news article; canceling is impossible"))
5369   (let (from newsgroups message-id distribution buf sender)
5370     (save-excursion
5371       ;; Get header info from original article.
5372       (save-restriction
5373         (message-narrow-to-head-1)
5374         (setq from (message-fetch-field "from")
5375               sender (message-fetch-field "sender")
5376               newsgroups (message-fetch-field "newsgroups")
5377               message-id (message-fetch-field "message-id" t)
5378               distribution (message-fetch-field "distribution")))
5379       ;; Make sure that this article was written by the user.
5380       (unless (or
5381                ;; Canlock-logic as suggested by Per Abrahamsen
5382                ;; <abraham@dina.kvl.dk>
5383                ;;
5384                ;; IF article has cancel-lock THEN
5385                ;;   IF we can verify it THEN
5386                ;;     issue cancel
5387                ;;   ELSE
5388                ;;     error: cancellock: article is not yours
5389                ;; ELSE
5390                ;;   Use old rules, comparing sender...
5391                (if (message-fetch-field "Cancel-Lock")
5392                    (if (null (canlock-verify))
5393                        t
5394                      (error "Failed to verify Cancel-lock: This article is not yours"))
5395                  nil)
5396                (message-gnksa-enable-p 'cancel-messages)
5397                (and sender
5398                     (string-equal
5399                      (downcase sender)
5400                      (downcase (message-make-sender))))
5401                (string-equal
5402                 (downcase (cadr (mail-extract-address-components from)))
5403                 (downcase (cadr (mail-extract-address-components
5404                                  (message-make-from))))))
5405         (error "This article is not yours"))
5406       (when (yes-or-no-p "Do you really want to cancel this article? ")
5407         ;; Make control message.
5408         (if arg
5409             (message-news)
5410           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
5411         (erase-buffer)
5412         (insert "Newsgroups: " newsgroups "\n"
5413                 "From: " from "\n"
5414                 "Subject: cmsg cancel " message-id "\n"
5415                 "Control: cancel " message-id "\n"
5416                 (if distribution
5417                     (concat "Distribution: " distribution "\n")
5418                   "")
5419                 mail-header-separator "\n"
5420                 message-cancel-message)
5421         (run-hooks 'message-cancel-hook)
5422         (unless arg
5423           (message "Canceling your article...")
5424           (if (let ((message-syntax-checks
5425                      'dont-check-for-anything-just-trust-me))
5426                 (funcall message-send-news-function))
5427               (message "Canceling your article...done"))
5428           (kill-buffer buf))))))
5429
5430 ;;;###autoload
5431 (defun message-supersede ()
5432   "Start composing a message to supersede the current message.
5433 This is done simply by taking the old article and adding a Supersedes
5434 header line with the old Message-ID."
5435   (interactive)
5436   (let ((cur (current-buffer))
5437         (sender (message-fetch-field "sender"))
5438         (from (message-fetch-field "from")))
5439     ;; Check whether the user owns the article that is to be superseded.
5440     (unless (or
5441              ;; Canlock-logic as suggested by Per Abrahamsen
5442              ;; <abraham@dina.kvl.dk>
5443              ;;
5444              ;; IF article has cancel-lock THEN
5445              ;;   IF we can verify it THEN
5446              ;;     issue cancel
5447              ;;   ELSE
5448              ;;     error: cancellock: article is not yours
5449              ;; ELSE
5450              ;;   Use old rules, comparing sender...
5451              (if (message-fetch-field "Cancel-Lock")
5452                  (if (null (canlock-verify))
5453                      t
5454                    (error "Failed to verify Cancel-lock: This article is not yours"))
5455                nil)
5456              (message-gnksa-enable-p 'cancel-messages)
5457                 (and sender
5458                      (string-equal
5459                       (downcase sender)
5460                       (downcase (message-make-sender))))
5461                 (string-equal
5462                  (downcase (cadr (mail-extract-address-components from)))
5463                  (downcase (cadr (mail-extract-address-components
5464                                   (message-make-from))))))
5465       (error "This article is not yours"))
5466     ;; Get a normal message buffer.
5467     (message-pop-to-buffer (message-buffer-name "supersede"))
5468     (insert-buffer-substring cur)
5469     (mime-to-mml)
5470     (message-narrow-to-head-1)
5471     ;; Remove unwanted headers.
5472     (when message-ignored-supersedes-headers
5473       (message-remove-header message-ignored-supersedes-headers t))
5474     (goto-char (point-min))
5475     (if (not (re-search-forward "^Message-ID: " nil t))
5476         (error "No Message-ID in this article")
5477       (replace-match "Supersedes: " t t))
5478     (goto-char (point-max))
5479     (insert mail-header-separator)
5480     (widen)
5481     (forward-line 1)))
5482
5483 ;;;###autoload
5484 (defun message-recover ()
5485   "Reread contents of current buffer from its last auto-save file."
5486   (interactive)
5487   (let ((file-name (make-auto-save-file-name)))
5488     (cond ((save-window-excursion
5489              (if (not (eq system-type 'vax-vms))
5490                  (with-output-to-temp-buffer "*Directory*"
5491                    (with-current-buffer standard-output
5492                      (fundamental-mode)) ; for Emacs 20.4+
5493                    (buffer-disable-undo standard-output)
5494                    (let ((default-directory "/"))
5495                      (call-process
5496                       "ls" nil standard-output nil "-l" file-name))))
5497              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
5498            (let ((buffer-read-only nil))
5499              (erase-buffer)
5500              (insert-file-contents file-name nil)))
5501           (t (error "message-recover cancelled")))))
5502
5503 ;;; Washing Subject:
5504
5505 (defun message-wash-subject (subject)
5506   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
5507 Previous forwarders, replyers, etc. may add it."
5508   (with-temp-buffer
5509     (insert subject)
5510     (goto-char (point-min))
5511     ;; strip Re/Fwd stuff off the beginning
5512     (while (re-search-forward
5513             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
5514       (replace-match ""))
5515
5516     ;; and gnus-style forwards [foo@bar.com] subject
5517     (goto-char (point-min))
5518     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
5519       (replace-match ""))
5520
5521     ;; and off the end
5522     (goto-char (point-max))
5523     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
5524       (replace-match ""))
5525
5526     ;; and finally, any whitespace that was left-over
5527     (goto-char (point-min))
5528     (while (re-search-forward "^[ \t]+" nil t)
5529       (replace-match ""))
5530     (goto-char (point-max))
5531     (while (re-search-backward "[ \t]+$" nil t)
5532       (replace-match ""))
5533
5534     (buffer-string)))
5535
5536 ;;; Forwarding messages.
5537
5538 (defvar message-forward-decoded-p nil
5539   "Non-nil means the original message is decoded.")
5540
5541 (defun message-forward-subject-author-subject (subject)
5542   "Generate a SUBJECT for a forwarded message.
5543 The form is: [Source] Subject, where if the original message was mail,
5544 Source is the sender, and if the original message was news, Source is
5545 the list of newsgroups is was posted to."
5546   (concat "["
5547           (let ((prefix
5548                  (or (message-fetch-field "newsgroups")
5549                      (message-fetch-field "from")
5550                      "(nowhere)")))
5551             (if message-forward-decoded-p
5552                 prefix
5553               (mail-decode-encoded-word-string prefix)))
5554           "] " subject))
5555
5556 (defun message-forward-subject-fwd (subject)
5557   "Generate a SUBJECT for a forwarded message.
5558 The form is: Fwd: Subject, where Subject is the original subject of
5559 the message."
5560   (concat "Fwd: " subject))
5561
5562 (defun message-make-forward-subject ()
5563   "Return a Subject header suitable for the message in the current buffer."
5564   (save-excursion
5565     (save-restriction
5566       (message-narrow-to-head-1)
5567       (let ((funcs message-make-forward-subject-function)
5568             (subject (message-fetch-field "Subject")))
5569         (setq subject
5570               (if subject
5571                   (if message-forward-decoded-p
5572                       subject
5573                     (mail-decode-encoded-word-string subject))
5574                 ""))
5575         (if message-wash-forwarded-subjects
5576             (setq subject (message-wash-subject subject)))
5577         ;; Make sure funcs is a list.
5578         (and funcs
5579              (not (listp funcs))
5580              (setq funcs (list funcs)))
5581         ;; Apply funcs in order, passing subject generated by previous
5582         ;; func to the next one.
5583         (while funcs
5584           (when (message-functionp (car funcs))
5585             (setq subject (funcall (car funcs) subject)))
5586           (setq funcs (cdr funcs)))
5587         subject))))
5588
5589 (eval-when-compile
5590   (defvar gnus-article-decoded-p))
5591
5592
5593 ;;;###autoload
5594 (defun message-forward (&optional news digest)
5595   "Forward the current message via mail.
5596 Optional NEWS will use news to forward instead of mail.
5597 Optional DIGEST will use digest to forward."
5598   (interactive "P")
5599   (let* ((cur (current-buffer))
5600          (message-forward-decoded-p
5601           (if (local-variable-p 'gnus-article-decoded-p (current-buffer))
5602               gnus-article-decoded-p ;; In an article buffer.
5603             message-forward-decoded-p))
5604          (subject (message-make-forward-subject)))
5605     (if news
5606         (message-news nil subject)
5607       (message-mail nil subject))
5608     (message-forward-make-body cur digest)))
5609
5610 ;;;###autoload
5611 (defun message-forward-make-body (forward-buffer &optional digest)
5612   ;; Put point where we want it before inserting the forwarded
5613   ;; message.
5614   (if message-forward-before-signature
5615       (message-goto-body)
5616     (goto-char (point-max)))
5617   (if message-forward-as-mime
5618       (if digest
5619           (insert "\n<#multipart type=digest>\n")
5620         (if message-forward-show-mml
5621             (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
5622           (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")))
5623     (insert "\n-------------------- Start of forwarded message --------------------\n"))
5624   (let ((b (point)) e)
5625     (if digest
5626         (if message-forward-as-mime
5627             (insert-buffer-substring forward-buffer)
5628           (mml-insert-buffer forward-buffer))
5629       (if (and message-forward-show-mml
5630                (not message-forward-decoded-p))
5631           (insert
5632            (with-temp-buffer
5633              (mm-disable-multibyte-mule4)
5634              (insert
5635               (with-current-buffer forward-buffer
5636                 (mm-string-as-unibyte (buffer-string))))
5637              (mm-enable-multibyte-mule4)
5638              (mime-to-mml)
5639              (goto-char (point-min))
5640              (when (looking-at "From ")
5641                (replace-match "X-From-Line: "))
5642              (buffer-string)))
5643         (save-restriction
5644           (narrow-to-region (point) (point))
5645           (mml-insert-buffer forward-buffer)
5646           (goto-char (point-min))
5647           (when (looking-at "From ")
5648             (replace-match "X-From-Line: "))
5649           (goto-char (point-max)))))
5650     (setq e (point))
5651     (if message-forward-as-mime
5652         (if digest
5653             (insert "<#/multipart>\n")
5654           (if message-forward-show-mml
5655               (insert "<#/mml>\n")
5656             (insert "<#/part>\n")))
5657       (insert "\n-------------------- End of forwarded message --------------------\n"))
5658     (if (and digest message-forward-as-mime)
5659         (save-restriction
5660           (narrow-to-region b e)
5661           (goto-char b)
5662           (narrow-to-region (point)
5663                             (or (search-forward "\n\n" nil t) (point)))
5664           (delete-region (point-min) (point-max)))
5665       (when (and (not current-prefix-arg)
5666                  message-forward-ignored-headers
5667                  ;; don't remove CTE, X-Gnus etc when doing "raw" forward:
5668                  message-forward-show-mml)
5669         (save-restriction
5670           (narrow-to-region b e)
5671           (goto-char b)
5672           (narrow-to-region (point)
5673                             (or (search-forward "\n\n" nil t) (point)))
5674           (message-remove-header message-forward-ignored-headers t)))))
5675   (message-position-point))
5676
5677 ;;;###autoload
5678 (defun message-forward-rmail-make-body (forward-buffer)
5679   (save-window-excursion
5680     (set-buffer forward-buffer)
5681     ;; Rmail doesn't have rmail-msg-restore-non-pruned-header in Emacs
5682     ;; 20.  FIXIT, or we drop support for rmail in Emacs 20.
5683     (if (rmail-msg-is-pruned)
5684         (rmail-msg-restore-non-pruned-header)))
5685   (message-forward-make-body forward-buffer))
5686
5687 ;;;###autoload
5688 (defun message-insinuate-rmail ()
5689   "Let RMAIL uses message to forward."
5690   (interactive)
5691   (setq rmail-enable-mime-composing t)
5692   (setq rmail-insert-mime-forwarded-message-function
5693         'message-forward-rmail-make-body))
5694
5695 ;;;###autoload
5696 (defun message-resend (address)
5697   "Resend the current article to ADDRESS."
5698   (interactive
5699    (list (message-read-from-minibuffer "Resend message to: ")))
5700   (message "Resending message to %s..." address)
5701   (save-excursion
5702     (let ((cur (current-buffer))
5703           beg)
5704       ;; We first set up a normal mail buffer.
5705       (unless (message-mail-user-agent)
5706         (set-buffer (get-buffer-create " *message resend*"))
5707         (erase-buffer))
5708       (let ((message-this-is-mail t))
5709         (message-setup `((To . ,address))))
5710       ;; Insert our usual headers.
5711       (message-generate-headers '(From Date To))
5712       (message-narrow-to-headers)
5713       ;; Rename them all to "Resent-*".
5714       (while (re-search-forward "^[A-Za-z]" nil t)
5715         (forward-char -1)
5716         (insert "Resent-"))
5717       (widen)
5718       (forward-line)
5719       (delete-region (point) (point-max))
5720       (setq beg (point))
5721       ;; Insert the message to be resent.
5722       (insert-buffer-substring cur)
5723       (goto-char (point-min))
5724       (search-forward "\n\n")
5725       (forward-char -1)
5726       (save-restriction
5727         (narrow-to-region beg (point))
5728         (message-remove-header message-ignored-resent-headers t)
5729         (goto-char (point-max)))
5730       (insert mail-header-separator)
5731       ;; Rename all old ("Also-")Resent headers.
5732       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
5733         (beginning-of-line)
5734         (insert "Also-"))
5735       ;; Quote any "From " lines at the beginning.
5736       (goto-char beg)
5737       (when (looking-at "From ")
5738         (replace-match "X-From-Line: "))
5739       ;; Send it.
5740       (let ((message-inhibit-body-encoding t)
5741             message-required-mail-headers)
5742         (message-send-mail))
5743       (kill-buffer (current-buffer)))
5744     (message "Resending message to %s...done" address)))
5745
5746 ;;;###autoload
5747 (defun message-bounce ()
5748   "Re-mail the current message.
5749 This only makes sense if the current message is a bounce message that
5750 contains some mail you have written which has been bounced back to
5751 you."
5752   (interactive)
5753   (let ((handles (mm-dissect-buffer t))
5754         boundary)
5755     (message-pop-to-buffer (message-buffer-name "bounce"))
5756     (if (stringp (car handles))
5757         ;; This is a MIME bounce.
5758         (mm-insert-part (car (last handles)))
5759       ;; This is a non-MIME bounce, so we try to remove things
5760       ;; manually.
5761       (mm-insert-part handles)
5762       (undo-boundary)
5763       (goto-char (point-min))
5764       (search-forward "\n\n" nil t)
5765       (if (or (and (re-search-forward message-unsent-separator nil t)
5766                    (forward-line 1))
5767               (re-search-forward "^Return-Path:.*\n" nil t))
5768           ;; We remove everything before the bounced mail.
5769           (delete-region
5770            (point-min)
5771            (if (re-search-forward "^[^ \n\t]+:" nil t)
5772                (match-beginning 0)
5773              (point)))
5774         (when (re-search-backward "^.?From .*\n" nil t)
5775           (delete-region (match-beginning 0) (match-end 0)))))
5776     (mm-enable-multibyte)
5777     (mime-to-mml)
5778     (save-restriction
5779       (message-narrow-to-head-1)
5780       (message-remove-header message-ignored-bounced-headers t)
5781       (goto-char (point-max))
5782       (insert mail-header-separator))
5783     (message-position-point)))
5784
5785 ;;;
5786 ;;; Interactive entry points for new message buffers.
5787 ;;;
5788
5789 ;;;###autoload
5790 (defun message-mail-other-window (&optional to subject)
5791   "Like `message-mail' command, but display mail buffer in another window."
5792   (interactive)
5793   (unless (message-mail-user-agent)
5794     (let ((pop-up-windows t)
5795           (special-display-buffer-names nil)
5796           (special-display-regexps nil)
5797           (same-window-buffer-names nil)
5798           (same-window-regexps nil))
5799       (message-pop-to-buffer (message-buffer-name "mail" to))))
5800   (let ((message-this-is-mail t))
5801     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
5802                    nil nil 'switch-to-buffer-other-window)))
5803
5804 ;;;###autoload
5805 (defun message-mail-other-frame (&optional to subject)
5806   "Like `message-mail' command, but display mail buffer in another frame."
5807   (interactive)
5808   (unless (message-mail-user-agent)
5809     (let ((pop-up-frames t)
5810           (special-display-buffer-names nil)
5811           (special-display-regexps nil)
5812           (same-window-buffer-names nil)
5813           (same-window-regexps nil))
5814       (message-pop-to-buffer (message-buffer-name "mail" to))))
5815   (let ((message-this-is-mail t))
5816     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
5817                    nil nil 'switch-to-buffer-other-frame)))
5818
5819 ;;;###autoload
5820 (defun message-news-other-window (&optional newsgroups subject)
5821   "Start editing a news article to be sent."
5822   (interactive)
5823   (let ((pop-up-windows t)
5824         (special-display-buffer-names nil)
5825         (special-display-regexps nil)
5826         (same-window-buffer-names nil)
5827         (same-window-regexps nil))
5828     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
5829   (let ((message-this-is-news t))
5830     (message-setup `((Newsgroups . ,(or newsgroups ""))
5831                      (Subject . ,(or subject ""))))))
5832
5833 ;;;###autoload
5834 (defun message-news-other-frame (&optional newsgroups subject)
5835   "Start editing a news article to be sent."
5836   (interactive)
5837   (let ((pop-up-frames t)
5838         (special-display-buffer-names nil)
5839         (special-display-regexps nil)
5840         (same-window-buffer-names nil)
5841         (same-window-regexps nil))
5842     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
5843   (let ((message-this-is-news t))
5844     (message-setup `((Newsgroups . ,(or newsgroups ""))
5845                      (Subject . ,(or subject ""))))))
5846
5847 ;;; underline.el
5848
5849 ;; This code should be moved to underline.el (from which it is stolen).
5850
5851 ;;;###autoload
5852 (defun bold-region (start end)
5853   "Bold all nonblank characters in the region.
5854 Works by overstriking characters.
5855 Called from program, takes two arguments START and END
5856 which specify the range to operate on."
5857   (interactive "r")
5858   (save-excursion
5859     (let ((end1 (make-marker)))
5860       (move-marker end1 (max start end))
5861       (goto-char (min start end))
5862       (while (< (point) end1)
5863         (or (looking-at "[_\^@- ]")
5864             (insert (char-after) "\b"))
5865         (forward-char 1)))))
5866
5867 ;;;###autoload
5868 (defun unbold-region (start end)
5869   "Remove all boldness (overstruck characters) in the region.
5870 Called from program, takes two arguments START and END
5871 which specify the range to operate on."
5872   (interactive "r")
5873   (save-excursion
5874     (let ((end1 (make-marker)))
5875       (move-marker end1 (max start end))
5876       (goto-char (min start end))
5877       (while (re-search-forward "\b" end1 t)
5878         (if (eq (char-after) (char-after (- (point) 2)))
5879             (delete-char -2))))))
5880
5881 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
5882
5883 ;; Support for toolbar
5884 (eval-when-compile
5885   (defvar tool-bar-map)
5886   (defvar tool-bar-mode))
5887
5888 (defun message-tool-bar-local-item-from-menu (command icon in-map &optional from-map &rest props)
5889   ;; We need to make tool bar entries in local keymaps with
5890   ;; `tool-bar-local-item-from-menu' in Emacs > 21.3
5891   (if (fboundp 'tool-bar-local-item-from-menu)
5892       ;; This is for Emacs 21.3
5893       (tool-bar-local-item-from-menu command icon in-map from-map props)
5894     (tool-bar-add-item-from-menu command icon from-map props)))
5895
5896 (defun message-tool-bar-map ()
5897   (or message-tool-bar-map
5898       (setq message-tool-bar-map
5899             (and 
5900              (condition-case nil (require 'tool-bar) (error nil))
5901              (fboundp 'tool-bar-add-item-from-menu)
5902              tool-bar-mode
5903              (let ((tool-bar-map (copy-keymap tool-bar-map))
5904                    (load-path (mm-image-load-path)))
5905                ;; Zap some items which aren't so relevant and take
5906                ;; up space.
5907                (dolist (key '(print-buffer kill-buffer save-buffer
5908                                            write-file dired open-file))
5909                  (define-key tool-bar-map (vector key) nil))
5910                (message-tool-bar-local-item-from-menu
5911                 'message-send-and-exit "mail_send" tool-bar-map message-mode-map)
5912                (message-tool-bar-local-item-from-menu
5913                 'message-kill-buffer "close" tool-bar-map message-mode-map)
5914                (message-tool-bar-local-item-from-menu
5915                     'message-dont-send "cancel" tool-bar-map message-mode-map)
5916                (message-tool-bar-local-item-from-menu
5917                 'mml-attach-file "attach" tool-bar-map mml-mode-map)
5918                (message-tool-bar-local-item-from-menu
5919                 'ispell-message "spell" tool-bar-map message-mode-map)
5920                (message-tool-bar-local-item-from-menu
5921                 'message-insert-importance-high "important"
5922                 tool-bar-map message-mode-map)
5923                (message-tool-bar-local-item-from-menu
5924                 'message-insert-importance-low "unimportant"
5925                 tool-bar-map message-mode-map)
5926                (message-tool-bar-local-item-from-menu
5927                 'message-insert-disposition-notification-to "receipt"
5928                 tool-bar-map message-mode-map)
5929                tool-bar-map)))))
5930
5931 ;;; Group name completion.
5932
5933 (defcustom message-newgroups-header-regexp
5934   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
5935   "Regexp that match headers that lists groups."
5936   :group 'message
5937   :type 'regexp)
5938
5939 (defcustom message-completion-alist
5940   (list (cons message-newgroups-header-regexp 'message-expand-group)
5941         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name)
5942         '("^\\(Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):" 
5943           . message-expand-name)
5944         '("^\\(Disposition-Notification-To\\|Return-Receipt-To\\):" 
5945           . message-expand-name))
5946   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
5947   :group 'message
5948   :type '(alist :key-type regexp :value-type function))
5949
5950 (defcustom message-tab-body-function nil
5951   "*Function to execute when `message-tab' (TAB) is executed in the body.
5952 If nil, the function bound in `text-mode-map' or `global-map' is executed."
5953   :group 'message
5954   :type 'function)
5955
5956 (defun message-tab ()
5957   "Complete names according to `message-completion-alist'.
5958 Execute function specified by `message-tab-body-function' when not in
5959 those headers."
5960   (interactive)
5961   (let ((alist message-completion-alist))
5962     (while (and alist
5963                 (let ((mail-abbrev-mode-regexp (caar alist)))
5964                   (not (mail-abbrev-in-expansion-header-p))))
5965       (setq alist (cdr alist)))
5966     (funcall (or (cdar alist) message-tab-body-function
5967                  (lookup-key text-mode-map "\t")
5968                  (lookup-key global-map "\t")
5969                  'indent-relative))))
5970
5971 (defun message-expand-group ()
5972   "Expand the group name under point."
5973   (let* ((b (save-excursion
5974               (save-restriction
5975                 (narrow-to-region
5976                  (save-excursion
5977                    (beginning-of-line)
5978                    (skip-chars-forward "^:")
5979                    (1+ (point)))
5980                  (point))
5981                 (skip-chars-backward "^, \t\n") (point))))
5982          (completion-ignore-case t)
5983          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
5984                                             (point))))
5985          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
5986          (completions (all-completions string hashtb))
5987          comp)
5988     (delete-region b (point))
5989     (cond
5990      ((= (length completions) 1)
5991       (if (string= (car completions) string)
5992           (progn
5993             (insert string)
5994             (message "Only matching group"))
5995         (insert (car completions))))
5996      ((and (setq comp (try-completion string hashtb))
5997            (not (string= comp string)))
5998       (insert comp))
5999      (t
6000       (insert string)
6001       (if (not comp)
6002           (message "No matching groups")
6003         (save-selected-window
6004           (pop-to-buffer "*Completions*")
6005           (buffer-disable-undo)
6006           (let ((buffer-read-only nil))
6007             (erase-buffer)
6008             (let ((standard-output (current-buffer)))
6009               (display-completion-list (sort completions 'string<)))
6010             (goto-char (point-min))
6011             (delete-region (point) (progn (forward-line 3) (point))))))))))
6012
6013 (defun message-expand-name ()
6014   (if (fboundp 'bbdb-complete-name)
6015       (bbdb-complete-name)
6016     (expand-abbrev)))
6017
6018 ;;; Help stuff.
6019
6020 (defun message-talkative-question (ask question show &rest text)
6021   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
6022 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
6023 The following arguments may contain lists of values."
6024   (if (and show
6025            (setq text (message-flatten-list text)))
6026       (save-window-excursion
6027         (save-excursion
6028           (with-output-to-temp-buffer " *MESSAGE information message*"
6029             (set-buffer " *MESSAGE information message*")
6030             (fundamental-mode)          ; for Emacs 20.4+
6031             (mapcar 'princ text)
6032             (goto-char (point-min))))
6033         (funcall ask question))
6034     (funcall ask question)))
6035
6036 (defun message-flatten-list (list)
6037   "Return a new, flat list that contains all elements of LIST.
6038
6039 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
6040 => (1 2 3 4 5 6 7)"
6041   (cond ((consp list)
6042          (apply 'append (mapcar 'message-flatten-list list)))
6043         (list
6044          (list list))))
6045
6046 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
6047   "Create and return a buffer with name based on NAME using `generate-new-buffer.'
6048 Then clone the local variables and values from the old buffer to the
6049 new one, cloning only the locals having a substring matching the
6050 regexp varstr."
6051   (let ((oldbuf (current-buffer)))
6052     (save-excursion
6053       (set-buffer (generate-new-buffer name))
6054       (message-clone-locals oldbuf varstr)
6055       (current-buffer))))
6056
6057 (defun message-clone-locals (buffer &optional varstr)
6058   "Clone the local variables from BUFFER to the current buffer."
6059   (let ((locals (save-excursion
6060                   (set-buffer buffer)
6061                   (buffer-local-variables)))
6062         (regexp "^gnus\\|^nn\\|^message\\|^user-mail-address"))
6063     (mapcar
6064      (lambda (local)
6065        (when (and (consp local)
6066                   (car local)
6067                   (string-match regexp (symbol-name (car local)))
6068                   (or (null varstr)
6069                       (string-match varstr (symbol-name (car local)))))
6070          (ignore-errors
6071            (set (make-local-variable (car local))
6072                 (cdr local)))))
6073      locals)))
6074
6075 ;;; Miscellaneous functions
6076
6077 (defsubst message-replace-chars-in-string (string from to)
6078   (mm-subst-char-in-string from to string))
6079
6080 ;;;
6081 ;;; MIME functions
6082 ;;;
6083
6084 (defvar message-inhibit-body-encoding nil)
6085
6086 (defun message-encode-message-body ()
6087   (unless message-inhibit-body-encoding
6088     (let ((mail-parse-charset (or mail-parse-charset
6089                                   message-default-charset))
6090           (case-fold-search t)
6091           lines content-type-p)
6092       (message-goto-body)
6093       (save-restriction
6094         (narrow-to-region (point) (point-max))
6095         (let ((new (mml-generate-mime)))
6096           (when new
6097             (delete-region (point-min) (point-max))
6098             (insert new)
6099             (goto-char (point-min))
6100             (if (eq (aref new 0) ?\n)
6101                 (delete-char 1)
6102               (search-forward "\n\n")
6103               (setq lines (buffer-substring (point-min) (1- (point))))
6104               (delete-region (point-min) (point))))))
6105       (save-restriction
6106         (message-narrow-to-headers-or-head)
6107         (message-remove-header "Mime-Version")
6108         (goto-char (point-max))
6109         (insert "MIME-Version: 1.0\n")
6110         (when lines
6111           (insert lines))
6112         (setq content-type-p
6113               (or mml-boundary
6114                   (re-search-backward "^Content-Type:" nil t))))
6115       (save-restriction
6116         (message-narrow-to-headers-or-head)
6117         (message-remove-first-header "Content-Type")
6118         (message-remove-first-header "Content-Transfer-Encoding"))
6119       ;; We always make sure that the message has a Content-Type
6120       ;; header.  This is because some broken MTAs and MUAs get
6121       ;; awfully confused when confronted with a message with a
6122       ;; MIME-Version header and without a Content-Type header.  For
6123       ;; instance, Solaris' /usr/bin/mail.
6124       (unless content-type-p
6125         (goto-char (point-min))
6126         ;; For unknown reason, MIME-Version doesn't exist.
6127         (when (re-search-forward "^MIME-Version:" nil t)
6128           (forward-line 1)
6129           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
6130
6131 (defun message-read-from-minibuffer (prompt &optional initial-contents)
6132   "Read from the minibuffer while providing abbrev expansion."
6133   (if (fboundp 'mail-abbrevs-setup)
6134       (let ((mail-abbrev-mode-regexp "")
6135             (minibuffer-setup-hook 'mail-abbrevs-setup)
6136             (minibuffer-local-map message-minibuffer-local-map))
6137         (read-from-minibuffer prompt initial-contents))
6138     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
6139           (minibuffer-local-map message-minibuffer-local-map))
6140       (read-string prompt initial-contents))))
6141
6142 (defun message-use-alternative-email-as-from ()
6143   (require 'mail-utils)
6144   (let* ((fields '("To" "Cc"))
6145          (emails
6146           (split-string
6147            (mail-strip-quoted-names
6148             (mapconcat 'message-fetch-reply-field fields ","))
6149            "[ \f\t\n\r\v,]+"))
6150          email)
6151     (while emails
6152       (if (string-match message-alternative-emails (car emails))
6153           (setq email (car emails)
6154                 emails nil))
6155       (pop emails))
6156     (unless (or (not email) (equal email user-mail-address))
6157       (goto-char (point-max))
6158       (insert "From: " email "\n"))))
6159
6160 (defun message-options-get (symbol)
6161   (cdr (assq symbol message-options)))
6162
6163 (defun message-options-set (symbol value)
6164   (let ((the-cons (assq symbol message-options)))
6165     (if the-cons
6166         (if value
6167             (setcdr the-cons value)
6168           (setq message-options (delq the-cons message-options)))
6169       (and value
6170            (push (cons symbol value) message-options))))
6171   value)
6172
6173 (defun message-options-set-recipient ()
6174   (save-restriction
6175     (message-narrow-to-headers-or-head)
6176     (message-options-set 'message-sender
6177                          (mail-strip-quoted-names
6178                           (message-fetch-field "from")))
6179     (message-options-set 'message-recipients
6180                          (mail-strip-quoted-names
6181                           (let ((to (message-fetch-field "to"))
6182                                 (cc (message-fetch-field "cc"))
6183                                 (bcc (message-fetch-field "bcc")))
6184                             (concat
6185                              (or to "")
6186                              (if (and to cc) ", ")
6187                              (or cc "")
6188                              (if (and (or to cc) bcc) ", ")
6189                              (or bcc "")))))))
6190
6191 (when (featurep 'xemacs)
6192   (require 'messagexmas)
6193   (message-xmas-redefine))
6194
6195 (provide 'message)
6196
6197 (run-hooks 'message-load-hook)
6198
6199 ;; Local Variables:
6200 ;; coding: iso-8859-1
6201 ;; End:
6202
6203 ;;; message.el ends here