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