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