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