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