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