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