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