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