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