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