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