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