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