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