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