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