Synch to Gnus 200306082217.
[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                 (mail-header-set-message-id message-reply-headers nil)
3347                 (mail-header-set-references message-reply-headers nil)
3348                 (widen)
3349                 (message-narrow-to-headers)
3350                 (if (let ((case-fold-search t))
3351                       (re-search-forward "^References:\\([\t ]+.+\n\\)+"
3352                                          nil t))
3353                     (replace-match "")
3354                   (goto-char (point-max)))
3355                 (mail-header-format
3356                  (list (or (assq 'References message-header-format-alist)
3357                            '(References . message-fill-references)))
3358                  (list (cons 'References (mapconcat 'identity
3359                                                     (nreverse newrefs) " "))))
3360                 (backward-delete-char 1))))))
3361       (unless arg
3362         (if (and message-suspend-font-lock-when-citing
3363                  (boundp 'font-lock-mode)
3364                  (symbol-value 'font-lock-mode))
3365             (unwind-protect
3366                 (progn
3367                   (sit-for 0)
3368                   (font-lock-mode 0)
3369                   (funcall message-cite-function))
3370               (font-lock-mode 1))
3371           (funcall message-cite-function)))
3372       (message-exchange-point-and-mark)
3373       (unless (bolp)
3374         (insert ?\n))
3375       (unless modified
3376         (setq message-checksum (message-checksum))))))
3377
3378 (defun message-yank-buffer (buffer)
3379   "Insert BUFFER into the current buffer and quote it."
3380   (interactive "bYank buffer: ")
3381   (let ((message-reply-buffer buffer))
3382     (save-window-excursion
3383       (message-yank-original))))
3384
3385 (defun message-buffers ()
3386   "Return a list of active message buffers."
3387   (let (buffers)
3388     (save-excursion
3389       (dolist (buffer (buffer-list t))
3390         (set-buffer buffer)
3391         (when (and (eq major-mode 'message-mode)
3392                    (null message-sent-message-via))
3393           (push (buffer-name buffer) buffers))))
3394     (nreverse buffers)))
3395
3396 (defun message-cite-original-without-signature ()
3397   "Cite function in the standard Message manner."
3398   (let ((start (point))
3399         (end (mark t))
3400         (functions
3401          (when message-indent-citation-function
3402            (if (listp message-indent-citation-function)
3403                message-indent-citation-function
3404              (list message-indent-citation-function))))
3405         (message-reply-headers (or message-reply-headers
3406                                    (make-mail-header))))
3407     (mail-header-set-from message-reply-headers
3408                           (save-restriction
3409                             (narrow-to-region
3410                              (point)
3411                              (if (search-forward "\n\n" nil t)
3412                                  (1- (point))
3413                                (point-max)))
3414                             (or (message-fetch-field "from")
3415                                 "unknown sender")))
3416     ;; Allow undoing.
3417     (undo-boundary)
3418     (goto-char end)
3419     (when (re-search-backward message-signature-separator start t)
3420       ;; Also peel off any blank lines before the signature.
3421       (forward-line -1)
3422       (while (looking-at "^[ \t]*$")
3423         (forward-line -1))
3424       (forward-line 1)
3425       (delete-region (point) end)
3426       (unless (search-backward "\n\n" start t)
3427         ;; Insert a blank line if it is peeled off.
3428         (insert "\n")))
3429     (goto-char start)
3430     (while functions
3431       (funcall (pop functions)))
3432     (when message-citation-line-function
3433       (unless (bolp)
3434         (insert "\n"))
3435       (funcall message-citation-line-function))))
3436
3437 (eval-when-compile (defvar mail-citation-hook))         ;Compiler directive
3438 (defun message-cite-original ()
3439   "Cite function in the standard Message manner."
3440   (if (and (boundp 'mail-citation-hook)
3441            mail-citation-hook)
3442       (run-hooks 'mail-citation-hook)
3443     (let ((start (point))
3444           (end (mark t))
3445           (functions
3446            (when message-indent-citation-function
3447              (if (listp message-indent-citation-function)
3448                  message-indent-citation-function
3449                (list message-indent-citation-function))))
3450           (message-reply-headers (or message-reply-headers
3451                                      (make-mail-header))))
3452       (mail-header-set-from message-reply-headers
3453                             (save-restriction
3454                               (narrow-to-region
3455                                (point)
3456                                (if (search-forward "\n\n" nil t)
3457                                    (1- (point))
3458                                  (point-max)))
3459                               (or (message-fetch-field "from")
3460                                   "unknown sender")))
3461       (goto-char start)
3462       (while functions
3463         (funcall (pop functions)))
3464       (when message-citation-line-function
3465         (unless (bolp)
3466           (insert "\n"))
3467         (funcall message-citation-line-function)))))
3468
3469 (defun message-insert-citation-line ()
3470   "Insert a simple citation line."
3471   (when message-reply-headers
3472     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
3473
3474 (defun message-position-on-field (header &rest afters)
3475   (let ((case-fold-search t))
3476     (save-restriction
3477       (narrow-to-region
3478        (goto-char (point-min))
3479        (progn
3480          (re-search-forward
3481           (concat "^" (regexp-quote mail-header-separator) "$"))
3482          (match-beginning 0)))
3483       (goto-char (point-min))
3484       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
3485           (progn
3486             (re-search-forward "^[^ \t]" nil 'move)
3487             (beginning-of-line)
3488             (skip-chars-backward "\n")
3489             t)
3490         (while (and afters
3491                     (not (re-search-forward
3492                           (concat "^" (regexp-quote (car afters)) ":")
3493                           nil t)))
3494           (pop afters))
3495         (when afters
3496           (re-search-forward "^[^ \t]" nil 'move)
3497           (beginning-of-line))
3498         (insert header ": \n")
3499         (forward-char -1)
3500         nil))))
3501
3502 (defun message-remove-signature ()
3503   "Remove the signature from the text between point and mark.
3504 The text will also be indented the normal way."
3505   (save-excursion
3506     (let ((start (point))
3507           mark)
3508       (if (not (re-search-forward message-signature-separator (mark t) t))
3509           ;; No signature here, so we just indent the cited text.
3510           (message-indent-citation)
3511         ;; Find the last non-empty line.
3512         (forward-line -1)
3513         (while (looking-at "[ \t]*$")
3514           (forward-line -1))
3515         (forward-line 1)
3516         (setq mark (set-marker (make-marker) (point)))
3517         (goto-char start)
3518         (message-indent-citation)
3519         ;; Enable undoing the deletion.
3520         (undo-boundary)
3521         (delete-region mark (mark t))
3522         (set-marker mark nil)))))
3523
3524 \f
3525
3526 ;;;
3527 ;;; Sending messages
3528 ;;;
3529
3530 ;; Avoid byte-compile warning.
3531 (defvar message-encoding-buffer nil)
3532 (defvar message-edit-buffer nil)
3533 (defvar message-mime-mode nil)
3534
3535 (defun message-send-and-exit (&optional arg)
3536   "Send message like `message-send', then, if no errors, exit from mail buffer."
3537   (interactive "P")
3538   (let ((buf (current-buffer))
3539         (actions message-exit-actions)
3540         (frame (selected-frame))
3541         (org-frame message-original-frame))
3542     (when (and (message-send arg)
3543                (buffer-name buf))
3544       (if message-kill-buffer-on-exit
3545           (kill-buffer buf)
3546         (bury-buffer buf)
3547         (when (eq buf (current-buffer))
3548           (message-bury buf)))
3549       (message-do-actions actions)
3550       (message-delete-frame frame org-frame)
3551       t)))
3552
3553 (defun message-dont-send ()
3554   "Don't send the message you have been editing.
3555 Instead, just auto-save the buffer and then bury it."
3556   (interactive)
3557   (set-buffer-modified-p t)
3558   (save-buffer)
3559   (let ((actions message-postpone-actions)
3560         (frame (selected-frame))
3561         (org-frame message-original-frame))
3562     (message-bury (current-buffer))
3563     (message-do-actions actions)
3564     (message-delete-frame frame org-frame)))
3565
3566 (defun message-kill-buffer ()
3567   "Kill the current buffer."
3568   (interactive)
3569   (when (or (not (buffer-modified-p))
3570             (eq t message-kill-buffer-query-function)
3571             (funcall message-kill-buffer-query-function
3572                      "The buffer modified; kill anyway? "))
3573     (let ((actions message-kill-actions)
3574           (draft-article message-draft-article)
3575           (auto-save-file-name buffer-auto-save-file-name)
3576           (file-name buffer-file-name)
3577           (modified (buffer-modified-p))
3578           (frame (selected-frame))
3579           (org-frame message-original-frame))
3580       (setq buffer-file-name nil)
3581       (kill-buffer (current-buffer))
3582       (when (and message-kill-buffer-and-remove-file
3583                  (or (and auto-save-file-name
3584                           (file-exists-p auto-save-file-name))
3585                      (and file-name
3586                           (file-exists-p file-name)))
3587                  (yes-or-no-p (format "Remove the backup file%s? "
3588                                       (if modified " too" ""))))
3589         (ignore-errors
3590           (delete-file auto-save-file-name))
3591         (let ((message-draft-article draft-article))
3592           (message-disassociate-draft)))
3593       (message-do-actions actions)
3594       (message-delete-frame frame org-frame)))
3595   (message ""))
3596
3597 (defun message-mimic-kill-buffer ()
3598   "Kill the current buffer with query.  This is an imitation for
3599 `kill-buffer', but it will delete a message frame."
3600   (interactive)
3601   (let ((bufname (read-buffer (format "Kill buffer: (default %s) "
3602                                       (buffer-name))))
3603         message-kill-buffer-and-remove-file)
3604     (when (or (not bufname)
3605               (string-equal bufname "")
3606               (string-equal bufname (buffer-name)))
3607       (message-kill-buffer))))
3608
3609 (defun message-delete-frame (frame org-frame)
3610   "Delete frame for editing message."
3611   (when (and (or (static-if (featurep 'xemacs)
3612                      (device-on-window-system-p)
3613                    window-system)
3614                  (>= emacs-major-version 20))
3615              (or (and (eq message-delete-frame-on-exit t)
3616                       (select-frame frame)
3617                       (or (eq frame org-frame)
3618                           (prog1
3619                               (y-or-n-p "Delete this frame?")
3620                             (message ""))))
3621                  (and (eq message-delete-frame-on-exit 'ask)
3622                       (select-frame frame)
3623                       (prog1
3624                           (y-or-n-p "Delete this frame?")
3625                         (message "")))))
3626     (delete-frame frame)))
3627
3628 (defun message-bury (buffer)
3629   "Bury this mail BUFFER."
3630   (let ((newbuf (other-buffer buffer)))
3631     (bury-buffer buffer)
3632     (if (and (fboundp 'frame-parameters)
3633              (cdr (assq 'dedicated (frame-parameters)))
3634              (not (null (delq (selected-frame) (visible-frame-list)))))
3635         (delete-frame (selected-frame))
3636       (switch-to-buffer newbuf))))
3637
3638 (defun message-send (&optional arg)
3639   "Send the message in the current buffer.
3640 If `message-interactive' is non-nil, wait for success indication or
3641 error messages, and inform user.
3642 Otherwise any failure is reported in a message back to the user from
3643 the mailer.
3644 The usage of ARG is defined by the instance that called Message.
3645 It should typically alter the sending method in some way or other."
3646   (interactive "P")
3647   ;; Disabled test.
3648   (when (or (buffer-modified-p)
3649             (message-check-element 'unchanged)
3650             (y-or-n-p "No changes in the buffer; really send? "))
3651     ;; Make it possible to undo the coming changes.
3652     (undo-boundary)
3653     (let ((inhibit-read-only t))
3654       (put-text-property (point-min) (point-max) 'read-only nil))
3655     (run-hooks 'message-send-hook)
3656     (message-fix-before-sending)
3657     (message message-sending-message)
3658     (let ((message-encoding-buffer
3659            (message-generate-new-buffer-clone-locals " message encoding"))
3660           (message-edit-buffer (current-buffer))
3661           (message-mime-mode mime-edit-mode-flag)
3662           (alist message-send-method-alist)
3663           (success t)
3664           elem sent dont-barf-on-no-method
3665           (message-options message-options))
3666       (unwind-protect
3667           (progn
3668             (message-options-set-recipient)
3669             (save-excursion
3670               (set-buffer message-encoding-buffer)
3671               (erase-buffer)
3672               ;; ;; Avoid copying text props (except hard newlines).
3673               ;; T-gnus change: copy all text props from the editing buffer
3674               ;; into the encoding buffer.
3675               (insert-buffer-substring message-edit-buffer)
3676               (funcall message-encode-function)
3677               (while (and success
3678                           (setq elem (pop alist)))
3679                 (when (funcall (cadr elem))
3680                   (when (and
3681                          (or (not (memq (car elem)
3682                                         message-sent-message-via))
3683                              (not (message-fetch-field "supersedes"))
3684                              (if (or (message-gnksa-enable-p 'multiple-copies)
3685                                      (not (eq (car elem) 'news)))
3686                                  (y-or-n-p
3687                                   (format
3688                                    "Already sent message via %s; resend? "
3689                                    (car elem)))
3690                                (error "Denied posting -- multiple copies")))
3691                          (setq success (funcall (caddr elem) arg)))
3692                     (setq sent t)))))
3693             (unless
3694                 (or
3695                  sent
3696                  (not success)
3697                  (let ((fcc (message-fetch-field "Fcc"))
3698                        (gcc (message-fetch-field "Gcc")))
3699                    (when (or fcc gcc)
3700                      (or
3701                       (eq message-allow-no-recipients 'always)
3702                       (and (not (eq message-allow-no-recipients 'never))
3703                            (setq dont-barf-on-no-method
3704                                  (gnus-y-or-n-p
3705                                   (format "No receiver, perform %s anyway? "
3706                                           (cond ((and fcc gcc) "Fcc and Gcc")
3707                                                 (fcc "Fcc")
3708                                                 (t "Gcc"))))))))))
3709               (error "No methods specified to send by"))
3710             (when (or dont-barf-on-no-method
3711                       (and success sent))
3712               (message-do-fcc)
3713               (save-excursion
3714                 (run-hooks 'message-sent-hook))
3715               (message "Sending...done")
3716               ;; Mark the buffer as unmodified and delete auto-save.
3717               (set-buffer-modified-p nil)
3718               (delete-auto-save-file-if-necessary t)
3719               (message-disassociate-draft)
3720               ;; Delete other mail buffers and stuff.
3721               (message-do-send-housekeeping)
3722               (message-do-actions message-send-actions)
3723               ;; Return success.
3724               t))
3725         (kill-buffer message-encoding-buffer)))))
3726
3727 (defun message-send-via-mail (arg)
3728   "Send the current message via mail."
3729   (message-send-mail arg))
3730
3731 (defun message-send-via-news (arg)
3732   "Send the current message via news."
3733   (message-send-news arg))
3734
3735 (defmacro message-check (type &rest forms)
3736   "Eval FORMS if TYPE is to be checked."
3737   `(or (message-check-element ,type)
3738        (save-excursion
3739          ,@forms)))
3740
3741 (put 'message-check 'lisp-indent-function 1)
3742 (put 'message-check 'edebug-form-spec '(form body))
3743
3744 ;; Advise the function `invisible-region'.
3745 (let (current-load-list)
3746   (eval
3747    `(defadvice invisible-region (around add-mime-edit-invisible (start end)
3748                                         activate)
3749       "Advised by T-gnus Message.
3750 Add the text property `mime-edit-invisible' to an invisible text when
3751 the buffer's major mode is `message-mode'.  The added property will be
3752 used to distinguish whether the invisible text is a MIME part or not."
3753       ,(if (featurep 'xemacs)
3754            '(if (eq ?\n (char-after start))
3755                 (setq start (1+ start)))
3756          '(if (eq ?\n (char-after (1- end)))
3757               (setq end (1- end))))
3758       (setq ad-return-value
3759             (if (eq 'message-mode major-mode)
3760                 (add-text-properties start end
3761                                      '(invisible t mime-edit-invisible t))
3762               (put-text-property start end 'invisible t))))))
3763
3764 (defun message-text-with-property (prop)
3765   "Return a list of all points where the text has PROP."
3766   (let ((points nil)
3767         (point (point-min)))
3768     (save-excursion
3769       (while (< point (point-max))
3770         (when (get-text-property point prop)
3771           (push point points))
3772         (incf point)))
3773     (nreverse points)))
3774
3775 (defun message-fix-before-sending ()
3776   "Do various things to make the message nice before sending it."
3777   ;; Make sure there's a newline at the end of the message.
3778   (widen)
3779   (goto-char (point-max))
3780   (unless (bolp)
3781     (insert "\n"))
3782   ;; Make the hidden headers visible.
3783   (let ((points (message-text-with-property 'message-hidden)))
3784     (when points
3785       (goto-char (car points))
3786       (dolist (point points)
3787         (add-text-properties point (1+ point)
3788                              '(invisible nil intangible nil)))))
3789   ;; Make invisible text visible except for the mime parts which may
3790   ;; be inserted by the MIME-Edit.
3791   (message-check 'invisible-text
3792     ;; FIXME T-gnus: It should also detect invisible overlays.
3793     (let (from
3794           (to (point-min))
3795           mime-from mime-to hidden-start)
3796       (while (setq from (text-property-any to (point-max) 'invisible t))
3797         (setq to (or (text-property-not-all from (point-max) 'invisible t)
3798                      (point-max))
3799               mime-to from)
3800         (while (setq mime-from (text-property-any mime-to to
3801                                                   'mime-edit-invisible t))
3802           (when (> mime-from mime-to)
3803             (setq hidden-start (or hidden-start mime-to))
3804             (add-text-properties mime-to mime-from
3805                                  '(invisible nil face highlight
3806                                              font-lock-face highlight)))
3807           (setq mime-to (or (text-property-not-all mime-from to
3808                                                    'mime-edit-invisible t)
3809                             to)))
3810         (when (< mime-to to)
3811           (setq hidden-start (or hidden-start mime-to))
3812           (add-text-properties mime-to to
3813                                '(invisible nil face highlight
3814                                            font-lock-face highlight))))
3815       (when hidden-start
3816         (goto-char hidden-start)
3817         (set-window-start (selected-window) (gnus-point-at-bol))
3818         (unless (yes-or-no-p
3819                  "Invisible text found and made visible; continue sending? ")
3820           (error "Invisible text found and made visible")))))
3821   (message-check 'illegible-text
3822     (let ((mm-7bit-chars "\x20-\x7f\r\n\t\x7\x8\xb\xc\x1f\x1b")
3823           found choice)
3824       (message-goto-body)
3825       (skip-chars-forward mm-7bit-chars)
3826       (while (not (eobp))
3827         (when (let ((char (char-after)))
3828                 (or (< (mm-char-int char) 128)
3829                     (and (mm-multibyte-p)
3830                          (> (length (mm-find-mime-charset-region
3831                                      (point) (point-max)))
3832                             1))))
3833           (message-overlay-put (message-make-overlay (point) (1+ (point)))
3834                                'face 'highlight)
3835           (setq found t))
3836         (forward-char)
3837         (skip-chars-forward mm-7bit-chars))
3838       (when found
3839         (setq choice
3840               (gnus-multiple-choice
3841                "Non-printable characters found.  Continue sending?"
3842                '((?d "Remove non-printable characters and send")
3843                  (?r "Replace non-printable characters with dots and send")
3844                  (?i "Ignore non-printable characters and send")
3845                  (?e "Continue editing"))))
3846         (if (eq choice ?e)
3847           (error "Non-printable characters"))
3848         (message-goto-body)
3849         (skip-chars-forward mm-7bit-chars)
3850         (while (not (eobp))
3851           (when (let ((char (char-after)))
3852                   (or (< (mm-char-int char) 128)
3853                       (and (mm-multibyte-p)
3854                            ;; Fixme: Wrong for Emacs 22 and for things
3855                            ;; like undecable utf-8.  Should at least
3856                            ;; use find-coding-systems-region.
3857                            (memq (char-charset char)
3858                                  '(eight-bit-control eight-bit-graphic
3859                                                      control-1)))))
3860             (if (eq choice ?i)
3861                 (message-kill-all-overlays)
3862               (delete-char 1)
3863               (when (eq choice ?r)
3864                 (insert "."))))
3865           (forward-char)
3866           (skip-chars-forward mm-7bit-chars))))))
3867
3868 (defun message-add-action (action &rest types)
3869   "Add ACTION to be performed when doing an exit of type TYPES."
3870   (while types
3871     (add-to-list (intern (format "message-%s-actions" (pop types)))
3872                  action)))
3873
3874 (defun message-delete-action (action &rest types)
3875   "Delete ACTION from lists of actions performed when doing an exit of type TYPES."
3876   (let (var)
3877     (while types
3878       (set (setq var (intern (format "message-%s-actions" (pop types))))
3879            (delq action (symbol-value var))))))
3880
3881 (defun message-do-actions (actions)
3882   "Perform all actions in ACTIONS."
3883   ;; Now perform actions on successful sending.
3884   (while actions
3885     (ignore-errors
3886       (cond
3887        ;; A simple function.
3888        ((functionp (car actions))
3889         (funcall (car actions)))
3890        ;; Something to be evaled.
3891        (t
3892         (eval (car actions)))))
3893     (pop actions)))
3894
3895 (defsubst message-maybe-split-and-send-mail ()
3896   "Split a message if necessary, and send it via mail.
3897 Returns nil if sending succeeded, returns any string if sending failed.
3898 This sub function is for exclusive use of `message-send-mail'."
3899   (let ((mime-edit-split-ignored-field-regexp
3900          mime-edit-split-ignored-field-regexp)
3901         (case-fold-search t)
3902         failure)
3903     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
3904       (setq mime-edit-split-ignored-field-regexp
3905             (concat (substring mime-edit-split-ignored-field-regexp
3906                                0 (match-beginning 0))
3907                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
3908                     "_so_don't_rape_it!"
3909                     (substring mime-edit-split-ignored-field-regexp
3910                                (match-end 0)))))
3911     (setq failure
3912           (or
3913            (catch 'message-sending-mail-failure
3914              (mime-edit-maybe-split-and-send
3915               (function
3916                (lambda ()
3917                  (interactive)
3918                  (save-restriction
3919                    (std11-narrow-to-header mail-header-separator)
3920                    (goto-char (point-min))
3921                    (when (re-search-forward "^Message-ID:" nil t)
3922                      (delete-region (match-end 0) (std11-field-end))
3923                      (insert " " (message-make-message-id))))
3924                  (condition-case err
3925                      (funcall (or message-send-mail-real-function
3926                                   message-send-mail-function))
3927                    (error
3928                     (throw 'message-sending-mail-failure err))))))
3929              nil)
3930            (condition-case err
3931                (progn
3932                  (funcall (or message-send-mail-real-function
3933                               message-send-mail-function))
3934                  nil)
3935              (error err))))
3936     (when failure
3937       (if (eq 'error (car failure))
3938           (cadr failure)
3939         (prin1-to-string failure)))))
3940
3941 (defun message-send-mail-partially ()
3942   "Send mail as message/partial."
3943   ;; replace the header delimiter with a blank line
3944   (goto-char (point-min))
3945   (re-search-forward
3946    (concat "^" (regexp-quote mail-header-separator) "\n"))
3947   (replace-match "\n")
3948   (run-hooks 'message-send-mail-hook)
3949   (let ((p (goto-char (point-min)))
3950         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
3951         (curbuf (current-buffer))
3952         (id (message-make-message-id)) (n 1)
3953         plist total  header required-mail-headers)
3954     (while (not (eobp))
3955       (if (< (point-max) (+ p message-send-mail-partially-limit))
3956           (goto-char (point-max))
3957         (goto-char (+ p message-send-mail-partially-limit))
3958         (beginning-of-line)
3959         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
3960       (push p plist)
3961       (setq p (point)))
3962     (setq total (length plist))
3963     (push (point-max) plist)
3964     (setq plist (nreverse plist))
3965     (unwind-protect
3966         (save-excursion
3967           (setq p (pop plist))
3968           (while plist
3969             (set-buffer curbuf)
3970             (copy-to-buffer tembuf p (car plist))
3971             (set-buffer tembuf)
3972             (goto-char (point-min))
3973             (if header
3974                 (progn
3975                   (goto-char (point-min))
3976                   (narrow-to-region (point) (point))
3977                   (insert header))
3978               (message-goto-eoh)
3979               (setq header (buffer-substring (point-min) (point)))
3980               (goto-char (point-min))
3981               (narrow-to-region (point) (point))
3982               (insert header)
3983               (message-remove-header "Mime-Version")
3984               (message-remove-header "Content-Type")
3985               (message-remove-header "Content-Transfer-Encoding")
3986               (message-remove-header "Message-ID")
3987               (message-remove-header "Lines")
3988               (goto-char (point-max))
3989               (insert "Mime-Version: 1.0\n")
3990               (setq header (buffer-string)))
3991             (goto-char (point-max))
3992             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
3993                             id n total))
3994             (forward-char -1)
3995             (let ((mail-header-separator ""))
3996               (when (memq 'Message-ID message-required-mail-headers)
3997                 (insert "Message-ID: " (message-make-message-id) "\n"))
3998               (when (memq 'Lines message-required-mail-headers)
3999                 (insert "Lines: " (message-make-lines) "\n"))
4000               (message-goto-subject)
4001               (end-of-line)
4002               (insert (format " (%d/%d)" n total))
4003               (widen)
4004               (mm-with-unibyte-current-buffer
4005                 (funcall (or message-send-mail-real-function
4006                              message-send-mail-function))))
4007             (setq n (+ n 1))
4008             (setq p (pop plist))
4009             (erase-buffer)))
4010       (kill-buffer tembuf))))
4011
4012 (defun message-send-mail (&optional arg)
4013   (require 'mail-utils)
4014   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
4015          (case-fold-search nil)
4016          (news (message-news-p))
4017          (message-this-is-mail t)
4018          (headers message-required-mail-headers)
4019          failure)
4020     (save-restriction
4021       (message-narrow-to-headers)
4022       ;; Generate the Mail-Followup-To header if the header is not there...
4023       (if (and (message-subscribed-p)
4024                (not (mail-fetch-field "mail-followup-to")))
4025           (setq headers
4026                 (cons
4027                  (cons "Mail-Followup-To" (message-make-mail-followup-to))
4028                  message-required-mail-headers))
4029         ;; otherwise, delete the MFT header if the field is empty
4030         (when (equal "" (mail-fetch-field "mail-followup-to"))
4031           (message-remove-header "^Mail-Followup-To:")))
4032       ;; Insert some headers.
4033       (let ((message-deletable-headers
4034              (if news nil message-deletable-headers)))
4035         (message-generate-headers headers))
4036       ;; Let the user do all of the above.
4037       (run-hooks 'message-header-hook))
4038     (if (not (message-check-mail-syntax))
4039         (progn
4040           (message "")
4041           nil)
4042       (unwind-protect
4043           (save-excursion
4044             (set-buffer tembuf)
4045             (erase-buffer)
4046             ;; ;; Avoid copying text props (except hard newlines).
4047             ;; T-gnus change: copy all text props from the editing buffer
4048             ;; into the encoding buffer.
4049             (insert-buffer-substring message-encoding-buffer)
4050             ;; Remove some headers.
4051             (save-restriction
4052               (message-narrow-to-headers)
4053 ;; We Semi-gnus people have no use for it.
4054 ;;            ;; We (re)generate the Lines header.
4055 ;;            (when (memq 'Lines message-required-mail-headers)
4056 ;;              (message-generate-headers '(Lines)))
4057               (message-remove-header message-ignored-mail-headers t))
4058             (goto-char (point-max))
4059             ;; require one newline at the end.
4060             (or (= (preceding-char) ?\n)
4061                 (insert ?\n))
4062             (message-cleanup-headers)
4063             ;; FIXME: we're inserting the courtesy copy after encoding.
4064             ;; This is wrong if the courtesy copy string contains
4065             ;; non-ASCII characters. -- jh
4066             (when
4067                 (save-restriction
4068                   (message-narrow-to-headers)
4069                   (and news
4070                        (or (message-fetch-field "cc")
4071                            (message-fetch-field "bcc")
4072                            (message-fetch-field "to"))
4073                        (let ((content-type (mime-read-Content-Type)))
4074                          (and
4075                           (or
4076                            (not content-type)
4077                            (and
4078                             (eq 'text (cdr (assq 'type content-type)))
4079                             (eq 'plain (cdr (assq 'subtype content-type)))))
4080                           (not
4081                            (string= "base64"
4082                                     (mime-read-Content-Transfer-Encoding)))))))
4083               (message-insert-courtesy-copy))
4084             (setq failure (message-maybe-split-and-send-mail)))
4085         (kill-buffer tembuf))
4086       (set-buffer message-edit-buffer)
4087       (if failure
4088           (progn
4089             (message "Couldn't send message via mail: %s" failure)
4090             nil)
4091         (push 'mail message-sent-message-via)))))
4092
4093 (defun message-send-mail-with-sendmail ()
4094   "Send off the prepared buffer with sendmail."
4095   (let ((errbuf (if message-interactive
4096                     (message-generate-new-buffer-clone-locals
4097                      " sendmail errors")
4098                   0))
4099         resend-to-addresses delimline)
4100     (unwind-protect
4101         (progn
4102           (let ((case-fold-search t))
4103             (save-restriction
4104               (message-narrow-to-headers)
4105               (setq resend-to-addresses (message-fetch-field "resent-to")))
4106             ;; Change header-delimiter to be what sendmail expects.
4107             (goto-char (point-min))
4108             (re-search-forward
4109              (concat "^" (regexp-quote mail-header-separator) "\n"))
4110             (replace-match "\n")
4111             (backward-char 1)
4112             (setq delimline (point-marker))
4113             (run-hooks 'message-send-mail-hook)
4114             ;; Insert an extra newline if we need it to work around
4115             ;; Sun's bug that swallows newlines.
4116             (goto-char (1+ delimline))
4117             (when (eval message-mailer-swallows-blank-line)
4118               (newline))
4119             (when message-interactive
4120               (save-excursion
4121                 (set-buffer errbuf)
4122                 (erase-buffer))))
4123           (let* ((default-directory "/")
4124                  (cpr (as-binary-process
4125                        (apply
4126                         'call-process-region
4127                         (append
4128                          (list (point-min) (point-max)
4129                                (if (boundp 'sendmail-program)
4130                                    sendmail-program
4131                                  "/usr/lib/sendmail")
4132                                nil errbuf nil "-oi")
4133                          ;; Always specify who from,
4134                          ;; since some systems have broken sendmails.
4135                          ;; But some systems are more broken with -f, so
4136                          ;; we'll let users override this.
4137                          (if (null message-sendmail-f-is-evil)
4138                              (list "-f" (message-sendmail-envelope-from)))
4139                          ;; These mean "report errors by mail"
4140                          ;; and "deliver in background".
4141                          (if (null message-interactive) '("-oem" "-odb"))
4142                          ;; Get the addresses from the message
4143                          ;; unless this is a resend.
4144                          ;; We must not do that for a resend
4145                          ;; because we would find the original addresses.
4146                          ;; For a resend, include the specific addresses.
4147                          (if resend-to-addresses
4148                              (list resend-to-addresses)
4149                            '("-t")))))))
4150             (unless (or (null cpr) (zerop cpr))
4151               (error "Sending...failed with exit value %d" cpr)))
4152           (when message-interactive
4153             (save-excursion
4154               (set-buffer errbuf)
4155               (goto-char (point-min))
4156               (while (re-search-forward "\n\n* *" nil t)
4157                 (replace-match "; "))
4158               (if (not (zerop (buffer-size)))
4159                   (error "Sending...failed to %s"
4160                          (buffer-string))))))
4161       (when (bufferp errbuf)
4162         (kill-buffer errbuf)))))
4163
4164 (defun message-send-mail-with-qmail ()
4165   "Pass the prepared message buffer to qmail-inject.
4166 Refer to the documentation for the variable `message-send-mail-function'
4167 to find out how to use this."
4168   ;; replace the header delimiter with a blank line
4169   (goto-char (point-min))
4170   (re-search-forward
4171    (concat "^" (regexp-quote mail-header-separator) "\n"))
4172   (replace-match "\n")
4173   (backward-char 1)
4174   (run-hooks 'message-send-mail-hook)
4175   ;; send the message
4176   (case
4177       (as-binary-process
4178        (apply
4179         'call-process-region 1 (point-max) message-qmail-inject-program
4180         nil nil nil
4181         ;; qmail-inject's default behaviour is to look for addresses on the
4182         ;; command line; if there're none, it scans the headers.
4183         ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
4184         ;;
4185         ;; in general, ALL of qmail-inject's defaults are perfect for simply
4186         ;; reading a formatted (i. e., at least a To: or Resent-To header)
4187         ;; message from stdin.
4188         ;;
4189         ;; qmail also has the advantage of not having been raped by
4190         ;; various vendors, so we don't have to allow for that, either --
4191         ;; compare this with message-send-mail-with-sendmail and weep
4192         ;; for sendmail's lost innocence.
4193         ;;
4194         ;; all this is way cool coz it lets us keep the arguments entirely
4195         ;; free for -inject-arguments -- a big win for the user and for us
4196         ;; since we don't have to play that double-guessing game and the user
4197         ;; gets full control (no gestapo'ish -f's, for instance).  --sj
4198         (if (functionp message-qmail-inject-args)
4199             (funcall message-qmail-inject-args)
4200           message-qmail-inject-args)))
4201     ;; qmail-inject doesn't say anything on it's stdout/stderr,
4202     ;; we have to look at the retval instead
4203     (0 nil)
4204     (100 (error "qmail-inject reported permanent failure"))
4205     (111 (error "qmail-inject reported transient failure"))
4206     ;; should never happen
4207     (t   (error "qmail-inject reported unknown failure"))))
4208
4209 (defun message-send-mail-with-mh ()
4210   "Send the prepared message buffer with mh."
4211   (let ((mh-previous-window-config nil)
4212         (name (mh-new-draft-name)))
4213     (setq buffer-file-name name)
4214     ;; MH wants to generate these headers itself.
4215     (when message-mh-deletable-headers
4216       (let ((headers message-mh-deletable-headers))
4217         (while headers
4218           (goto-char (point-min))
4219           (and (re-search-forward
4220                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4221                (message-delete-line))
4222           (pop headers))))
4223     (run-hooks 'message-send-mail-hook)
4224     ;; Pass it on to mh.
4225     (mh-send-letter)))
4226
4227 (defun message-send-mail-with-smtp ()
4228   "Send off the prepared buffer with SMTP."
4229   (require 'smtp) ; XXX
4230   (let ((case-fold-search t)
4231         recipients)
4232     (save-restriction
4233       (message-narrow-to-headers)
4234       (setq recipients
4235             ;; XXX: Should be replaced by better one.
4236             (smtp-deduce-address-list (current-buffer)
4237                                       (point-min) (point-max)))
4238       ;; Remove BCC lines.
4239       (message-remove-header "bcc"))
4240     ;; replace the header delimiter with a blank line.
4241     (goto-char (point-min))
4242     (re-search-forward
4243      (concat "^" (regexp-quote mail-header-separator) "\n"))
4244     (replace-match "\n")
4245     (backward-char 1)
4246     (run-hooks 'message-send-mail-hook)
4247     (if recipients
4248         (smtp-send-buffer user-mail-address recipients (current-buffer))
4249       (error "Sending failed; no recipients"))))
4250
4251 (defsubst message-maybe-split-and-send-news (method)
4252   "Split a message if necessary, and send it via news.
4253 Returns nil if sending succeeded, returns t if sending failed.
4254 This sub function is for exclusive use of `message-send-news'."
4255   (let ((mime-edit-split-ignored-field-regexp
4256          mime-edit-split-ignored-field-regexp)
4257         (case-fold-search t))
4258     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
4259       (setq mime-edit-split-ignored-field-regexp
4260             (concat (substring mime-edit-split-ignored-field-regexp
4261                                0 (match-beginning 0))
4262                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
4263                     "_so_don't_rape_it!"
4264                     (substring mime-edit-split-ignored-field-regexp
4265                                (match-end 0)))))
4266     (or
4267      (catch 'message-sending-news-failure
4268        (mime-edit-maybe-split-and-send
4269         (function
4270          (lambda ()
4271            (interactive)
4272            (save-restriction
4273              (std11-narrow-to-header mail-header-separator)
4274              (goto-char (point-min))
4275              (when (re-search-forward "^Message-ID:" nil t)
4276                (delete-region (match-end 0) (std11-field-end))
4277                (insert " " (message-make-message-id))))
4278            (unless (funcall message-send-news-function method)
4279              (throw 'message-sending-news-failure t)))))
4280        nil)
4281      (not (funcall message-send-news-function method)))))
4282
4283 (defun message-smtpmail-send-it ()
4284   "Send the prepared message buffer with `smtpmail-send-it'.
4285 This only differs from `smtpmail-send-it' that this command evaluates
4286 `message-send-mail-hook' just before sending a message.  It is useful
4287 if your ISP requires the POP-before-SMTP authentication.  See the
4288 documentation for the function `mail-source-touch-pop'."
4289   (run-hooks 'message-send-mail-hook)
4290   (smtpmail-send-it))
4291
4292 (defun message-canlock-generate ()
4293   "Return a string that is non-trival to guess.
4294 Do not use this for anything important, it is cryptographically weak."
4295   (let (sha1-maximum-internal-length)
4296     (sha1 (concat (message-unique-id)
4297                   (format "%x%x%x" (random) (random t) (random))
4298                   (prin1-to-string (recent-keys))
4299                   (prin1-to-string (garbage-collect))))))
4300
4301 (defun message-canlock-password ()
4302   "The password used by message for cancel locks.
4303 This is the value of `canlock-password', if that option is non-nil.
4304 Otherwise, generate and save a value for `canlock-password' first."
4305   (unless canlock-password
4306     (customize-save-variable 'canlock-password (message-canlock-generate))
4307     (setq canlock-password-for-verify canlock-password))
4308   canlock-password)
4309
4310 (defun message-insert-canlock ()
4311   (when message-insert-canlock
4312     (message-canlock-password)
4313     (canlock-insert-header)))
4314
4315 (defun message-send-news (&optional arg)
4316   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
4317          (case-fold-search nil)
4318          (method (if (functionp message-post-method)
4319                      (funcall message-post-method arg)
4320                    message-post-method))
4321          (newsgroups-field (save-restriction
4322                              (message-narrow-to-headers-or-head)
4323                              (message-fetch-field "Newsgroups")))
4324          (followup-field (save-restriction
4325                            (message-narrow-to-headers-or-head)
4326                            (message-fetch-field "Followup-To")))
4327          ;; BUG: We really need to get the charset for each name in the
4328          ;; Newsgroups and Followup-To lines to allow crossposting
4329          ;; between group namess with incompatible character sets.
4330          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
4331          (group-field-charset
4332           (gnus-group-name-charset method newsgroups-field))
4333          (followup-field-charset
4334           (gnus-group-name-charset method (or followup-field "")))
4335          (mime-field-encoding-method-alist
4336           (append (when group-field-charset
4337                     (list (cons "Newsgroups" group-field-charset)))
4338                   (when followup-field-charset
4339                     (list (cons "Followup-To" followup-field-charset)))
4340                   mime-field-encoding-method-alist))
4341          (message-syntax-checks
4342           (if (and arg
4343                    (listp message-syntax-checks))
4344               (cons '(existing-newsgroups . disabled)
4345                     message-syntax-checks)
4346             message-syntax-checks))
4347          (message-this-is-news t)
4348          result)
4349     (save-restriction
4350       (message-narrow-to-headers)
4351       ;; Insert some headers.
4352       (message-generate-headers message-required-news-headers)
4353       (message-insert-canlock)
4354       ;; Let the user do all of the above.
4355       (run-hooks 'message-header-hook))
4356     ;; Note: This check will be disabled by the ".*" default value for
4357     ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
4358     (when (and group-field-charset
4359                (listp message-syntax-checks))
4360       (setq message-syntax-checks
4361             (cons '(valid-newsgroups . disabled)
4362                   message-syntax-checks)))
4363     (message-cleanup-headers)
4364     (if (not (let ((message-post-method method))
4365                (message-check-news-syntax)))
4366         nil
4367       (unwind-protect
4368           (save-excursion
4369             (set-buffer tembuf)
4370             (buffer-disable-undo)
4371             (erase-buffer)
4372             (insert-buffer-substring message-encoding-buffer)
4373             ;; Remove some headers.
4374             (save-restriction
4375               (message-narrow-to-headers)
4376 ;; We Semi-gnus people have no use for it.
4377 ;;            ;; We (re)generate the Lines header.
4378 ;;            (when (memq 'Lines message-required-mail-headers)
4379 ;;              (message-generate-headers '(Lines)))
4380               ;; Remove some headers.
4381               (message-remove-header message-ignored-news-headers t))
4382             (goto-char (point-max))
4383             ;; require one newline at the end.
4384             (or (= (preceding-char) ?\n)
4385                 (insert ?\n))
4386             (setq result (message-maybe-split-and-send-news method)))
4387         (kill-buffer tembuf))
4388       (set-buffer message-edit-buffer)
4389       (if result
4390           (progn
4391             (message "Couldn't send message via news: %s"
4392                      (nnheader-get-report (car method)))
4393             nil)
4394         (push 'news message-sent-message-via)))))
4395
4396 ;; 1997-09-29 by MORIOKA Tomohiko
4397 (defun message-send-news-with-gnus (method)
4398   (let ((case-fold-search t))
4399     ;; Remove the delimiter.
4400     (goto-char (point-min))
4401     (re-search-forward
4402      (concat "^" (regexp-quote mail-header-separator) "\n"))
4403     (replace-match "\n")
4404     (backward-char 1)
4405     (run-hooks 'message-send-news-hook)
4406     (gnus-open-server method)
4407     (message "Sending news via %s..." (gnus-server-string method))
4408     (gnus-request-post method)
4409     ))
4410
4411 ;;;
4412 ;;; Header generation & syntax checking.
4413 ;;;
4414
4415 (defun message-check-element (type)
4416   "Return non-nil if this TYPE is not to be checked."
4417   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
4418       t
4419     (let ((able (assq type message-syntax-checks)))
4420       (and (consp able)
4421            (eq (cdr able) 'disabled)))))
4422
4423 (defun message-check-news-syntax ()
4424   "Check the syntax of the message."
4425   (save-excursion
4426     (save-restriction
4427       (widen)
4428       (and
4429        ;; We narrow to the headers and check them first.
4430        (save-excursion
4431          (save-restriction
4432            (message-narrow-to-headers)
4433            (message-check-news-header-syntax)))
4434        ;; Check the body.
4435        (save-excursion
4436          (set-buffer message-edit-buffer)
4437          (message-check-news-body-syntax))))))
4438
4439 (defun message-check-news-header-syntax ()
4440   (and
4441    ;; Check Newsgroups header.
4442    (message-check 'newsgroups
4443      (let ((group (message-fetch-field "newsgroups")))
4444        (or
4445         (and group
4446              (not (string-match "\\`[ \t]*\\'" group)))
4447         (ignore
4448          (message
4449           "The newsgroups field is empty or missing.  Posting is denied.")))))
4450    ;; Check the Subject header.
4451    (message-check 'subject
4452      (let* ((case-fold-search t)
4453             (subject (message-fetch-field "subject")))
4454        (or
4455         (and subject
4456              (not (string-match "\\`[ \t]*\\'" subject)))
4457         (ignore
4458          (message
4459           "The subject field is empty or missing.  Posting is denied.")))))
4460    ;; Check for commands in Subject.
4461    (message-check 'subject-cmsg
4462      (if (string-match "^cmsg " (message-fetch-field "subject"))
4463          (y-or-n-p
4464           "The control code \"cmsg\" is in the subject.  Really post? ")
4465        t))
4466    ;; Check long header lines.
4467    (message-check 'long-header-lines
4468      (let ((start (point))
4469            (header nil)
4470            (length 0)
4471            found)
4472        (while (and (not found)
4473                    (re-search-forward "^\\([^ \t:]+\\): " nil t))
4474          (if (> (- (point) (match-beginning 0)) 998)
4475              (setq found t
4476                    length (- (point) (match-beginning 0)))
4477            (setq header (match-string-no-properties 1)))
4478          (setq start (match-beginning 0))
4479          (forward-line 1))
4480        (if found
4481            (y-or-n-p (format "Your %s header is too long (%d).  Really post? "
4482                              header length))
4483          t)))
4484    ;; Check for multiple identical headers.
4485    (message-check 'multiple-headers
4486      (let (found)
4487        (while (and (not found)
4488                    (re-search-forward "^[^ \t:]+: " nil t))
4489          (save-excursion
4490            (or (re-search-forward
4491                 (concat "^"
4492                         (regexp-quote
4493                          (setq found
4494                                (buffer-substring
4495                                 (match-beginning 0) (- (match-end 0) 2))))
4496                         ":")
4497                 nil t)
4498                (setq found nil))))
4499        (if found
4500            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
4501          t)))
4502    ;; Check for Version and Sendsys.
4503    (message-check 'sendsys
4504      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
4505          (y-or-n-p
4506           (format "The article contains a %s command.  Really post? "
4507                   (buffer-substring (match-beginning 0)
4508                                     (1- (match-end 0)))))
4509        t))
4510    ;; See whether we can shorten Followup-To.
4511    (message-check 'shorten-followup-to
4512      (let ((newsgroups (message-fetch-field "newsgroups"))
4513            (followup-to (message-fetch-field "followup-to"))
4514            to)
4515        (when (and newsgroups
4516                   (string-match "," newsgroups)
4517                   (not followup-to)
4518                   (not
4519                    (zerop
4520                     (length
4521                      (setq to (completing-read
4522                                "Followups to (default: no Followup-To header) "
4523                                (mapcar #'list
4524                                        (cons "poster"
4525                                              (message-tokenize-header
4526                                               newsgroups)))))))))
4527          (goto-char (point-min))
4528          (insert "Followup-To: " to "\n"))
4529        t))
4530    ;; Check "Shoot me".
4531    (message-check 'shoot
4532      (if (re-search-forward
4533           "Message-ID.*.i-did-not-set--mail-host-address--so-tickle-me" nil t)
4534          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
4535        t))
4536    ;; Check for Approved.
4537    (message-check 'approved
4538      (if (re-search-forward "^Approved:" nil t)
4539          (y-or-n-p "The article contains an Approved header.  Really post? ")
4540        t))
4541    ;; Check the Message-ID header.
4542    (message-check 'message-id
4543      (let* ((case-fold-search t)
4544             (message-id (message-fetch-field "message-id" t)))
4545        (or (not message-id)
4546            ;; Is there an @ in the ID?
4547            (and (string-match "@" message-id)
4548                 ;; Is there a dot in the ID?
4549                 (string-match "@[^.]*\\." message-id)
4550                 ;; Does the ID end with a dot?
4551                 (not (string-match "\\.>" message-id)))
4552            (y-or-n-p
4553             (format "The Message-ID looks strange: \"%s\".  Really post? "
4554                     message-id)))))
4555    ;; Check the Newsgroups & Followup-To headers.
4556    (message-check 'existing-newsgroups
4557      (let* ((case-fold-search t)
4558             (newsgroups (message-fetch-field "newsgroups"))
4559             (followup-to (message-fetch-field "followup-to"))
4560             (groups (message-tokenize-header
4561                      (if followup-to
4562                          (concat newsgroups "," followup-to)
4563                        newsgroups)))
4564             (post-method (if (functionp message-post-method)
4565                              (funcall message-post-method)
4566                            message-post-method))
4567             ;; KLUDGE to handle nnvirtual groups.  Doing this right
4568             ;; would probably involve a new nnoo function.
4569             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
4570             (method (if (and (consp post-method)
4571                              (eq (car post-method) 'nnvirtual)
4572                              gnus-message-group-art)
4573                         (let ((group (car (nnvirtual-find-group-art
4574                                            (car gnus-message-group-art)
4575                                            (cdr gnus-message-group-art)))))
4576                           (gnus-find-method-for-group group))
4577                       post-method))
4578             (known-groups
4579              (mapcar (lambda (n)
4580                        (gnus-group-name-decode
4581                         (gnus-group-real-name n)
4582                         (gnus-group-name-charset method n)))
4583                      (gnus-groups-from-server method)))
4584             errors)
4585        (while groups
4586          (when (and (not (equal (car groups) "poster"))
4587                     (not (member (car groups) known-groups))
4588                     (not (member (car groups) errors)))
4589            (push (car groups) errors))
4590          (pop groups))
4591        (cond
4592         ;; Gnus is not running.
4593         ((or (not (and (boundp 'gnus-active-hashtb)
4594                        gnus-active-hashtb))
4595              (not (boundp 'gnus-read-active-file)))
4596          t)
4597         ;; We don't have all the group names.
4598         ((and (or (not gnus-read-active-file)
4599                   (eq gnus-read-active-file 'some))
4600               errors)
4601          (y-or-n-p
4602           (format
4603            "Really use %s possibly unknown group%s: %s? "
4604            (if (= (length errors) 1) "this" "these")
4605            (if (= (length errors) 1) "" "s")
4606            (mapconcat 'identity errors ", "))))
4607         ;; There were no errors.
4608         ((not errors)
4609          t)
4610         ;; There are unknown groups.
4611         (t
4612          (y-or-n-p
4613           (format
4614            "Really post to %s unknown group%s: %s? "
4615            (if (= (length errors) 1) "this" "these")
4616            (if (= (length errors) 1) "" "s")
4617            (mapconcat 'identity errors ", ")))))))
4618    ;; Check continuation headers.
4619    (message-check 'continuation-headers
4620      (goto-char (point-min))
4621      (let ((do-posting t))
4622        (while (re-search-forward "^[^ \t\n][^:\n]*$" nil t)
4623          (if (y-or-n-p "Fix continuation lines? ")
4624              (progn
4625                (goto-char (match-beginning 0))
4626                (insert " "))
4627            (unless (y-or-n-p "Send anyway? ")
4628              (setq do-posting nil))))
4629        do-posting))
4630    ;; Check the Newsgroups & Followup-To headers for syntax errors.
4631    (message-check 'valid-newsgroups
4632      (let ((case-fold-search t)
4633            (headers '("Newsgroups" "Followup-To"))
4634            header error)
4635        (while (and headers (not error))
4636          (when (setq header (mail-fetch-field (car headers)))
4637            (if (or
4638                 (not
4639                  (string-match
4640                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
4641                   header))
4642                 (memq
4643                  nil (mapcar
4644                       (lambda (g)
4645                         (not (string-match "\\.\\'\\|\\.\\." g)))
4646                       (message-tokenize-header header ","))))
4647                (setq error t)))
4648          (unless error
4649            (pop headers)))
4650        (if (not error)
4651            t
4652          (y-or-n-p
4653           (format "The %s header looks odd: \"%s\".  Really post? "
4654                   (car headers) header)))))
4655    (message-check 'repeated-newsgroups
4656      (let ((case-fold-search t)
4657            (headers '("Newsgroups" "Followup-To"))
4658            header error groups group)
4659        (while (and headers
4660                    (not error))
4661          (when (setq header (mail-fetch-field (pop headers)))
4662            (setq groups (message-tokenize-header header ","))
4663            (while (setq group (pop groups))
4664              (when (member group groups)
4665                (setq error group
4666                      groups nil)))))
4667        (if (not error)
4668            t
4669          (y-or-n-p
4670           (format "Group %s is repeated in headers.  Really post? " error)))))
4671    ;; Check the From header.
4672    (message-check 'from
4673      (let* ((case-fold-search t)
4674             (from (message-fetch-field "from"))
4675             ad)
4676        (cond
4677         ((not from)
4678          (message "There is no From line.  Posting is denied.")
4679          nil)
4680         ((or (not (string-match
4681                    "@[^\\.]*\\."
4682                    (setq ad (nth 1 (mail-extract-address-components
4683                                     from))))) ;larsi@ifi
4684              (string-match "\\.\\." ad) ;larsi@ifi..uio
4685              (string-match "@\\." ad)   ;larsi@.ifi.uio
4686              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4687              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4688              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
4689          (message
4690           "Denied posting -- the From looks strange: \"%s\"." from)
4691          nil)
4692         ((let ((addresses (rfc822-addresses from)))
4693            (while (and addresses
4694                        (not (eq (string-to-char (car addresses)) ?\()))
4695              (setq addresses (cdr addresses)))
4696            addresses)
4697          (message
4698           "Denied posting -- bad From address: \"%s\"." from)
4699          nil)
4700         (t t))))
4701    ;; Check the Reply-To header.
4702    (message-check 'reply-to
4703      (let* ((case-fold-search t)
4704             (reply-to (message-fetch-field "reply-to"))
4705             ad)
4706        (cond
4707         ((not reply-to)
4708          t)
4709         ((string-match "," reply-to)
4710          (y-or-n-p
4711           (format "Multiple Reply-To addresses: \"%s\". Really post? "
4712                   reply-to)))
4713         ((or (not (string-match
4714                    "@[^\\.]*\\."
4715                    (setq ad (nth 1 (mail-extract-address-components
4716                                     reply-to))))) ;larsi@ifi
4717              (string-match "\\.\\." ad) ;larsi@ifi..uio
4718              (string-match "@\\." ad)   ;larsi@.ifi.uio
4719              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4720              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4721              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
4722          (y-or-n-p
4723           (format
4724            "The Reply-To looks strange: \"%s\". Really post? "
4725            reply-to)))
4726         (t t))))))
4727
4728 (defun message-check-news-body-syntax ()
4729   (and
4730    ;; Check for long lines.
4731    (message-check 'long-lines
4732      (goto-char (point-min))
4733      (re-search-forward
4734       (concat "^" (regexp-quote mail-header-separator) "$"))
4735      (forward-line 1)
4736      (while (and
4737              (or (looking-at
4738                   mime-edit-tag-regexp)
4739                  (let ((p (point)))
4740                    (end-of-line)
4741                    (< (- (point) p) 80)))
4742              (zerop (forward-line 1))))
4743      (or (bolp)
4744          (eobp)
4745          (y-or-n-p
4746           "You have lines longer than 79 characters.  Really post? ")))
4747    ;; Check whether the article is empty.
4748    (message-check 'empty
4749      (goto-char (point-min))
4750      (re-search-forward
4751       (concat "^" (regexp-quote mail-header-separator) "$"))
4752      (forward-line 1)
4753      (let ((b (point)))
4754        (goto-char (point-max))
4755        (re-search-backward message-signature-separator nil t)
4756        (beginning-of-line)
4757        (or (re-search-backward "[^ \n\t]" b t)
4758            (if (message-gnksa-enable-p 'empty-article)
4759                (y-or-n-p "Empty article.  Really post? ")
4760              (message "Denied posting -- Empty article.")
4761              nil))))
4762    ;; Check for control characters.
4763    (message-check 'control-chars
4764      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
4765          (y-or-n-p
4766           "The article contains control characters.  Really post? ")
4767        t))
4768    ;; Check 8bit characters.
4769    (message-check '8bit
4770      (message-check-8bit))
4771    ;; Check excessive size.
4772    (message-check 'size
4773      (if (> (buffer-size) 60000)
4774          (y-or-n-p
4775           (format "The article is %d octets long.  Really post? "
4776                   (buffer-size)))
4777        t))
4778    ;; Check whether any new text has been added.
4779    (message-check 'new-text
4780      (or
4781       (not message-checksum)
4782       (not (eq (message-checksum) message-checksum))
4783       (if (message-gnksa-enable-p 'quoted-text-only)
4784           (y-or-n-p
4785            "It looks like no new text has been added.  Really post? ")
4786         (message "Denied posting -- no new text has been added.")
4787         nil)))
4788    ;; Check the length of the signature.
4789    (message-check 'signature
4790      (goto-char (point-max))
4791      (if (> (count-lines (point) (point-max)) 5)
4792          (y-or-n-p
4793           (format
4794            "Your .sig is %d lines; it should be max 4.  Really post? "
4795            (1- (count-lines (point) (point-max)))))
4796        t))
4797    ;; Ensure that text follows last quoted portion.
4798    (message-check 'quoting-style
4799      (goto-char (point-max))
4800      (let ((no-problem t))
4801        (when (search-backward-regexp "^>[^\n]*\n" nil t)
4802          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
4803        (if no-problem
4804            t
4805          (if (message-gnksa-enable-p 'quoted-text-only)
4806              (y-or-n-p "Your text should follow quoted text.  Really post? ")
4807            ;; Ensure that
4808            (goto-char (point-min))
4809            (re-search-forward
4810             (concat "^" (regexp-quote mail-header-separator) "$"))
4811            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
4812                (y-or-n-p "Your text should follow quoted text.  Really post? ")
4813              (message "Denied posting -- only quoted text.")
4814              nil)))))))
4815
4816 (defun message-check-mail-syntax ()
4817   "Check the syntax of the message."
4818   (save-excursion
4819     (save-restriction
4820       (widen)
4821       (and
4822        ;; We narrow to the headers and check them first.
4823        (save-excursion
4824          (save-restriction
4825            (message-narrow-to-headers)
4826            (message-check-mail-header-syntax)))
4827        ;; Check the body.
4828        (save-excursion
4829          (set-buffer message-edit-buffer)
4830          (message-check-mail-body-syntax))))))
4831
4832 (defun message-check-mail-header-syntax ()
4833   t)
4834
4835 (defun message-check-mail-body-syntax ()
4836   (and
4837    ;; Check 8bit characters.
4838    (message-check '8bit
4839      (message-check-8bit)
4840      )))
4841
4842 (defun message-check-8bit ()
4843   "Check the article contains 8bit characters."
4844   (save-excursion
4845     (set-buffer message-encoding-buffer)
4846     (message-narrow-to-headers)
4847     (let* ((case-fold-search t)
4848            (field-value (message-fetch-field "content-transfer-encoding")))
4849       (if (and field-value
4850                (member (downcase field-value) message-8bit-encoding-list))
4851           t
4852         (widen)
4853         (set-buffer (get-buffer-create " message syntax"))
4854         (erase-buffer)
4855         (goto-char (point-min))
4856         (set-buffer-multibyte nil)
4857         (insert-buffer-substring message-encoding-buffer)
4858         (goto-char (point-min))
4859         (if (re-search-forward "[^\x00-\x7f]" nil t)
4860             (y-or-n-p
4861              "The article contains 8bit characters.  Really post? ")
4862           t)))))
4863
4864 (defun message-checksum ()
4865   "Return a \"checksum\" for the current buffer."
4866   (let ((sum 0))
4867     (save-excursion
4868       (goto-char (point-min))
4869       (re-search-forward
4870        (concat "^" (regexp-quote mail-header-separator) "$"))
4871       (while (not (eobp))
4872         (when (not (looking-at "[ \t\n]"))
4873           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
4874                             (char-after))))
4875         (forward-char 1)))
4876     sum))
4877
4878 (defun message-do-fcc ()
4879   "Process Fcc headers in the current buffer."
4880   (let ((case-fold-search t)
4881         (coding-system-for-write 'raw-text)
4882         (output-coding-system 'raw-text)
4883         list file
4884         (mml-externalize-attachments message-fcc-externalize-attachments))
4885     (save-excursion
4886       (save-restriction
4887         (message-narrow-to-headers)
4888         (setq file (message-fetch-field "fcc" t)))
4889       (when file
4890         (set-buffer (get-buffer-create " *message temp*"))
4891         (erase-buffer)
4892         (insert-buffer-substring message-encoding-buffer)
4893         (save-restriction
4894           (message-narrow-to-headers)
4895           (while (setq file (message-fetch-field "fcc"))
4896             (push file list)
4897             (message-remove-header "fcc" nil t)))
4898         (goto-char (point-min))
4899         (when (re-search-forward
4900                (concat "^" (regexp-quote mail-header-separator) "$")
4901                nil t)
4902           (replace-match "" t t))
4903         ;; Process FCC operations.
4904         (while list
4905           (setq file (pop list))
4906           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
4907               ;; Pipe the article to the program in question.
4908               (call-process-region (point-min) (point-max) shell-file-name
4909                                    nil nil nil shell-command-switch
4910                                    (match-string 1 file))
4911             ;; Save the article.
4912             (setq file (expand-file-name file))
4913             (unless (file-exists-p (file-name-directory file))
4914               (make-directory (file-name-directory file) t))
4915             (if (and message-fcc-handler-function
4916                      (not (eq message-fcc-handler-function 'rmail-output)))
4917                 (funcall message-fcc-handler-function file)
4918               (if (and (file-readable-p file) (mail-file-babyl-p file))
4919                   (rmail-output file 1 nil t)
4920                 (let ((mail-use-rfc822 t))
4921                   (rmail-output file 1 t t))))))
4922         (kill-buffer (current-buffer))))))
4923
4924 (defun message-output (filename)
4925   "Append this article to Unix/babyl mail file FILENAME."
4926   (if (and (file-readable-p filename)
4927            (mail-file-babyl-p filename))
4928       (gnus-output-to-rmail filename t)
4929     (gnus-output-to-mail filename t)))
4930
4931 (defun message-cleanup-headers ()
4932   "Do various automatic cleanups of the headers."
4933   ;; Remove empty lines in the header.
4934   (save-restriction
4935     (message-narrow-to-headers)
4936     ;; Remove blank lines.
4937     (while (re-search-forward "^[ \t]*\n" nil t)
4938       (replace-match "" t t))
4939
4940     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
4941     ;; spaces to comma and eliminate spaces around commas.  Eliminate
4942     ;; embedded line breaks.
4943     (goto-char (point-min))
4944     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
4945       (save-restriction
4946         (narrow-to-region
4947          (point)
4948          (if (re-search-forward "^[^ \t]" nil t)
4949              (match-beginning 0)
4950            (forward-line 1)
4951            (point)))
4952         (goto-char (point-min))
4953         (while (re-search-forward "\n[ \t]+" nil t)
4954           (replace-match " " t t))      ;No line breaks (too confusing)
4955         (goto-char (point-min))
4956         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
4957           (replace-match "," t t))
4958         (goto-char (point-min))
4959         ;; Remove trailing commas.
4960         (when (re-search-forward ",+$" nil t)
4961           (replace-match "" t t))))))
4962
4963 (defun message-make-date (&optional now)
4964   "Make a valid data header.
4965 If NOW, use that time instead."
4966   (let* ((now (or now (current-time)))
4967          (zone (nth 8 (decode-time now)))
4968          (sign "+"))
4969     (when (< zone 0)
4970       (setq sign "-")
4971       (setq zone (- zone)))
4972     (concat
4973      ;; The day name of the %a spec is locale-specific.  Pfff.
4974      (format "%s, " (capitalize (car (rassoc (nth 6 (decode-time now))
4975                                              parse-time-weekdays))))
4976      (format-time-string "%d" now)
4977      ;; The month name of the %b spec is locale-specific.  Pfff.
4978      (format " %s "
4979              (capitalize (car (rassoc (nth 4 (decode-time now))
4980                                       parse-time-months))))
4981      (format-time-string "%Y %H:%M:%S " now)
4982      ;; We do all of this because XEmacs doesn't have the %z spec.
4983      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
4984
4985 (defun message-make-followup-subject (subject)
4986   "Make a followup Subject."
4987   (cond
4988    ((and (eq message-use-subject-re 'guess)
4989          (string-match message-subject-encoded-re-regexp subject))
4990     subject)
4991    (message-use-subject-re
4992     (concat "Re: " (message-strip-subject-re subject)))
4993    (t subject)))
4994
4995 (defun message-make-message-id ()
4996   "Make a unique Message-ID."
4997   (concat "<" (message-unique-id)
4998           (let ((psubject (save-excursion (message-fetch-field "subject")))
4999                 (psupersedes
5000                  (save-excursion (message-fetch-field "supersedes"))))
5001             (if (or
5002                  (and message-reply-headers
5003                       (mail-header-references message-reply-headers)
5004                       (mail-header-subject message-reply-headers)
5005                       psubject
5006                       (not (string=
5007                             (message-strip-subject-re
5008                              (mail-header-subject message-reply-headers))
5009                             (message-strip-subject-re psubject))))
5010                  (and psupersedes
5011                       (string-match "_-_@" psupersedes)))
5012                 "_-_" ""))
5013           "@" (message-make-fqdn) ">"))
5014
5015 (defvar message-unique-id-char nil)
5016
5017 ;; If you ever change this function, make sure the new version
5018 ;; cannot generate IDs that the old version could.
5019 ;; You might for example insert a "." somewhere (not next to another dot
5020 ;; or string boundary), or modify the "fsf" string.
5021 (defun message-unique-id ()
5022   ;; Don't use microseconds from (current-time), they may be unsupported.
5023   ;; Instead we use this randomly inited counter.
5024   (setq message-unique-id-char
5025         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
5026            ;; (current-time) returns 16-bit ints,
5027            ;; and 2^16*25 just fits into 4 digits i base 36.
5028            (* 25 25)))
5029   (let ((tm (current-time)))
5030     (concat
5031      (if (memq system-type '(ms-dos emx vax-vms))
5032          (let ((user (downcase (user-login-name))))
5033            (while (string-match "[^a-z0-9_]" user)
5034              (aset user (match-beginning 0) ?_))
5035            user)
5036        (message-number-base36 (user-uid) -1))
5037      (message-number-base36 (+ (car tm)
5038                                (lsh (% message-unique-id-char 25) 16)) 4)
5039      (message-number-base36 (+ (nth 1 tm)
5040                                (lsh (/ message-unique-id-char 25) 16)) 4)
5041      ;; Append a given name, because while the generated ID is unique
5042      ;; to this newsreader, other newsreaders might otherwise generate
5043      ;; the same ID via another algorithm.
5044      ".fsf")))
5045
5046 (defun message-number-base36 (num len)
5047   (if (if (< len 0)
5048           (<= num 0)
5049         (= len 0))
5050       ""
5051     (concat (message-number-base36 (/ num 36) (1- len))
5052             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
5053                                   (% num 36))))))
5054
5055 (defun message-make-organization ()
5056   "Make an Organization header."
5057   (let* ((organization
5058           (when message-user-organization
5059             (if (functionp message-user-organization)
5060                 (funcall message-user-organization)
5061               message-user-organization))))
5062     (with-temp-buffer
5063       (set-buffer-multibyte t)
5064       (cond ((stringp organization)
5065              (insert organization))
5066             ((and (eq t organization)
5067                   message-user-organization-file
5068                   (file-exists-p message-user-organization-file))
5069              (insert-file-contents message-user-organization-file)))
5070       (goto-char (point-min))
5071       (while (re-search-forward "[\t\n]+" nil t)
5072         (replace-match "" t t))
5073       (unless (zerop (buffer-size))
5074         (buffer-string)))))
5075
5076 (defun message-make-lines ()
5077   "Count the number of lines and return numeric string."
5078   (save-excursion
5079     (save-restriction
5080       (widen)
5081       (message-goto-body)
5082       (int-to-string (count-lines (point) (point-max))))))
5083
5084 (defun message-make-references ()
5085   "Return the References header for this message."
5086   (when message-reply-headers
5087     (let ((message-id (mail-header-message-id message-reply-headers))
5088           (references (mail-header-references message-reply-headers))
5089           new-references)
5090       (if (or references message-id)
5091           (concat (or references "") (and references " ")
5092                   (or message-id ""))
5093         nil))))
5094
5095 (defun message-make-in-reply-to ()
5096   "Return the In-Reply-To header for this message."
5097   (when message-reply-headers
5098     (let ((from (mail-header-from message-reply-headers))
5099           (date (mail-header-date message-reply-headers))
5100           (msg-id (mail-header-message-id message-reply-headers)))
5101       (when from
5102         (let ((name (std11-extract-address-components from)))
5103           (concat msg-id (if msg-id " (")
5104                   (or (car name)
5105                       (nth 1 name))
5106                   "'s message of \""
5107                   (if (or (not date) (string= date ""))
5108                       "(unknown date)" date)
5109                   "\"" (if msg-id ")")))))))
5110
5111 (defun message-make-distribution ()
5112   "Make a Distribution header."
5113   (let ((orig-distribution (message-fetch-reply-field "distribution")))
5114     (cond ((functionp message-distribution-function)
5115            (funcall message-distribution-function))
5116           (t orig-distribution))))
5117
5118 (defun message-make-expires ()
5119   "Return an Expires header based on `message-expires'."
5120   (let ((current (current-time))
5121         (future (* 1.0 message-expires 60 60 24)))
5122     ;; Add the future to current.
5123     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
5124     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
5125     (message-make-date current)))
5126
5127 (defun message-make-path ()
5128   "Return uucp path."
5129   (let ((login-name (user-login-name)))
5130     (cond ((null message-user-path)
5131            (concat (system-name) "!" login-name))
5132           ((stringp message-user-path)
5133            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
5134            (concat message-user-path "!" login-name))
5135           (t login-name))))
5136
5137 (defun message-make-from ()
5138   "Make a From header."
5139   (let* ((style message-from-style)
5140          (login (message-make-address))
5141          (fullname
5142           (or (and (boundp 'user-full-name)
5143                    user-full-name)
5144               (user-full-name))))
5145     (when (string= fullname "&")
5146       (setq fullname (user-login-name)))
5147     (with-temp-buffer
5148       (set-buffer-multibyte t)
5149       (cond
5150        ((or (null style)
5151             (equal fullname ""))
5152         (insert login))
5153        ((or (eq style 'angles)
5154             (and (not (eq style 'parens))
5155                  ;; Use angles if no quoting is needed, or if parens would
5156                  ;; need quoting too.
5157                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
5158                      (let ((tmp (concat fullname nil)))
5159                        (while (string-match "([^()]*)" tmp)
5160                          (aset tmp (match-beginning 0) ?-)
5161                          (aset tmp (1- (match-end 0)) ?-))
5162                        (string-match "[\\()]" tmp)))))
5163         (insert fullname)
5164         (insert " <" login ">"))
5165        (t                               ; 'parens or default
5166         (insert login " (")
5167         (let ((fullname-start (point)))
5168           (insert fullname)
5169           (goto-char fullname-start)
5170           ;; RFC 822 says \ and nonmatching parentheses
5171           ;; must be escaped in comments.
5172           ;; Escape every instance of ()\ ...
5173           (while (re-search-forward "[()\\]" nil 1)
5174             (replace-match "\\\\\\&" t))
5175           ;; ... then undo escaping of matching parentheses,
5176           ;; including matching nested parentheses.
5177           (goto-char fullname-start)
5178           (while (re-search-forward
5179                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
5180                   nil 1)
5181             (replace-match "\\1(\\3)" t)
5182             (goto-char fullname-start)))
5183         (insert ")")))
5184       (buffer-string))))
5185
5186 (defun message-make-sender ()
5187   "Return the \"real\" user address.
5188 This function tries to ignore all user modifications, and
5189 give as trustworthy answer as possible."
5190   (concat (user-login-name) "@" (system-name)))
5191
5192 (defun message-make-address ()
5193   "Make the address of the user."
5194   (or (message-user-mail-address)
5195       (concat (user-login-name) "@" (message-make-domain))))
5196
5197 (defun message-user-mail-address ()
5198   "Return the pertinent part of `user-mail-address'."
5199   (when (and user-mail-address
5200              (string-match "@.*\\." user-mail-address))
5201     (if (string-match " " user-mail-address)
5202         (nth 1 (std11-extract-address-components user-mail-address))
5203       user-mail-address)))
5204
5205 (defun message-sendmail-envelope-from ()
5206   "Return the envelope from."
5207   (cond ((eq message-sendmail-envelope-from 'header)
5208          (nth 1 (mail-extract-address-components
5209                  (message-fetch-field "from"))))
5210         ((stringp message-sendmail-envelope-from)
5211          message-sendmail-envelope-from)
5212         (t
5213          (message-make-address))))
5214
5215 (defun message-make-fqdn ()
5216   "Return user's fully qualified domain name."
5217   (let* ((system-name (system-name))
5218          (user-mail (message-user-mail-address))
5219          (user-domain
5220           (if (and user-mail
5221                    (string-match "@\\(.*\\)\\'" user-mail))
5222               (match-string 1 user-mail))))
5223     (cond
5224      ((and message-user-fqdn
5225            (stringp message-user-fqdn)
5226            (string-match message-valid-fqdn-regexp message-user-fqdn)
5227            (not (string-match message-bogus-system-names message-user-fqdn)))
5228       message-user-fqdn)
5229      ;; `message-user-fqdn' seems to be valid
5230      ((and (string-match message-valid-fqdn-regexp system-name)
5231            (not (string-match message-bogus-system-names system-name)))
5232       ;; `system-name' returned the right result.
5233       system-name)
5234      ;; Try `mail-host-address'.
5235      ((and (boundp 'mail-host-address)
5236            (stringp mail-host-address)
5237            (string-match message-valid-fqdn-regexp mail-host-address)
5238            (not (string-match message-bogus-system-names mail-host-address)))
5239       mail-host-address)
5240      ;; We try `user-mail-address' as a backup.
5241      ((and user-domain
5242            (stringp user-domain)
5243            (string-match message-valid-fqdn-regexp user-domain)
5244            (not (string-match message-bogus-system-names user-domain)))
5245       user-domain)
5246      ;; Default to this bogus thing.
5247      (t
5248       (concat system-name
5249               ".i-did-not-set--mail-host-address--so-tickle-me")))))
5250
5251 (defun message-make-host-name ()
5252   "Return the name of the host."
5253   (let ((fqdn (message-make-fqdn)))
5254     (string-match "^[^.]+\\." fqdn)
5255     (substring fqdn 0 (1- (match-end 0)))))
5256
5257 (defun message-make-domain ()
5258   "Return the domain name."
5259   (or mail-host-address
5260       (message-make-fqdn)))
5261
5262 (defun message-to-list-only ()
5263   "Send a message to the list only.
5264 Remove all addresses but the list address from To and Cc headers."
5265   (interactive)
5266   (let ((listaddr (message-make-mail-followup-to t)))
5267     (when listaddr
5268       (save-excursion
5269         (message-remove-header "to")
5270         (message-remove-header "cc")
5271         (message-position-on-field "To" "X-Draft-From")
5272         (insert listaddr)))))
5273
5274 (defun message-make-mail-followup-to (&optional only-show-subscribed)
5275   "Return the Mail-Followup-To header.
5276 If passed the optional argument ONLY-SHOW-SUBSCRIBED only return the
5277 subscribed address (and not the additional To and Cc header contents)."
5278   (let* ((case-fold-search t)
5279          (to (message-fetch-field "To"))
5280          (cc (message-fetch-field "cc"))
5281          (msg-recipients (concat to (and to cc ", ") cc))
5282          (recipients
5283           (mapcar 'mail-strip-quoted-names
5284                   (message-tokenize-header msg-recipients)))
5285          (file-regexps
5286           (if message-subscribed-address-file
5287               (let (begin end item re)
5288                 (save-excursion
5289                   (with-temp-buffer
5290                     (insert-file-contents message-subscribed-address-file)
5291                     (while (not (eobp))
5292                       (setq begin (point))
5293                       (forward-line 1)
5294                       (setq end (point))
5295                       (if (bolp) (setq end (1- end)))
5296                       (setq item (regexp-quote (buffer-substring begin end)))
5297                       (if re (setq re (concat re "\\|" item))
5298                         (setq re (concat "\\`\\(" item))))
5299                     (and re (list (concat re "\\)\\'"))))))))
5300          (mft-regexps (apply 'append message-subscribed-regexps
5301                              (mapcar 'regexp-quote
5302                                      message-subscribed-addresses)
5303                              file-regexps
5304                              (mapcar 'funcall
5305                                      message-subscribed-address-functions))))
5306     (save-match-data
5307       (let ((subscribed-lists nil)
5308             (list
5309              (loop for recipient in recipients
5310                when (loop for regexp in mft-regexps
5311                       when (string-match regexp recipient) return t)
5312                return recipient)))
5313         (when list
5314           (if only-show-subscribed
5315               list
5316             msg-recipients))))))
5317
5318 ;; Dummy to avoid byte-compile warning.
5319 (defvar mule-version)
5320 (defvar emacs-beta-version)
5321 (defvar xemacs-codename)
5322 (defvar gnus-inviolable-extended-version)
5323
5324 (defun message-make-user-agent ()
5325   "Return user-agent info if the value `message-user-agent' is non-nil. If the
5326 \"User-Agent\" field has already exist, remove it."
5327   (when message-user-agent
5328     (save-excursion
5329       (goto-char (point-min))
5330       (let ((case-fold-search t))
5331         (when (re-search-forward "^User-Agent:[\t ]*" nil t)
5332           (delete-region (match-beginning 0) (1+ (std11-field-end)))))))
5333   message-user-agent)
5334
5335 (defun message-idna-inside-rhs-p ()
5336   "Return t iff point is inside a RHS (heuristically).
5337 Only works properly if header contains mailbox-list or address-list.
5338 I.e., calling it on a Subject: header is useless."
5339   (save-restriction
5340     (narrow-to-region (save-excursion (or (re-search-backward "^[^ \t]" nil t)
5341                                           (point-min)))
5342                       (save-excursion (or (re-search-forward "^[^ \t]" nil t)
5343                                           (point-max))))
5344     (if (re-search-backward "[\\\n\r\t ]"
5345                             (save-excursion (search-backward "@" nil t)) t)
5346         ;; whitespace between @ and point
5347         nil
5348       (let ((dquote 1) (paren 1))
5349         (while (save-excursion (re-search-backward "[^\\]\"" nil t dquote))
5350           (incf dquote))
5351         (while (save-excursion (re-search-backward "[^\\]\(" nil t paren))
5352           (incf paren))
5353         (and (= (% dquote 2) 1) (= (% paren 2) 1))))))
5354
5355 (autoload 'idna-to-ascii "idna")
5356
5357 (defun message-idna-to-ascii-rhs-1 (header)
5358   "Interactively potentially IDNA encode domain names in HEADER."
5359   (let (rhs ace start startpos endpos ovl)
5360     (goto-char (point-min))
5361     (while (re-search-forward (concat "^" header) nil t)
5362       (while (re-search-forward "@\\([^ \t\r\n>]+\\)"
5363                                 (or (save-excursion
5364                                       (re-search-forward "^[^ \t]" nil t))
5365                                     (point-max))
5366                                 t)
5367         (setq rhs (match-string-no-properties 1)
5368               startpos (match-beginning 1)
5369               endpos (match-end 1))
5370         (when (save-match-data
5371                 (and (message-idna-inside-rhs-p)
5372                      (setq ace (idna-to-ascii rhs))
5373                      (not (string= rhs ace))
5374                      (if (eq message-use-idna 'ask)
5375                          (unwind-protect
5376                              (progn
5377                                (setq ovl (message-make-overlay startpos
5378                                                                endpos))
5379                                (message-overlay-put ovl 'face 'highlight)
5380                                (y-or-n-p
5381                                 (format "Replace with `%s'? " ace)))
5382                            (message "")
5383                            (message-delete-overlay ovl))
5384                        message-use-idna)))
5385           (replace-match (concat "@" ace)))))))
5386
5387 (defun message-idna-to-ascii-rhs ()
5388   "Possibly IDNA encode non-ASCII domain names in From:, To: and Cc: headers.
5389 See `message-idna-encode'."
5390   (interactive)
5391   (when message-use-idna
5392     (save-excursion
5393       (save-restriction
5394         (message-narrow-to-head)
5395         (message-idna-to-ascii-rhs-1 "From")
5396         (message-idna-to-ascii-rhs-1 "To")
5397         (message-idna-to-ascii-rhs-1 "Cc")))))
5398
5399 (defun message-generate-headers (headers)
5400   "Prepare article HEADERS.
5401 Headers already prepared in the buffer are not modified."
5402   (setq headers (append headers message-required-headers))
5403   (save-restriction
5404     (message-narrow-to-headers)
5405     (let* ((Date (message-make-date))
5406            (Message-ID (message-make-message-id))
5407            (Organization (message-make-organization))
5408            (From (message-make-from))
5409            (Path (message-make-path))
5410            (Subject nil)
5411            (Newsgroups nil)
5412            (In-Reply-To (message-make-in-reply-to))
5413            (References (message-make-references))
5414            (To nil)
5415            (Distribution (message-make-distribution))
5416            (Lines (message-make-lines))
5417            (User-Agent (message-make-user-agent))
5418            (Expires (message-make-expires))
5419            (case-fold-search t)
5420            (optionalp nil)
5421            header value elem)
5422       ;; First we remove any old generated headers.
5423       (let ((headers message-deletable-headers))
5424         (unless (buffer-modified-p)
5425           (setq headers (delq 'Message-ID (copy-sequence headers))))
5426         (while headers
5427           (goto-char (point-min))
5428           (and (re-search-forward
5429                 (concat "^" (symbol-name (car headers)) ": *") nil t)
5430                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
5431                (message-delete-line))
5432           (pop headers)))
5433       ;; Go through all the required headers and see if they are in the
5434       ;; articles already.  If they are not, or are empty, they are
5435       ;; inserted automatically - except for Subject, Newsgroups and
5436       ;; Distribution.
5437       (while headers
5438         (goto-char (point-min))
5439         (setq elem (pop headers))
5440         (if (consp elem)
5441             (if (eq (car elem) 'optional)
5442                 (setq header (cdr elem)
5443                       optionalp t)
5444               (setq header (car elem)))
5445           (setq header elem))
5446         (when (or (not (re-search-forward
5447                         (concat "^"
5448                                 (regexp-quote
5449                                  (downcase
5450                                   (if (stringp header)
5451                                       header
5452                                     (symbol-name header))))
5453                                 ":")
5454                         nil t))
5455                   (progn
5456                     ;; The header was found.  We insert a space after the
5457                     ;; colon, if there is none.
5458                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
5459                     ;; Find out whether the header is empty.
5460                     (looking-at "[ \t]*\n[^ \t]")))
5461           ;; So we find out what value we should insert.
5462           (setq value
5463                 (cond
5464                  ((and (consp elem)
5465                        (eq (car elem) 'optional))
5466                   ;; This is an optional header.  If the cdr of this
5467                   ;; is something that is nil, then we do not insert
5468                   ;; this header.
5469                   (setq header (cdr elem))
5470                   (or (and (functionp (cdr elem))
5471                            (funcall (cdr elem)))
5472                       (and (boundp (cdr elem))
5473                            (symbol-value (cdr elem)))))
5474                  ((consp elem)
5475                   ;; The element is a cons.  Either the cdr is a
5476                   ;; string to be inserted verbatim, or it is a
5477                   ;; function, and we insert the value returned from
5478                   ;; this function.
5479                   (or (and (stringp (cdr elem))
5480                            (cdr elem))
5481                       (and (functionp (cdr elem))
5482                            (funcall (cdr elem)))))
5483                  ((and (boundp header)
5484                        (symbol-value header))
5485                   ;; The element is a symbol.  We insert the value
5486                   ;; of this symbol, if any.
5487                   (symbol-value header))
5488                  ((not (message-check-element header))
5489                   ;; We couldn't generate a value for this header,
5490                   ;; so we just ask the user.
5491                   (read-from-minibuffer
5492                    (format "Empty header for %s; enter value: " header)))))
5493           ;; Finally insert the header.
5494           (when (and value
5495                      (not (equal value "")))
5496             (save-excursion
5497               (if (bolp)
5498                   (progn
5499                     ;; This header didn't exist, so we insert it.
5500                     (goto-char (point-max))
5501                     (let ((formatter
5502                            (cdr (assq header message-header-format-alist))))
5503                       (if formatter
5504                           (funcall formatter header value)
5505                         (insert (if (stringp header)
5506                                     header (symbol-name header))
5507                                 ": " value))
5508                       ;; We check whether the value was ended by a
5509                       ;; newline.  If now, we insert one.
5510                       (unless (bolp)
5511                         (insert "\n"))
5512                       (forward-line -1)))
5513                 ;; The value of this header was empty, so we clear
5514                 ;; totally and insert the new value.
5515                 (delete-region (point) (gnus-point-at-eol))
5516                 ;; If the header is optional, and the header was
5517                 ;; empty, we can't insert it anyway.
5518                 (unless optionalp
5519                   (insert value)
5520                   (when (bolp)
5521                     (delete-char -1))))
5522               ;; Add the deletable property to the headers that require it.
5523               (and (memq header message-deletable-headers)
5524                    (progn (beginning-of-line) (looking-at "[^:]+: "))
5525                    (add-text-properties
5526                     (point) (match-end 0)
5527                     '(message-deletable t face italic) (current-buffer)))))))
5528       ;; Insert new Sender if the From is strange.
5529       (let ((from (message-fetch-field "from"))
5530             (sender (message-fetch-field "sender"))
5531             (secure-sender (message-make-sender)))
5532         (when (and from
5533                    (not (message-check-element 'sender))
5534                    (not (string=
5535                          (downcase
5536                           (cadr (std11-extract-address-components from)))
5537                          (downcase secure-sender)))
5538                    (or (null sender)
5539                        (not
5540                         (string=
5541                          (downcase
5542                           (cadr (std11-extract-address-components sender)))
5543                          (downcase secure-sender)))))
5544           (goto-char (point-min))
5545           ;; Rename any old Sender headers to Original-Sender.
5546           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
5547             (beginning-of-line)
5548             (insert "Original-")
5549             (beginning-of-line))
5550           (when (or (message-news-p)
5551                     (string-match "@.+\\.." secure-sender))
5552             (insert "Sender: " secure-sender "\n"))))
5553       ;; Check for IDNA
5554       (message-idna-to-ascii-rhs))))
5555
5556 (defun message-insert-courtesy-copy ()
5557   "Insert a courtesy message in mail copies of combined messages."
5558   (let (newsgroups)
5559     (save-excursion
5560       (save-restriction
5561         (message-narrow-to-headers)
5562         (when (setq newsgroups (message-fetch-field "newsgroups"))
5563           (goto-char (point-max))
5564           (insert "Posted-To: " newsgroups "\n")))
5565       (forward-line 1)
5566       (when message-courtesy-message
5567         (cond
5568          ((string-match "%s" message-courtesy-message)
5569           (insert (format message-courtesy-message newsgroups)))
5570          (t
5571           (insert message-courtesy-message)))))))
5572
5573 ;;;
5574 ;;; Setting up a message buffer
5575 ;;;
5576
5577 (defun message-fill-address (header value)
5578   (save-restriction
5579     (narrow-to-region (point) (point))
5580     (insert (capitalize (symbol-name header))
5581             ": "
5582             (if (consp value) (car value) value)
5583             "\n")
5584     (narrow-to-region (point-min) (1- (point-max)))
5585     (let (quoted last)
5586       (goto-char (point-min))
5587       (while (not (eobp))
5588         (skip-chars-forward "^,\"" (point-max))
5589         (if (or (eq (char-after) ?,)
5590                 (eobp))
5591             (when (not quoted)
5592               (if (and (> (current-column) 78)
5593                        last)
5594                   (save-excursion
5595                     (goto-char last)
5596                     (looking-at "[ \t]*")
5597                     (replace-match "\n " t t)))
5598               (setq last (1+ (point))))
5599           (setq quoted (not quoted)))
5600         (unless (eobp)
5601           (forward-char 1))))
5602     (goto-char (point-max))
5603     (widen)
5604     (forward-line 1)))
5605
5606 (defun message-fill-references (header value)
5607   (insert (capitalize (symbol-name header))
5608           ": "
5609           (std11-fill-msg-id-list-string
5610            (if (consp value) (car value) value))
5611           "\n"))
5612
5613 (defun message-split-line ()
5614   "Split current line, moving portion beyond point vertically down.
5615 If the current line has `message-yank-prefix', insert it on the new line."
5616   (interactive "*")
5617   (condition-case nil
5618       (split-line message-yank-prefix) ;; Emacs 21.3.50+ supports arg.
5619     (error
5620      (split-line))))
5621      
5622
5623 (defun message-fill-header (header value)
5624   (let ((begin (point))
5625         (fill-column 78)
5626         (fill-prefix " "))
5627     (insert (capitalize (symbol-name header))
5628             ": "
5629             (if (consp value) (car value) value)
5630             "\n")
5631     (save-restriction
5632       (narrow-to-region begin (point))
5633       (fill-region-as-paragraph begin (point))
5634       ;; Tapdance around looong Message-IDs.
5635       (forward-line -1)
5636       (when (looking-at "[ \t]*$")
5637         (message-delete-line))
5638       (goto-char begin)
5639       (re-search-forward ":" nil t)
5640       (when (looking-at "\n[ \t]+")
5641         (replace-match " " t t))
5642       (goto-char (point-max)))))
5643
5644 (defun message-shorten-1 (list cut surplus)
5645   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
5646   (setcdr (nthcdr (- cut 2) list)
5647           (nthcdr (+ (- cut 2) surplus 1) list)))
5648
5649 (defun message-shorten-references (header references)
5650   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
5651 If folding is disallowed, also check that the REFERENCES are less
5652 than 988 characters long, and if they are not, trim them until they are."
5653   (let ((maxcount 21)
5654         (count 0)
5655         (cut 2)
5656         refs)
5657     (with-temp-buffer
5658       (insert references)
5659       (goto-char (point-min))
5660       ;; Cons a list of valid references.
5661       (while (re-search-forward "<[^>]+>" nil t)
5662         (push (match-string 0) refs))
5663       (setq refs (nreverse refs)
5664             count (length refs)))
5665
5666     ;; If the list has more than MAXCOUNT elements, trim it by
5667     ;; removing the CUTth element and the required number of
5668     ;; elements that follow.
5669     (when (> count maxcount)
5670       (let ((surplus (- count maxcount)))
5671         (message-shorten-1 refs cut surplus)
5672         (decf count surplus)))
5673
5674     ;; If folding is disallowed, make sure the total length (including
5675     ;; the spaces between) will be less than MAXSIZE characters.
5676     ;;
5677     ;; Only disallow folding for News messages. At this point the headers
5678     ;; have not been generated, thus we use message-this-is-news directly.
5679     (when (and message-this-is-news message-cater-to-broken-inn)
5680       (let ((maxsize 988)
5681             (totalsize (+ (apply #'+ (mapcar #'length refs))
5682                           (1- count)))
5683             (surplus 0)
5684             (ptr (nthcdr (1- cut) refs)))
5685         ;; Decide how many elements to cut off...
5686         (while (> totalsize maxsize)
5687           (decf totalsize (1+ (length (car ptr))))
5688           (incf surplus)
5689           (setq ptr (cdr ptr)))
5690         ;; ...and do it.
5691         (when (> surplus 0)
5692           (message-shorten-1 refs cut surplus))))
5693
5694     ;; Finally, collect the references back into a string and insert
5695     ;; it into the buffer.
5696     (let ((refstring (mapconcat #'identity refs " ")))
5697       (if (and message-this-is-news message-cater-to-broken-inn)
5698           (insert (capitalize (symbol-name header)) ": "
5699                   refstring "\n")
5700         (message-fill-header header refstring)))))
5701
5702 (defun message-position-point ()
5703   "Move point to where the user probably wants to find it."
5704   (message-narrow-to-headers)
5705   (cond
5706    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
5707     (search-backward ":" )
5708     (widen)
5709     (forward-char 1)
5710     (if (eq (char-after) ? )
5711         (forward-char 1)
5712       (insert " ")))
5713    (t
5714     (goto-char (point-max))
5715     (widen)
5716     (forward-line 1)
5717     (unless (looking-at "$")
5718       (forward-line 2)))
5719    (sit-for 0)))
5720
5721 (defcustom message-beginning-of-line t
5722   "Whether \\<message-mode-map>\\[message-beginning-of-line]\
5723  goes to beginning of header values."
5724   :group 'message-buffers
5725   :type 'boolean)
5726
5727 (defun message-beginning-of-line (&optional n)
5728   "Move point to beginning of header value or to beginning of line.
5729 The prefix argument N is passed directly to `beginning-of-line'.
5730
5731 This command is identical to `beginning-of-line' if point is
5732 outside the message header or if the option `message-beginning-of-line'
5733 is nil.
5734
5735 If point is in the message header and on a (non-continued) header
5736 line, move point to the beginning of the header value.  If point
5737 is already there, move point to beginning of line.  Therefore,
5738 repeated calls will toggle point between beginning of field and
5739 beginning of line."
5740   (interactive "p")
5741   (let ((zrs 'zmacs-region-stays))
5742     (when (and (interactive-p) (boundp zrs))
5743       (set zrs t)))
5744   (if (and message-beginning-of-line
5745            (message-point-in-header-p))
5746       (let* ((here (point))
5747              (bol (progn (beginning-of-line n) (point)))
5748              (eol (gnus-point-at-eol))
5749              (eoh (re-search-forward ": *" eol t)))
5750         (if (or (not eoh) (equal here eoh))
5751             (goto-char bol)
5752           (goto-char eoh)))
5753     (beginning-of-line n)))
5754
5755 (defun message-buffer-name (type &optional to group)
5756   "Return a new (unique) buffer name based on TYPE and TO."
5757   (cond
5758    ;; Generate a new buffer name The Message Way.
5759    ((eq message-generate-new-buffers 'unique)
5760     (generate-new-buffer-name
5761      (concat "*" type
5762              (if to
5763                  (concat " to "
5764                          (or (car (std11-extract-address-components to))
5765                              to) "")
5766                "")
5767              (if (and group (not (string= group ""))) (concat " on " group) "")
5768              "*")))
5769    ;; Check whether `message-generate-new-buffers' is a function,
5770    ;; and if so, call it.
5771    ((functionp message-generate-new-buffers)
5772     (funcall message-generate-new-buffers type to group))
5773    ((eq message-generate-new-buffers 'unsent)
5774     (generate-new-buffer-name
5775      (concat "*unsent " type
5776              (if to
5777                  (concat " to "
5778                          (or (car (mail-extract-address-components to))
5779                              to) "")
5780                "")
5781              (if (and group (not (string= group ""))) (concat " on " group) "")
5782              "*")))
5783    ;; Use standard name.
5784    (t
5785     (format "*%s message*" type))))
5786
5787 (defmacro message-pop-to-buffer-1 (buffer)
5788   `(if pop-up-frames
5789        (let (special-display-buffer-names
5790              special-display-regexps
5791              same-window-buffer-names
5792              same-window-regexps)
5793          (pop-to-buffer ,buffer))
5794      (pop-to-buffer ,buffer)))
5795
5796 (defun message-pop-to-buffer (name)
5797   "Pop to buffer NAME, and warn if it already exists and is modified."
5798   (let ((buffer (get-buffer name))
5799         (pop-up-frames (and (or (static-if (featurep 'xemacs)
5800                                     (device-on-window-system-p)
5801                                   window-system)
5802                                 (>= emacs-major-version 20))
5803                             message-use-multi-frames)))
5804     (if (and buffer
5805              (buffer-name buffer))
5806         (progn
5807           (message-pop-to-buffer-1 buffer)
5808           (when (and (buffer-modified-p)
5809                      (not (y-or-n-p
5810                            "Message already being composed; erase? ")))
5811             (error "Message being composed")))
5812       (message-pop-to-buffer-1 name))
5813     (erase-buffer)
5814     (message-mode)
5815     (when pop-up-frames
5816       (set (make-local-variable 'message-original-frame) (selected-frame)))))
5817
5818 (defun message-do-send-housekeeping ()
5819   "Kill old message buffers."
5820   ;; We might have sent this buffer already.  Delete it from the
5821   ;; list of buffers.
5822   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
5823   (while (and message-max-buffers
5824               message-buffer-list
5825               (>= (length message-buffer-list) message-max-buffers))
5826     ;; Kill the oldest buffer -- unless it has been changed.
5827     (let ((buffer (pop message-buffer-list)))
5828       (when (and (buffer-name buffer)
5829                  (not (buffer-modified-p buffer)))
5830         (kill-buffer buffer))))
5831   ;; Rename the buffer.
5832   (if message-send-rename-function
5833       (funcall message-send-rename-function)
5834     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
5835     (when (string-match
5836            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
5837            (buffer-name))
5838       (let ((name (match-string 2 (buffer-name)))
5839             to group)
5840         (if (not (or (null name)
5841                      (string-equal name "mail")
5842                      (string-equal name "posting")))
5843             (setq name (concat "*sent " name "*"))
5844           (message-narrow-to-headers)
5845           (setq to (message-fetch-field "to"))
5846           (setq group (message-fetch-field "newsgroups"))
5847           (widen)
5848           (setq name
5849                 (cond
5850                  (to (concat "*sent mail to "
5851                              (or (car (mail-extract-address-components to))
5852                                  to) "*"))
5853                  ((and group (not (string= group "")))
5854                   (concat "*sent posting on " group "*"))
5855                  (t "*sent mail*"))))
5856         (unless (string-equal name (buffer-name))
5857           (rename-buffer name t)))))
5858   ;; Push the current buffer onto the list.
5859   (when message-max-buffers
5860     (setq message-buffer-list
5861           (nconc message-buffer-list (list (current-buffer))))))
5862
5863 (defun message-mail-user-agent ()
5864   (let ((mua (cond
5865               ((not message-mail-user-agent) nil)
5866               ((eq message-mail-user-agent t) mail-user-agent)
5867               (t message-mail-user-agent))))
5868     (if (memq mua '(message-user-agent gnus-user-agent))
5869         nil
5870       mua)))
5871
5872 (defun message-setup (headers &optional replybuffer actions switch-function)
5873   (let ((mua (message-mail-user-agent))
5874         subject to field yank-action)
5875     (if (not (and message-this-is-mail mua))
5876         (message-setup-1 headers replybuffer actions)
5877       (if replybuffer
5878           (setq yank-action (list 'insert-buffer replybuffer)))
5879       (setq headers (copy-sequence headers))
5880       (setq field (assq 'Subject headers))
5881       (when field
5882         (setq subject (cdr field))
5883         (setq headers (delq field headers)))
5884       (setq field (assq 'To headers))
5885       (when field
5886         (setq to (cdr field))
5887         (setq headers (delq field headers)))
5888       (let ((mail-user-agent mua))
5889         (compose-mail to subject
5890                       (mapcar (lambda (item)
5891                                 (cons
5892                                  (format "%s" (car item))
5893                                  (cdr item)))
5894                               headers)
5895                       nil switch-function yank-action actions)))))
5896
5897 (defun message-headers-to-generate (headers included-headers excluded-headers)
5898   "Return a list that includes all headers from HEADERS.
5899 If INCLUDED-HEADERS is a list, just include those headers.  If if is
5900 t, include all headers.  In any case, headers from EXCLUDED-HEADERS
5901 are not included."
5902   (let ((result nil)
5903         header-name)
5904     (dolist (header headers)
5905       (setq header-name (cond
5906                          ((and (consp header)
5907                                (eq (car header) 'optional))
5908                           ;; On the form (optional . Header)
5909                           (cdr header))
5910                          ((consp header)
5911                           ;; On the form (Header . function)
5912                           (car header))
5913                          (t
5914                           ;; Just a Header.
5915                           header)))
5916       (when (and (not (memq header-name excluded-headers))
5917                  (or (eq included-headers t)
5918                      (memq header-name included-headers)))
5919         (push header result)))
5920     (nreverse result)))
5921
5922 (defun message-setup-1 (headers &optional replybuffer actions)
5923   (dolist (action actions)
5924     (condition-case nil
5925         (add-to-list 'message-send-actions
5926                      `(apply ',(car action) ',(cdr action)))))
5927   (setq message-reply-buffer
5928         (or (message-get-parameter 'reply-buffer)
5929             replybuffer))
5930   (goto-char (point-min))
5931   ;; Insert all the headers.
5932   (mail-header-format
5933    (let ((h headers)
5934          (alist message-header-format-alist))
5935      (while h
5936        (unless (assq (caar h) message-header-format-alist)
5937          (push (list (caar h)) alist))
5938        (pop h))
5939      alist)
5940    headers)
5941   (delete-region (point) (progn (forward-line -1) (point)))
5942   (when message-default-headers
5943     (insert message-default-headers)
5944     (or (bolp) (insert ?\n)))
5945   (put-text-property
5946    (point)
5947    (progn
5948      (insert mail-header-separator "\n")
5949      (1- (point)))
5950    'read-only nil)
5951   (forward-line -1)
5952   (when (message-news-p)
5953     (when message-default-news-headers
5954       (insert message-default-news-headers)
5955       (or (bolp) (insert ?\n)))
5956     (when message-generate-headers-first
5957       (message-generate-headers
5958        (message-headers-to-generate
5959         (append message-required-news-headers
5960                 message-required-headers)
5961         message-generate-headers-first
5962         '(Lines Subject)))))
5963   (when (message-mail-p)
5964     (when message-default-mail-headers
5965       (insert message-default-mail-headers)
5966       (or (bolp) (insert ?\n)))
5967     (save-restriction
5968       (message-narrow-to-headers)
5969       (if (and replybuffer
5970                message-alternative-emails)
5971           (message-use-alternative-email-as-from)))
5972     (when message-generate-headers-first
5973       (message-generate-headers
5974        (message-headers-to-generate
5975         (append message-required-mail-headers
5976                 message-required-headers)
5977         message-generate-headers-first
5978         '(Lines Subject)))))
5979   (run-hooks 'message-signature-setup-hook)
5980   (message-insert-signature)
5981   (save-restriction
5982     (message-narrow-to-headers)
5983     (run-hooks 'message-header-setup-hook))
5984   (set-buffer-modified-p nil)
5985   (setq buffer-undo-list nil)
5986   (run-hooks 'message-setup-hook)
5987   (message-position-point)
5988   (undo-boundary))
5989
5990 (defun message-set-auto-save-file-name ()
5991   "Associate the message buffer with a file in the drafts directory."
5992   (when message-auto-save-directory
5993     (unless (file-directory-p
5994              (directory-file-name message-auto-save-directory))
5995       (make-directory message-auto-save-directory t))
5996     (if (gnus-alive-p)
5997         (setq message-draft-article
5998               (nndraft-request-associate-buffer "drafts"))
5999       (setq buffer-file-name (expand-file-name
6000                               (if (memq system-type
6001                                         '(ms-dos ms-windows windows-nt
6002                                                  cygwin cygwin32 win32 w32
6003                                                  mswindows))
6004                                   "message"
6005                                 "*message*")
6006                               message-auto-save-directory))
6007       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
6008     (clear-visited-file-modtime)
6009     (static-if (boundp 'MULE)
6010         (set-file-coding-system message-draft-coding-system)
6011       (setq buffer-file-coding-system message-draft-coding-system))))
6012
6013 (defun message-disassociate-draft ()
6014   "Disassociate the message buffer from the drafts directory."
6015   (when message-draft-article
6016     (nndraft-request-expire-articles
6017      (list message-draft-article) "drafts" nil t)))
6018
6019 (defun message-insert-headers ()
6020   "Generate the headers for the article."
6021   (interactive)
6022   (save-excursion
6023     (save-restriction
6024       (message-narrow-to-headers)
6025       (when (message-news-p)
6026         (message-generate-headers
6027          (delq 'Lines
6028                (delq 'Subject
6029                      (copy-sequence message-required-news-headers)))))
6030       (when (message-mail-p)
6031         (message-generate-headers
6032          (delq 'Lines
6033                (delq 'Subject
6034                      (copy-sequence message-required-mail-headers))))))))
6035
6036 \f
6037
6038 ;;;
6039 ;;; Commands for interfacing with message
6040 ;;;
6041
6042 ;;;###autoload
6043 (defun message-mail (&optional to subject
6044                                other-headers continue switch-function
6045                                yank-action send-actions)
6046   "Start editing a mail message to be sent.
6047 OTHER-HEADERS is an alist of header/value pairs."
6048   (interactive)
6049   (let ((message-this-is-mail t) replybuffer)
6050     (unless (message-mail-user-agent)
6051       (message-pop-to-buffer (message-buffer-name "mail" to)))
6052     ;; FIXME: message-mail should do something if YANK-ACTION is not
6053     ;; insert-buffer.
6054     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
6055          (setq replybuffer (nth 1 yank-action)))
6056     (message-setup
6057      (nconc
6058       `((To . ,(or to "")) (Subject . ,(or subject "")))
6059       (when other-headers other-headers))
6060      replybuffer send-actions)
6061     ;; FIXME: Should return nil if failure.
6062     t))
6063
6064 ;;;###autoload
6065 (defun message-news (&optional newsgroups subject)
6066   "Start editing a news article to be sent."
6067   (interactive)
6068   (let ((message-this-is-news t))
6069     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
6070     (message-setup `((Newsgroups . ,(or newsgroups ""))
6071                      (Subject . ,(or subject ""))))))
6072
6073 (defun message-get-reply-headers (wide &optional to-address address-headers)
6074   (let (follow-to mct never-mct to cc author mft recipients)
6075     ;; Find all relevant headers we need.
6076     (let ((mrt (when message-use-mail-reply-to
6077                  (message-fetch-field "mail-reply-to")))
6078           (reply-to (message-fetch-field "reply-to")))
6079       (setq to (message-fetch-field "to")
6080             cc (message-fetch-field "cc")
6081             mct (when message-use-mail-copies-to
6082                   (message-fetch-field "mail-copies-to"))
6083             author (or mrt
6084                        reply-to
6085                        (message-fetch-field "from")
6086                        "")
6087             mft (when (and (not (or to-address mrt reply-to))
6088                            message-use-mail-followup-to)
6089                   (message-fetch-field "mail-followup-to"))))
6090
6091     (save-match-data
6092       ;; Handle special values of Mail-Copies-To.
6093       (when mct
6094         (cond ((or (equal (downcase mct) "never")
6095                    (equal (downcase mct) "nobody"))
6096                (when (or (not (eq message-use-mail-copies-to 'ask))
6097                          (message-y-or-n-p
6098                           (concat "Obey Mail-Copies-To: never? ") t "\
6099 You should normally obey the Mail-Copies-To: header.
6100
6101         `Mail-Copies-To: " mct "'
6102 directs you not to send your response to the author."))
6103                  (setq never-mct t))
6104                (setq mct nil))
6105               ((or (equal (downcase mct) "always")
6106                    (equal (downcase mct) "poster"))
6107                (if (or (not (eq message-use-mail-copies-to 'ask))
6108                        (message-y-or-n-p
6109                         (concat "Obey Mail-Copies-To: always? ") t "\
6110 You should normally obey the Mail-Copies-To: header.
6111
6112         `Mail-Copies-To: " mct "'
6113 sends a copy of your response to the author."))
6114                    (setq mct author)
6115                  (setq mct nil)))
6116               ((and (eq message-use-mail-copies-to 'ask)
6117                     (not (message-y-or-n-p
6118                           (concat "Obey Mail-Copies-To: " mct " ? ") t "\
6119 You should normally obey the Mail-Copies-To: header.
6120
6121         `Mail-Copies-To: " mct "'
6122 sends a copy of your response to " (if (string-match "," mct)
6123                                        "the specified addresses"
6124                                      "that address") ".")))
6125                (setq mct nil))))
6126
6127       ;; Build (textual) list of new recipient addresses.
6128       (cond
6129        ((not wide)
6130         (setq recipients (concat ", " author)))
6131        (address-headers
6132         (dolist (header address-headers)
6133           (let ((value (message-fetch-field header)))
6134             (when value
6135               (setq recipients (concat recipients ", " value))))))
6136        ((and mft
6137              (string-match "[^ \t,]" mft)
6138              (or (not (eq message-use-mail-followup-to 'ask))
6139                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
6140 You should normally obey the Mail-Followup-To: header.  In this
6141 article, it has the value of
6142
6143 " mft "
6144
6145 which directs your response to " (if (string-match "," mft)
6146                                      "the specified addresses"
6147                                    "that address only") ".
6148
6149 Most commonly, Mail-Followup-To is used by a mailing list poster to
6150 express that responses should be sent to just the list, and not the
6151 poster as well.
6152
6153 If a message is posted to several mailing lists, Mail-Followup-To may
6154 also be used to direct the following discussion to one list only,
6155 because discussions that are spread over several lists tend to be
6156 fragmented and very difficult to follow.
6157
6158 Also, some source/announcement lists are not intended for discussion;
6159 responses here are directed to other addresses.")))
6160         (setq recipients (concat ", " mft)))
6161        (to-address
6162         (setq recipients (concat ", " to-address))
6163         ;; If the author explicitly asked for a copy, we don't deny it to them.
6164         (if mct (setq recipients (concat recipients ", " mct))))
6165        (t
6166         (setq recipients (if never-mct "" (concat ", " author)))
6167         (if to  (setq recipients (concat recipients ", " to)))
6168         (if cc  (setq recipients (concat recipients ", " cc)))
6169         (if mct (setq recipients (concat recipients ", " mct)))))
6170       (if (>= (length recipients) 2)
6171           ;; Strip the leading ", ".
6172           (setq recipients (substring recipients 2)))
6173       ;; Squeeze whitespace.
6174       (while (string-match "[ \t][ \t]+" recipients)
6175         (setq recipients (replace-match " " t t recipients)))
6176       ;; Remove addresses that match `rmail-dont-reply-to-names'.
6177       (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
6178         (setq recipients (rmail-dont-reply-to recipients)))
6179       ;; Perhaps "Mail-Copies-To: never" removed the only address?
6180       (if (string-equal recipients "")
6181           (setq recipients author))
6182       ;; Convert string to a list of (("foo@bar" . "Name <Foo@BAR>") ...).
6183       (setq recipients
6184             (mapcar
6185              (lambda (addr)
6186                (cons (downcase (mail-strip-quoted-names addr)) addr))
6187              (message-tokenize-header recipients)))
6188       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
6189       (let ((s recipients))
6190         (while s
6191           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
6192
6193       ;; Remove hierarchical lists that are contained within each other,
6194       ;; if message-hierarchical-addresses is defined.
6195       (when message-hierarchical-addresses
6196         (let ((plain-addrs (mapcar 'car recipients))
6197               subaddrs recip)
6198           (while plain-addrs
6199             (setq subaddrs (assoc (car plain-addrs)
6200                                   message-hierarchical-addresses)
6201                   plain-addrs (cdr plain-addrs))
6202             (when subaddrs
6203               (setq subaddrs (cdr subaddrs))
6204               (while subaddrs
6205                 (setq recip (assoc (car subaddrs) recipients)
6206                       subaddrs (cdr subaddrs))
6207                 (if recip
6208                     (setq recipients (delq recip recipients))))))))
6209
6210       ;; Build the header alist.  Allow the user to be asked whether
6211       ;; or not to reply to all recipients in a wide reply.
6212       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
6213       (when (and recipients
6214                  (or (not message-wide-reply-confirm-recipients)
6215                      (y-or-n-p "Reply to all recipients? ")))
6216         (setq recipients (mapconcat
6217                           (lambda (addr) (cdr addr)) recipients ", "))
6218         (if (string-match "^ +" recipients)
6219             (setq recipients (substring recipients (match-end 0))))
6220         (push (cons 'Cc recipients) follow-to)))
6221     follow-to))
6222
6223 ;;;###autoload
6224 (defun message-reply (&optional to-address wide)
6225   "Start editing a reply to the article in the current buffer."
6226   (interactive)
6227   (require 'gnus-sum)                   ; for gnus-list-identifiers
6228   (let ((cur (current-buffer))
6229         from subject date
6230         references message-id follow-to
6231         (inhibit-point-motion-hooks t)
6232         (message-this-is-mail t)
6233         gnus-warning in-reply-to)
6234     (save-restriction
6235       (message-narrow-to-head-1)
6236       ;; Allow customizations to have their say.
6237       (if (not wide)
6238           ;; This is a regular reply.
6239           (when (functionp message-reply-to-function)
6240             (save-excursion
6241               (setq follow-to (funcall message-reply-to-function))))
6242         ;; This is a followup.
6243         (when (functionp message-wide-reply-to-function)
6244           (save-excursion
6245             (setq follow-to
6246                   (funcall message-wide-reply-to-function)))))
6247       (setq message-id (message-fetch-field "message-id" t)
6248             references (message-fetch-field "references")
6249             date (message-fetch-field "date")
6250             from (message-fetch-field "from")
6251             subject (or (message-fetch-field "subject") "none"))
6252       (when gnus-list-identifiers
6253         (setq subject (message-strip-list-identifiers subject)))
6254       (setq subject (message-make-followup-subject subject))
6255       (when message-subject-trailing-was-query
6256         (setq subject (message-strip-subject-trailing-was subject)))
6257
6258       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6259                  (string-match "<[^>]+>" gnus-warning))
6260         (setq message-id (match-string 0 gnus-warning)))
6261
6262       (unless follow-to
6263         (setq follow-to (message-get-reply-headers wide to-address)))
6264
6265       ;; Get the references from "In-Reply-To" field if there were
6266       ;; no references and "In-Reply-To" field looks promising.
6267       (unless references
6268         (when (and (setq in-reply-to (message-fetch-field "in-reply-to"))
6269                    (string-match "<[^>]+>" in-reply-to))
6270           (setq references (match-string 0 in-reply-to)))))
6271
6272     (unless (message-mail-user-agent)
6273       (message-pop-to-buffer
6274        (message-buffer-name
6275         (if wide "wide reply" "reply") from
6276         (if wide to-address nil))))
6277
6278     (setq message-reply-headers
6279           (make-full-mail-header-from-decoded-header
6280            0 subject from date message-id references 0 0 ""))
6281
6282     (message-setup
6283      `((Subject . ,subject)
6284        ,@follow-to)
6285      cur)))
6286
6287 ;;;###autoload
6288 (defun message-wide-reply (&optional to-address)
6289   "Make a \"wide\" reply to the message in the current buffer."
6290   (interactive)
6291   (message-reply to-address t))
6292
6293 ;;;###autoload
6294 (defun message-followup (&optional to-newsgroups)
6295   "Follow up to the message in the current buffer.
6296 If TO-NEWSGROUPS, use that as the new Newsgroups line."
6297   (interactive)
6298   (require 'gnus-sum)                   ; for gnus-list-identifiers
6299   (let ((cur (current-buffer))
6300         from subject date reply-to mrt mct mft
6301         references message-id follow-to
6302         (inhibit-point-motion-hooks t)
6303         (message-this-is-news t)
6304         followup-to distribution newsgroups gnus-warning posted-to)
6305     (save-restriction
6306       (message-narrow-to-head)
6307       (when (functionp message-followup-to-function)
6308         (setq follow-to
6309               (funcall message-followup-to-function)))
6310       (setq from (message-fetch-field "from")
6311             date (message-fetch-field "date")
6312             subject (or (message-fetch-field "subject") "none")
6313             references (message-fetch-field "references")
6314             message-id (message-fetch-field "message-id" t)
6315             followup-to (message-fetch-field "followup-to")
6316             newsgroups (message-fetch-field "newsgroups")
6317             posted-to (message-fetch-field "posted-to")
6318             reply-to (message-fetch-field "reply-to")
6319             mrt (when message-use-mail-reply-to
6320                   (message-fetch-field "mail-reply-to"))
6321             distribution (message-fetch-field "distribution")
6322             mct (when message-use-mail-copies-to
6323                   (message-fetch-field "mail-copies-to"))
6324             mft (when message-use-mail-followup-to
6325                   (message-fetch-field "mail-followup-to")))
6326       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6327                  (string-match "<[^>]+>" gnus-warning))
6328         (setq message-id (match-string 0 gnus-warning)))
6329       ;; Remove bogus distribution.
6330       (when (and (stringp distribution)
6331                  (let ((case-fold-search t))
6332                    (string-match "world" distribution)))
6333         (setq distribution nil))
6334       (if gnus-list-identifiers
6335           (setq subject (message-strip-list-identifiers subject)))
6336       (setq subject (message-make-followup-subject subject))
6337       (when message-subject-trailing-was-query
6338         (setq subject (message-strip-subject-trailing-was subject)))
6339       (widen))
6340
6341     ;; Handle special values of Mail-Copies-To.
6342     (when mct
6343       (cond
6344        ((and (or (equal (downcase mct) "never")
6345                  (equal (downcase mct) "nobody")))
6346         (setq mct nil))
6347        ((and (or (equal (downcase mct) "always")
6348                  (equal (downcase mct) "poster")))
6349         (if (or (not (eq message-use-mail-copies-to 'ask))
6350                 (message-y-or-n-p
6351                  (concat "Obey Mail-Copies-To: always? ") t "\
6352 You should normally obey the Mail-Copies-To: header.
6353
6354         `Mail-Copies-To: " mct "'
6355 sends a copy of your response to the author."))
6356             (setq mct (or mrt reply-to from))
6357           (setq mct nil)))
6358        ((and (eq message-use-mail-copies-to 'ask)
6359              (not
6360               (message-y-or-n-p
6361                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
6362 You should normally obey the Mail-Copies-To: header.
6363
6364         `Mail-Copies-To: " mct "'
6365 sends a copy of your response to " (if (string-match "," mct)
6366                                        "the specified addresses"
6367                                      "that address") ".")))
6368         (setq mct nil))))
6369
6370     (unless follow-to
6371       (cond
6372        (to-newsgroups (setq follow-to (list (cons 'Newsgroups to-newsgroups))))
6373        ;; Handle Followup-To.
6374        (followup-to
6375         (cond
6376          ((equal (downcase followup-to) "poster")
6377           (if (or (and followup-to (eq message-use-followup-to 'use))
6378                   (message-y-or-n-p "Obey Followup-To: poster? " t "\
6379 You should normally obey the Followup-To: header.
6380
6381         `Followup-To: poster'
6382 sends your response via e-mail instead of news.
6383
6384 A typical situation where `Followup-To: poster' is used is when the author
6385 does not read the newsgroup, so he wouldn't see any replies sent to it."))
6386               (setq message-this-is-news nil
6387                     distribution nil
6388                     follow-to (list (cons 'To (or mrt reply-to from ""))))
6389             (setq follow-to (list (cons 'Newsgroups newsgroups)))))
6390          (t
6391           (if (or (equal followup-to newsgroups)
6392                   (not (and followup-to (eq message-use-followup-to 'ask)))
6393                   (message-y-or-n-p
6394                    (concat "Obey Followup-To: " followup-to "? ") t "\
6395 You should normally obey the Followup-To: header.
6396
6397         `Followup-To: " followup-to "'
6398 directs your response to " (if (string-match "," followup-to)
6399                                "the specified newsgroups"
6400                              "that newsgroup only") ".
6401
6402 If a message is posted to several newsgroups, Followup-To is often
6403 used to direct the following discussion to one newsgroup only,
6404 because discussions that are spread over several newsgroup tend to
6405 be fragmented and very difficult to follow.
6406
6407 Also, some source/announcement newsgroups are not intended for discussion;
6408 responses here are directed to other newsgroups."))
6409               (setq follow-to (list (cons 'Newsgroups followup-to)))
6410             (setq follow-to (list (cons 'Newsgroups newsgroups)))))))
6411        ;; Handle Mail-Followup-To, followup via e-mail.
6412        ((and mft
6413              (or (not (eq message-use-mail-followup-to 'ask))
6414                  (message-y-or-n-p
6415                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
6416 You should normally obey the Mail-Followup-To: header.
6417
6418         `Mail-Followup-To: " mft "'
6419 directs your response to " (if (string-match "," mft)
6420                                "the specified addresses"
6421                              "that address only") " instead of news.
6422
6423 A typical situation where Mail-Followup-To is used is when the author thinks
6424 that further discussion should take place only in "
6425                              (if (string-match "," mft)
6426                                  "the specified mailing lists"
6427                                "that mailing list") ".")))
6428         (setq message-this-is-news nil
6429               distribution nil
6430               follow-to (list (cons 'To mft))))
6431        (posted-to (setq follow-to (list (cons 'Newsgroups posted-to))))
6432        (t
6433         (setq follow-to (list (cons 'Newsgroups newsgroups))))))
6434
6435     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
6436
6437     (setq message-reply-headers
6438           (make-full-mail-header-from-decoded-header
6439            0 subject from date message-id references 0 0 ""))
6440
6441     (message-setup
6442      `((Subject . ,subject)
6443        ,@follow-to
6444        ,@(and mct (list (cons 'Cc mct)))
6445        ,@(and distribution (list (cons 'Distribution distribution))))
6446      cur)))
6447
6448 ;;;###autoload
6449 (defun message-cancel-news (&optional arg)
6450   "Cancel an article you posted.
6451 If ARG, allow editing of the cancellation message."
6452   (interactive "P")
6453   (unless (message-news-p)
6454     (error "This is not a news article; canceling is impossible"))
6455   (let (from newsgroups message-id distribution buf sender)
6456     (save-excursion
6457       ;; Get header info from original article.
6458       (save-restriction
6459         (message-narrow-to-head-1)
6460         (setq from (message-fetch-field "from")
6461               sender (message-fetch-field "sender")
6462               newsgroups (message-fetch-field "newsgroups")
6463               message-id (message-fetch-field "message-id" t)
6464               distribution (message-fetch-field "distribution")))
6465       ;; Make sure that this article was written by the user.
6466       (unless (or
6467                ;; Canlock-logic as suggested by Per Abrahamsen
6468                ;; <abraham@dina.kvl.dk>
6469                ;;
6470                ;; IF article has cancel-lock THEN
6471                ;;   IF we can verify it THEN
6472                ;;     issue cancel
6473                ;;   ELSE
6474                ;;     error: cancellock: article is not yours
6475                ;; ELSE
6476                ;;   Use old rules, comparing sender...
6477                (if (message-fetch-field "Cancel-Lock")
6478                    (if (null (canlock-verify))
6479                        t
6480                      (error "Failed to verify Cancel-lock: This article is not yours"))
6481                  nil)
6482                (message-gnksa-enable-p 'cancel-messages)
6483                (and sender
6484                     (string-equal
6485                      (downcase sender)
6486                      (downcase (message-make-sender))))
6487                (string-equal
6488                 (downcase (cadr (std11-extract-address-components from)))
6489                 (downcase (cadr (std11-extract-address-components
6490                                  (message-make-from))))))
6491         (error "This article is not yours"))
6492       (when (yes-or-no-p "Do you really want to cancel this article? ")
6493         ;; Make control message.
6494         (if arg
6495             (message-news)
6496           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
6497         (erase-buffer)
6498         (insert "Newsgroups: " newsgroups "\n"
6499                 "From: " from "\n"
6500                 "Subject: cmsg cancel " message-id "\n"
6501                 "Control: cancel " message-id "\n"
6502                 (if distribution
6503                     (concat "Distribution: " distribution "\n")
6504                   "")
6505                 mail-header-separator "\n"
6506                 message-cancel-message)
6507         (run-hooks 'message-cancel-hook)
6508         (unless arg
6509           (message "Canceling your article...")
6510           (if (let ((message-syntax-checks
6511                      'dont-check-for-anything-just-trust-me)
6512                     (message-encoding-buffer (current-buffer))
6513                     (message-edit-buffer (current-buffer)))
6514                 (message-send-news))
6515               (message "Canceling your article...done"))
6516           (kill-buffer buf))))))
6517
6518 (defun message-supersede-setup-for-mime-edit ()
6519   (set (make-local-variable 'message-setup-hook) nil)
6520   (mime-edit-again))
6521
6522 ;;;###autoload
6523 (defun message-supersede ()
6524   "Start composing a message to supersede the current message.
6525 This is done simply by taking the old article and adding a Supersedes
6526 header line with the old Message-ID."
6527   (interactive)
6528   (let ((cur (current-buffer))
6529         (sender (message-fetch-field "sender"))
6530         (from (message-fetch-field "from")))
6531     ;; Check whether the user owns the article that is to be superseded.
6532     (unless (or
6533              ;; Canlock-logic as suggested by Per Abrahamsen
6534              ;; <abraham@dina.kvl.dk>
6535              ;;
6536              ;; IF article has cancel-lock THEN
6537              ;;   IF we can verify it THEN
6538              ;;     issue cancel
6539              ;;   ELSE
6540              ;;     error: cancellock: article is not yours
6541              ;; ELSE
6542              ;;   Use old rules, comparing sender...
6543              (if (message-fetch-field "Cancel-Lock")
6544                  (if (null (canlock-verify))
6545                      t
6546                    (error "Failed to verify Cancel-lock: This article is not yours"))
6547                nil)
6548              (message-gnksa-enable-p 'cancel-messages)
6549              (and sender
6550                   (string-equal
6551                    (downcase sender)
6552                    (downcase (message-make-sender))))
6553              (string-equal
6554               (downcase (cadr (std11-extract-address-components from)))
6555               (downcase (cadr (std11-extract-address-components
6556                                (message-make-from))))))
6557       (error "This article is not yours"))
6558     ;; Get a normal message buffer.
6559     (message-pop-to-buffer (message-buffer-name "supersede"))
6560     (insert-buffer-substring cur)
6561     (message-narrow-to-head-1)
6562     ;; Remove unwanted headers.
6563     (when message-ignored-supersedes-headers
6564       (message-remove-header message-ignored-supersedes-headers t))
6565     (goto-char (point-min))
6566     (if (not (re-search-forward "^Message-ID: " nil t))
6567         (error "No Message-ID in this article")
6568       (replace-match "Supersedes: " t t))
6569     (goto-char (point-max))
6570     (insert mail-header-separator)
6571     (widen)
6572     (when message-supersede-setup-function
6573       (funcall message-supersede-setup-function))
6574     (run-hooks 'message-supersede-setup-hook)
6575     (goto-char (point-min))
6576     (search-forward (concat "\n" mail-header-separator "\n") nil t)))
6577
6578 ;;;###autoload
6579 (defun message-recover ()
6580   "Reread contents of current buffer from its last auto-save file."
6581   (interactive)
6582   (let ((file-name (make-auto-save-file-name)))
6583     (cond ((save-window-excursion
6584              (if (not (eq system-type 'vax-vms))
6585                  (with-output-to-temp-buffer "*Directory*"
6586                    (with-current-buffer standard-output
6587                      (fundamental-mode)) ; for Emacs 20.4+
6588                    (buffer-disable-undo standard-output)
6589                    (let ((default-directory "/"))
6590                      (call-process
6591                       "ls" nil standard-output nil "-l" file-name))))
6592              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
6593            (let ((buffer-read-only nil))
6594              (erase-buffer)
6595              (insert-file-contents file-name nil)))
6596           (t (error "message-recover cancelled")))))
6597
6598 ;;; Washing Subject:
6599
6600 (defun message-wash-subject (subject)
6601   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
6602 Previous forwarders, replyers, etc. may add it."
6603   (with-temp-buffer
6604     (insert subject)
6605     (goto-char (point-min))
6606     ;; strip Re/Fwd stuff off the beginning
6607     (while (re-search-forward
6608             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
6609       (replace-match ""))
6610
6611     ;; and gnus-style forwards [foo@bar.com] subject
6612     (goto-char (point-min))
6613     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
6614       (replace-match ""))
6615
6616     ;; and off the end
6617     (goto-char (point-max))
6618     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
6619       (replace-match ""))
6620
6621     ;; and finally, any whitespace that was left-over
6622     (goto-char (point-min))
6623     (while (re-search-forward "^[ \t]+" nil t)
6624       (replace-match ""))
6625     (goto-char (point-max))
6626     (while (re-search-backward "[ \t]+$" nil t)
6627       (replace-match ""))
6628
6629     (buffer-string)))
6630
6631 ;;; Forwarding messages.
6632
6633 (defvar message-forward-decoded-p nil
6634   "Non-nil means the original message is decoded.")
6635
6636 (defun message-forward-subject-author-subject (subject)
6637   "Generate a SUBJECT for a forwarded message.
6638 The form is: [Source] Subject, where if the original message was mail,
6639 Source is the sender, and if the original message was news, Source is
6640 the list of newsgroups is was posted to."
6641   (concat "["
6642           (let ((prefix (message-fetch-field "newsgroups")))
6643             (or prefix
6644                 (and (setq prefix (message-fetch-field "from"))
6645                      (nnheader-decode-from prefix))
6646                 "(nowhere)"))
6647           "] " subject))
6648
6649 (defun message-forward-subject-name-subject (subject)
6650   "Generate a SUBJECT for a forwarded message.
6651 The form is: [Source] Subject, where if the original message was mail,
6652 Source is the name of the sender, and if the original message was
6653 news, Source is the list of newsgroups is was posted to."
6654   (concat "["
6655           (let ((prefix (message-fetch-field "newsgroups")))
6656             (or prefix
6657                 (and (setq prefix (message-fetch-field "from"))
6658                      (car (std11-extract-address-components
6659                            (nnheader-decode-from prefix))))
6660                 "(nowhere)"))
6661           "] " subject))
6662
6663 (defun message-forward-subject-fwd (subject)
6664   "Generate a SUBJECT for a forwarded message.
6665 The form is: Fwd: Subject, where Subject is the original subject of
6666 the message."
6667   (concat "Fwd: " subject))
6668
6669 (defun message-make-forward-subject ()
6670   "Return a Subject header suitable for the message in the current buffer."
6671   (save-excursion
6672     (save-restriction
6673       (message-narrow-to-head-1)
6674       (let ((funcs message-make-forward-subject-function)
6675             (subject (message-fetch-field "Subject")))
6676         (setq subject
6677               (if subject
6678                   (if message-forward-decoded-p
6679                       subject
6680                     (nnheader-decode-subject subject))
6681                 ""))
6682         (if message-wash-forwarded-subjects
6683             (setq subject (message-wash-subject subject)))
6684         ;; Make sure funcs is a list.
6685         (and funcs
6686              (not (listp funcs))
6687              (setq funcs (list funcs)))
6688         ;; Apply funcs in order, passing subject generated by previous
6689         ;; func to the next one.
6690         (while funcs
6691           (when (functionp (car funcs))
6692             (setq subject (funcall (car funcs) subject)))
6693           (setq funcs (cdr funcs)))
6694         subject))))
6695
6696 ;;;###autoload
6697 (defun message-forward (&optional news)
6698   "Forward the current message via mail.
6699 Optional NEWS will use news to forward instead of mail."
6700   (interactive "P")
6701   (let ((cur (current-buffer))
6702         (subject (message-make-forward-subject)))
6703     (if news
6704         (message-news nil subject)
6705       (message-mail nil subject))
6706     (message-forward-make-body cur)))
6707
6708 ;;;###autoload
6709 (defun message-forward-make-body (forward-buffer)
6710   ;; Put point where we want it before inserting the forwarded
6711   ;; message.
6712   ;; Note that this function definition for T-gnus is totally different
6713   ;; from the original Gnus."
6714   (if message-forward-before-signature
6715       (message-goto-body)
6716     (goto-char (point-max)))
6717   ;; Make sure we're at the start of the line.
6718   (unless (bolp)
6719     (insert "\n"))
6720   ;; Narrow to the area we are to insert.
6721   (narrow-to-region (point) (point))
6722   ;; Insert the separators and the forwarded buffer.
6723   (insert message-forward-start-separator)
6724   (let ((art-beg (point)))
6725     (insert-buffer-substring forward-buffer)
6726     (goto-char (point-max))
6727     (insert message-forward-end-separator)
6728     (set-text-properties (point-min) (point-max) nil)
6729     ;; Remove all unwanted headers.
6730     (goto-char art-beg)
6731     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
6732                                   (1- (point))
6733                                 (point)))
6734     (goto-char (point-min))
6735     (message-remove-header message-included-forward-headers t nil t)
6736     (widen)
6737     (message-position-point)))
6738
6739 ;;;###autoload
6740 (defun message-forward-rmail-make-body (forward-buffer)
6741   (save-window-excursion
6742     (set-buffer forward-buffer)
6743     ;; Rmail doesn't have rmail-msg-restore-non-pruned-header in Emacs
6744     ;; 20.  FIXIT, or we drop support for rmail in Emacs 20.
6745     (if (rmail-msg-is-pruned)
6746         (rmail-msg-restore-non-pruned-header)))
6747   (message-forward-make-body forward-buffer))
6748
6749 (eval-when-compile (defvar rmail-enable-mime-composing))
6750
6751 ;; Fixme: Should have defcustom.
6752 ;;;###autoload
6753 (defun message-insinuate-rmail ()
6754   "Let RMAIL use message to forward."
6755   (interactive)
6756   (setq rmail-enable-mime-composing t)
6757   (setq rmail-insert-mime-forwarded-message-function
6758         'message-forward-rmail-make-body))
6759
6760 ;;;###autoload
6761 (defun message-resend (address)
6762   "Resend the current article to ADDRESS."
6763   (interactive
6764    (list (message-read-from-minibuffer "Resend message to: ")))
6765   (message "Resending message to %s..." address)
6766   (save-excursion
6767     (let ((cur (current-buffer))
6768           beg)
6769       ;; We first set up a normal mail buffer.
6770       (unless (message-mail-user-agent)
6771         (set-buffer (get-buffer-create " *message resend*"))
6772         (erase-buffer))
6773       (let ((message-this-is-mail t)
6774             message-setup-hook)
6775         (message-setup `((To . ,address))))
6776       ;; Insert our usual headers.
6777       (message-generate-headers '(From Date To))
6778       (message-narrow-to-headers)
6779       ;; Remove X-Draft-From header etc.
6780       (message-remove-header message-ignored-mail-headers t)
6781       ;; Rename them all to "Resent-*".
6782       (goto-char (point-min))
6783       (while (re-search-forward "^[A-Za-z]" nil t)
6784         (forward-char -1)
6785         (insert "Resent-"))
6786       (widen)
6787       (forward-line)
6788       (delete-region (point) (point-max))
6789       (setq beg (point))
6790       ;; Insert the message to be resent.
6791       (insert-buffer-substring cur)
6792       (goto-char (point-min))
6793       (search-forward "\n\n")
6794       (forward-char -1)
6795       (save-restriction
6796         (narrow-to-region beg (point))
6797         (message-remove-header message-ignored-resent-headers t)
6798         (goto-char (point-max)))
6799       (insert mail-header-separator)
6800       ;; Rename all old ("Also-")Resent headers.
6801       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
6802         (beginning-of-line)
6803         (insert "Also-"))
6804       ;; Quote any "From " lines at the beginning.
6805       (goto-char beg)
6806       (when (looking-at "From ")
6807         (replace-match "X-From-Line: "))
6808       ;; Send it.
6809       (let ((message-encoding-buffer (current-buffer))
6810             (message-edit-buffer (current-buffer))
6811             message-required-mail-headers)
6812         (message-send-mail))
6813       (kill-buffer (current-buffer)))
6814     (message "Resending message to %s...done" address)))
6815
6816 (defun message-bounce-setup-for-mime-edit ()
6817   (set (make-local-variable 'message-setup-hook) nil)
6818   (mime-edit-again))
6819
6820 ;;;###autoload
6821 (defun message-bounce ()
6822   "Re-mail the current message.
6823 This only makes sense if the current message is a bounce message that
6824 contains some mail you have written which has been bounced back to
6825 you."
6826   (interactive)
6827   (let ((cur (current-buffer))
6828         boundary)
6829     (message-pop-to-buffer (message-buffer-name "bounce"))
6830     (insert-buffer-substring cur)
6831     (undo-boundary)
6832     (message-narrow-to-head)
6833     (if (and (message-fetch-field "MIME-Version")
6834              (setq boundary (message-fetch-field "Content-Type")))
6835         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
6836             (setq boundary (concat (match-string 1 boundary) " *\n"
6837                                    "Content-Type: message/rfc822"))
6838           (setq boundary nil)))
6839     (widen)
6840     (goto-char (point-min))
6841     (search-forward "\n\n" nil t)
6842     (if (or (and boundary
6843                  (re-search-forward boundary nil t)
6844                  (forward-line 2))
6845             (and (re-search-forward message-unsent-separator nil t)
6846                  (forward-line 1))
6847             (re-search-forward "^Return-Path:.*\n" nil t))
6848         ;; We remove everything before the bounced mail.
6849         (delete-region
6850          (point-min)
6851          (if (re-search-forward "^[^ \n\t]+:" nil t)
6852              (match-beginning 0)
6853            (point)))
6854       (when (re-search-backward "^.?From .*\n" nil t)
6855         (delete-region (match-beginning 0) (match-end 0))))
6856     (save-restriction
6857       (message-narrow-to-head-1)
6858       (message-remove-header message-ignored-bounced-headers t)
6859       (goto-char (point-max))
6860       (insert mail-header-separator))
6861     (when message-bounce-setup-function
6862       (funcall message-bounce-setup-function))
6863     (run-hooks 'message-bounce-setup-hook)
6864     (message-position-point)))
6865
6866 ;;;
6867 ;;; Interactive entry points for new message buffers.
6868 ;;;
6869
6870 ;;;###autoload
6871 (defun message-mail-other-window (&optional to subject)
6872   "Like `message-mail' command, but display mail buffer in another window."
6873   (interactive)
6874   (unless (message-mail-user-agent)
6875     (let ((pop-up-windows 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 "mail" to))))
6881   (let ((message-this-is-mail t))
6882     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6883                    nil nil 'switch-to-buffer-other-window)))
6884
6885 ;;;###autoload
6886 (defun message-mail-other-frame (&optional to subject)
6887   "Like `message-mail' command, but display mail buffer in another frame."
6888   (interactive)
6889   (unless (message-mail-user-agent)
6890     (let ((pop-up-frames t)
6891           (special-display-buffer-names nil)
6892           (special-display-regexps nil)
6893           (same-window-buffer-names nil)
6894           (same-window-regexps nil))
6895       (message-pop-to-buffer (message-buffer-name "mail" to))))
6896   (let ((message-this-is-mail t))
6897     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6898                    nil nil 'switch-to-buffer-other-frame)))
6899
6900 ;;;###autoload
6901 (defun message-news-other-window (&optional newsgroups subject)
6902   "Start editing a news article to be sent."
6903   (interactive)
6904   (let ((pop-up-windows t)
6905         (special-display-buffer-names nil)
6906         (special-display-regexps nil)
6907         (same-window-buffer-names nil)
6908         (same-window-regexps nil))
6909     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6910   (let ((message-this-is-news t))
6911     (message-setup `((Newsgroups . ,(or newsgroups ""))
6912                      (Subject . ,(or subject ""))))))
6913
6914 ;;;###autoload
6915 (defun message-news-other-frame (&optional newsgroups subject)
6916   "Start editing a news article to be sent."
6917   (interactive)
6918   (let ((pop-up-frames t)
6919         (special-display-buffer-names nil)
6920         (special-display-regexps nil)
6921         (same-window-buffer-names nil)
6922         (same-window-regexps nil))
6923     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6924   (let ((message-this-is-news t))
6925     (message-setup `((Newsgroups . ,(or newsgroups ""))
6926                      (Subject . ,(or subject ""))))))
6927
6928 ;;; underline.el
6929
6930 ;; This code should be moved to underline.el (from which it is stolen).
6931
6932 ;;;###autoload
6933 (defun bold-region (start end)
6934   "Bold all nonblank characters in the region.
6935 Works by overstriking characters.
6936 Called from program, takes two arguments START and END
6937 which specify the range to operate on."
6938   (interactive "r")
6939   (save-excursion
6940     (let ((end1 (make-marker)))
6941       (move-marker end1 (max start end))
6942       (goto-char (min start end))
6943       (while (< (point) end1)
6944         (or (looking-at "[_\^@- ]")
6945             (insert (char-after) "\b"))
6946         (forward-char 1)))))
6947
6948 ;;;###autoload
6949 (defun unbold-region (start end)
6950   "Remove all boldness (overstruck characters) in the region.
6951 Called from program, takes two arguments START and END
6952 which specify the range to operate on."
6953   (interactive "r")
6954   (save-excursion
6955     (let ((end1 (make-marker)))
6956       (move-marker end1 (max start end))
6957       (goto-char (min start end))
6958       (while (re-search-forward "\b" end1 t)
6959         (if (eq (char-after) (char-after (- (point) 2)))
6960             (delete-char -2))))))
6961
6962 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
6963 (defalias 'message-make-overlay 'make-overlay)
6964 (defalias 'message-delete-overlay 'delete-overlay)
6965 (defalias 'message-overlay-put 'overlay-put)
6966 (defun message-kill-all-overlays ()
6967   (if (featurep 'xemacs)
6968       (map-extents (lambda (extent ignore) (delete-extent extent)))
6969     (mapcar #'delete-overlay (overlays-in (point-min) (point-max)))))
6970
6971 ;; Support for toolbar
6972 (eval-when-compile
6973   (defvar tool-bar-map)
6974   (defvar tool-bar-mode))
6975
6976 (defun message-tool-bar-local-item-from-menu (command icon in-map &optional from-map &rest props)
6977   ;; We need to make tool bar entries in local keymaps with
6978   ;; `tool-bar-local-item-from-menu' in Emacs > 21.3
6979   (if (fboundp 'tool-bar-local-item-from-menu)
6980       ;; This is for Emacs 21.3
6981       (tool-bar-local-item-from-menu command icon in-map from-map props)
6982     (tool-bar-add-item-from-menu command icon from-map props)))
6983
6984 (defun message-tool-bar-map ()
6985   (or message-tool-bar-map
6986       (setq message-tool-bar-map
6987             (and
6988              (condition-case nil (require 'tool-bar) (error nil))
6989              (fboundp 'tool-bar-add-item-from-menu)
6990              tool-bar-mode
6991              (let ((tool-bar-map (copy-keymap tool-bar-map))
6992                    (load-path (mm-image-load-path)))
6993                ;; Zap some items which aren't so relevant and take
6994                ;; up space.
6995                (dolist (key '(print-buffer kill-buffer save-buffer
6996                                            write-file dired open-file))
6997                  (define-key tool-bar-map (vector key) nil))
6998                (message-tool-bar-local-item-from-menu
6999                 'message-send-and-exit "mail_send" tool-bar-map message-mode-map)
7000                (message-tool-bar-local-item-from-menu
7001                 'message-kill-buffer "close" tool-bar-map message-mode-map)
7002                (message-tool-bar-local-item-from-menu
7003                 'message-dont-send "cancel" tool-bar-map message-mode-map)
7004 ;;             (message-tool-bar-local-item-from-menu
7005 ;;              'mime-edit-insert-file "attach"
7006 ;;              tool-bar-map mime-edit-mode-map)
7007                (message-tool-bar-local-item-from-menu
7008                 'ispell-message "spell" tool-bar-map message-mode-map)
7009 ;;             (message-tool-bar-local-item-from-menu
7010 ;;              'mime-edit-preview-message "preview"
7011 ;;              tool-bar-map mime-edit-mode-map)
7012                (message-tool-bar-local-item-from-menu
7013                 'message-insert-importance-high "important"
7014                 tool-bar-map message-mode-map)
7015                (message-tool-bar-local-item-from-menu
7016                 'message-insert-importance-low "unimportant"
7017                 tool-bar-map message-mode-map)
7018                (message-tool-bar-local-item-from-menu
7019                 'message-insert-disposition-notification-to "receipt"
7020                 tool-bar-map message-mode-map)
7021                tool-bar-map)))))
7022
7023 ;;; Group name completion.
7024
7025 (defcustom message-newgroups-header-regexp
7026   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
7027   "Regexp that match headers that lists groups."
7028   :group 'message
7029   :type 'regexp)
7030
7031 (defcustom message-completion-alist
7032   (list (cons message-newgroups-header-regexp 'message-expand-group)
7033         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name)
7034         '("^\\(Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):"
7035           . message-expand-name)
7036         '("^\\(Disposition-Notification-To\\|Return-Receipt-To\\):"
7037           . message-expand-name))
7038   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
7039   :group 'message
7040   :type '(alist :key-type regexp :value-type function))
7041
7042 (defcustom message-expand-name-function
7043   (if (fboundp 'bbdb-complete-name)
7044       'bbdb-complete-name
7045     (if (fboundp 'lsdb-complete-name)
7046         'lsdb-complete-name
7047       'expand-abbrev))
7048   "*A function called to expand addresses in field body."
7049   :group 'message
7050   :type 'function)
7051
7052 (defcustom message-tab-body-function nil
7053   "*Function to execute when `message-tab' (TAB) is executed in the body.
7054 If nil, the function bound in `text-mode-map' or `global-map' is executed."
7055   :group 'message
7056   :type 'function)
7057
7058 (defun message-tab ()
7059   "Complete names according to `message-completion-alist'.
7060 Execute function specified by `message-tab-body-function' when not in
7061 those headers."
7062   (interactive)
7063   (let ((alist message-completion-alist))
7064     (while (and alist
7065                 (let ((mail-abbrev-mode-regexp (caar alist)))
7066                   (not (mail-abbrev-in-expansion-header-p))))
7067       (setq alist (cdr alist)))
7068     (funcall (or (cdar alist) message-tab-body-function
7069                  (lookup-key text-mode-map "\t")
7070                  (lookup-key global-map "\t")
7071                  'indent-relative))))
7072
7073 (defun message-expand-group ()
7074   "Expand the group name under point."
7075   (let* ((b (save-excursion
7076               (save-restriction
7077                 (narrow-to-region
7078                  (save-excursion
7079                    (beginning-of-line)
7080                    (skip-chars-forward "^:")
7081                    (1+ (point)))
7082                  (point))
7083                 (skip-chars-backward "^, \t\n") (point))))
7084          (completion-ignore-case t)
7085          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
7086                                             (point))))
7087          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
7088          (completions (all-completions string hashtb))
7089          comp)
7090     (delete-region b (point))
7091     (cond
7092      ((= (length completions) 1)
7093       (if (string= (car completions) string)
7094           (progn
7095             (insert string)
7096             (message "Only matching group"))
7097         (insert (car completions))))
7098      ((and (setq comp (try-completion string hashtb))
7099            (not (string= comp string)))
7100       (insert comp))
7101      (t
7102       (insert string)
7103       (if (not comp)
7104           (message "No matching groups")
7105         (save-selected-window
7106           (pop-to-buffer "*Completions*")
7107           (buffer-disable-undo)
7108           (let ((buffer-read-only nil))
7109             (erase-buffer)
7110             (let ((standard-output (current-buffer)))
7111               (display-completion-list (sort completions 'string<)))
7112             (goto-char (point-min))
7113             (delete-region (point) (progn (forward-line 3) (point))))))))))
7114
7115 (defun message-expand-name ()
7116   (funcall message-expand-name-function))
7117
7118 ;;; Help stuff.
7119
7120 (defun message-talkative-question (ask question show &rest text)
7121   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
7122 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
7123 The following arguments may contain lists of values."
7124   (if (and show
7125            (setq text (message-flatten-list text)))
7126       (save-window-excursion
7127         (save-excursion
7128           (with-output-to-temp-buffer " *MESSAGE information message*"
7129             (set-buffer " *MESSAGE information message*")
7130             (fundamental-mode)          ; for Emacs 20.4+
7131             (mapcar 'princ text)
7132             (goto-char (point-min))))
7133         (funcall ask question))
7134     (funcall ask question)))
7135
7136 (defun message-flatten-list (list)
7137   "Return a new, flat list that contains all elements of LIST.
7138
7139 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
7140 => (1 2 3 4 5 6 7)"
7141   (cond ((consp list)
7142          (apply 'append (mapcar 'message-flatten-list list)))
7143         (list
7144          (list list))))
7145
7146 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
7147   "Create and return a buffer with name based on NAME using `generate-new-buffer.'
7148 Then clone the local variables and values from the old buffer to the
7149 new one, cloning only the locals having a substring matching the
7150 regexp varstr."
7151   (let ((oldbuf (current-buffer)))
7152     (save-excursion
7153       (set-buffer (generate-new-buffer name))
7154       (message-clone-locals oldbuf varstr)
7155       (current-buffer))))
7156
7157 (defun message-clone-locals (buffer &optional varstr)
7158   "Clone the local variables from BUFFER to the current buffer."
7159   (let ((locals (save-excursion
7160                   (set-buffer buffer)
7161                   (buffer-local-variables)))
7162         (regexp
7163          "^\\(gnus\\|nn\\|message\\|user-\\(mail-address\\|full-name\\)\\)"))
7164     (mapcar
7165      (lambda (local)
7166        (when (and (consp local)
7167                   (car local)
7168                   (string-match regexp (symbol-name (car local)))
7169                   (or (null varstr)
7170                       (string-match varstr (symbol-name (car local)))))
7171          (ignore-errors
7172            (set (make-local-variable (car local))
7173                 (cdr local)))))
7174      locals)))
7175
7176
7177 ;;; @ for MIME Edit mode
7178 ;;;
7179
7180 (defun message-maybe-encode ()
7181   (when message-mime-mode
7182     ;; Inherit the buffer local variable `mime-edit-pgp-processing'.
7183     (let ((pgp-processing (with-current-buffer message-edit-buffer
7184                             mime-edit-pgp-processing)))
7185       (setq mime-edit-pgp-processing pgp-processing))
7186     (run-hooks 'mime-edit-translate-hook)
7187     (if (catch 'mime-edit-error
7188           (save-excursion
7189             (mime-edit-pgp-enclose-buffer)
7190             (mime-edit-translate-body)))
7191         (error "Translation error!"))
7192     (run-hooks 'mime-edit-exit-hook)))
7193
7194 (defun message-mime-insert-article (&optional full-headers)
7195   (interactive "P")
7196   (let ((message-cite-function 'mime-edit-inserted-message-filter)
7197         (message-reply-buffer
7198          (message-get-parameter-with-eval 'original-buffer))
7199         (start (point)))
7200     (message-yank-original nil)
7201     (save-excursion
7202       (narrow-to-region (goto-char start)
7203                         (if (search-forward "\n\n" nil t)
7204                             (1- (point))
7205                           (point-max)))
7206       (goto-char (point-min))
7207       (let ((message-included-forward-headers
7208              (if full-headers "" message-included-forward-headers)))
7209         (message-remove-header message-included-forward-headers t nil t))
7210       (widen))))
7211
7212 (set-alist 'mime-edit-message-inserter-alist
7213            'message-mode (function message-mime-insert-article))
7214
7215 ;;;
7216 ;;; MIME functions
7217 ;;;
7218
7219 (defvar message-inhibit-body-encoding t)
7220
7221 (defun message-encode-message-body ()
7222   (unless message-inhibit-body-encoding
7223     (let ((mail-parse-charset (or mail-parse-charset
7224                                   message-default-charset))
7225           (case-fold-search t)
7226           lines content-type-p)
7227       (message-goto-body)
7228       (save-restriction
7229         (narrow-to-region (point) (point-max))
7230         (let ((new (mml-generate-mime)))
7231           (when new
7232             (delete-region (point-min) (point-max))
7233             (insert new)
7234             (goto-char (point-min))
7235             (if (eq (aref new 0) ?\n)
7236                 (delete-char 1)
7237               (search-forward "\n\n")
7238               (setq lines (buffer-substring (point-min) (1- (point))))
7239               (delete-region (point-min) (point))))))
7240       (save-restriction
7241         (message-narrow-to-headers-or-head)
7242         (message-remove-header "Mime-Version")
7243         (goto-char (point-max))
7244         (insert "MIME-Version: 1.0\n")
7245         (when lines
7246           (insert lines))
7247         (setq content-type-p
7248               (or mml-boundary
7249                   (re-search-backward "^Content-Type:" nil t))))
7250       (save-restriction
7251         (message-narrow-to-headers-or-head)
7252         (message-remove-first-header "Content-Type")
7253         (message-remove-first-header "Content-Transfer-Encoding"))
7254       ;; We always make sure that the message has a Content-Type
7255       ;; header.  This is because some broken MTAs and MUAs get
7256       ;; awfully confused when confronted with a message with a
7257       ;; MIME-Version header and without a Content-Type header.  For
7258       ;; instance, Solaris' /usr/bin/mail.
7259       (unless content-type-p
7260         (goto-char (point-min))
7261         ;; For unknown reason, MIME-Version doesn't exist.
7262         (when (re-search-forward "^MIME-Version:" nil t)
7263           (forward-line 1)
7264           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
7265
7266 (defun message-read-from-minibuffer (prompt &optional initial-contents)
7267   "Read from the minibuffer while providing abbrev expansion."
7268   (if (fboundp 'mail-abbrevs-setup)
7269       (let ((mail-abbrev-mode-regexp "")
7270             (minibuffer-setup-hook 'mail-abbrevs-setup)
7271             (minibuffer-local-map message-minibuffer-local-map))
7272         (read-from-minibuffer prompt initial-contents))
7273     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
7274           (minibuffer-local-map message-minibuffer-local-map))
7275       (read-string prompt initial-contents))))
7276
7277 (defun message-use-alternative-email-as-from ()
7278   (require 'mail-utils)
7279   (let* ((fields '("To" "Cc"))
7280          (emails
7281           (split-string
7282            (mail-strip-quoted-names
7283             (mapconcat 'message-fetch-reply-field fields ","))
7284            "[ \f\t\n\r\v,]+"))
7285          email)
7286     (while emails
7287       (if (string-match message-alternative-emails (car emails))
7288           (setq email (car emails)
7289                 emails nil))
7290       (pop emails))
7291     (unless (or (not email) (equal email user-mail-address))
7292       (goto-char (point-max))
7293       (insert "From: " email "\n"))))
7294
7295 (defun message-options-get (symbol)
7296   (cdr (assq symbol message-options)))
7297
7298 (defun message-options-set (symbol value)
7299   (let ((the-cons (assq symbol message-options)))
7300     (if the-cons
7301         (if value
7302             (setcdr the-cons value)
7303           (setq message-options (delq the-cons message-options)))
7304       (and value
7305            (push (cons symbol value) message-options))))
7306   value)
7307
7308 (defun message-options-set-recipient ()
7309   (save-restriction
7310     (message-narrow-to-headers-or-head)
7311     (message-options-set 'message-sender
7312                          (mail-strip-quoted-names
7313                           (message-fetch-field "from")))
7314     (message-options-set 'message-recipients
7315                          (mail-strip-quoted-names
7316                           (let ((to (message-fetch-field "to"))
7317                                 (cc (message-fetch-field "cc"))
7318                                 (bcc (message-fetch-field "bcc")))
7319                             (concat
7320                              (or to "")
7321                              (if (and to cc) ", ")
7322                              (or cc "")
7323                              (if (and (or to cc) bcc) ", ")
7324                              (or bcc "")))))))
7325
7326 (defun message-hide-headers ()
7327   "Hide headers based on the `message-hidden-headers' variable."
7328   (let ((regexps (if (stringp message-hidden-headers)
7329                      (list message-hidden-headers)
7330                    message-hidden-headers))
7331         (inhibit-point-motion-hooks t)
7332         (after-change-functions nil))
7333     (when regexps
7334       (save-excursion
7335         (save-restriction
7336           (message-narrow-to-headers)
7337           (goto-char (point-min))
7338           (while (not (eobp))
7339             (if (not (message-hide-header-p regexps))
7340                 (message-next-header)
7341               (let ((begin (point)))
7342                 (message-next-header)
7343                 (add-text-properties
7344                  begin (point)
7345                  '(invisible t message-hidden t))))))))))
7346
7347 (defun message-hide-header-p (regexps)
7348   (let ((result nil)
7349         (reverse nil))
7350     (when (eq (car regexps) 'not)
7351       (setq reverse t)
7352       (pop regexps))
7353     (dolist (regexp regexps)
7354       (setq result (or result (looking-at regexp))))
7355     (if reverse
7356         (not result)
7357       result)))
7358
7359 (when (featurep 'xemacs)
7360   (require 'messagexmas)
7361   (message-xmas-redefine))
7362
7363 (provide 'message)
7364
7365 (run-hooks 'message-load-hook)
7366
7367 ;; Local Variables:
7368 ;; coding: iso-8859-1
7369 ;; End:
7370
7371 ;;; message.el ends here