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