Synch with Oort Gnus.
[elisp/gnus.git-] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
7 ;;      Shuhei KOBAYASHI <shuhei-k@jaist.ac.jp>
8 ;;      Keiichi Suzuki   <kei-suzu@mail.wbs.ne.jp>
9 ;;      Tatsuya Ichikawa <t-ichi@po.shiojiri.ne.jp>
10 ;;      Katsumi Yamaoka  <yamaoka@jpl.org>
11 ;;      Kiyokazu SUTO    <suto@merry.xmath.ous.ac.jp>
12 ;; Keywords: mail, news, MIME
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software; you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation; either version 2, or (at your option)
19 ;; any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
28 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
29 ;; Boston, MA 02111-1307, USA.
30
31 ;;; Commentary:
32
33 ;; This mode provides mail-sending facilities from within Emacs.  It
34 ;; consists mainly of large chunks of code from the sendmail.el,
35 ;; gnus-msg.el and rnewspost.el files.
36
37 ;;; Code:
38
39 (eval-when-compile
40   (require 'cl)
41   (require 'smtp)
42   (defvar gnus-list-identifiers)) ; gnus-sum is required where necessary
43 (eval-and-compile
44   (if (boundp 'MULE)
45       (progn
46         (require 'base64)
47         (require 'canlock-om))
48     (require 'canlock)))
49 (require 'mailheader)
50 (require 'nnheader)
51 ;; This is apparently necessary even though things are autoloaded.
52 ;; Because we dynamically bind mail-abbrev-mode-regexp, we'd better
53 ;; require mailabbrev here.
54 (if (featurep 'xemacs)
55     (require 'mail-abbrevs)
56   (require 'mailabbrev))
57 (require 'mime-edit)
58 (eval-when-compile (require 'static))
59
60 ;; Avoid byte-compile warnings.
61 (eval-when-compile
62   (require 'mail-parse)
63   (require 'mml))
64
65 (require 'rfc822)
66 (eval-and-compile
67   (autoload 'sha1 "sha1-el")
68   (autoload 'customize-save-variable "cus-edit"));; for Mule 2.
69
70 (defgroup message '((user-mail-address custom-variable)
71                     (user-full-name custom-variable))
72   "Mail and news message composing."
73   :link '(custom-manual "(message)Top")
74   :group 'mail
75   :group 'news)
76
77 (put 'user-mail-address 'custom-type 'string)
78 (put 'user-full-name 'custom-type 'string)
79
80 (defgroup message-various nil
81   "Various Message Variables"
82   :link '(custom-manual "(message)Various Message Variables")
83   :group 'message)
84
85 (defgroup message-buffers nil
86   "Message Buffers"
87   :link '(custom-manual "(message)Message Buffers")
88   :group 'message)
89
90 (defgroup message-sending nil
91   "Message Sending"
92   :link '(custom-manual "(message)Sending Variables")
93   :group 'message)
94
95 (defgroup message-interface nil
96   "Message Interface"
97   :link '(custom-manual "(message)Interface")
98   :group 'message)
99
100 (defgroup message-forwarding nil
101   "Message Forwarding"
102   :link '(custom-manual "(message)Forwarding")
103   :group 'message-interface)
104
105 (defgroup message-insertion nil
106   "Message Insertion"
107   :link '(custom-manual "(message)Insertion")
108   :group 'message)
109
110 (defgroup message-headers nil
111   "Message Headers"
112   :link '(custom-manual "(message)Message Headers")
113   :group 'message)
114
115 (defgroup message-news nil
116   "Composing News Messages"
117   :group 'message)
118
119 (defgroup message-mail nil
120   "Composing Mail Messages"
121   :group 'message)
122
123 (defgroup message-faces nil
124   "Faces used for message composing."
125   :group 'message
126   :group 'faces)
127
128 (defgroup message-frames nil
129   "Message frames"
130   :group 'message)
131
132 (defcustom message-directory "~/Mail/"
133   "*Directory from which all other mail file variables are derived."
134   :group 'message-various
135   :type 'directory)
136
137 (defcustom message-max-buffers 10
138   "*How many buffers to keep before starting to kill them off."
139   :group 'message-buffers
140   :type 'integer)
141
142 (defcustom message-send-rename-function nil
143   "Function called to rename the buffer after sending it."
144   :group 'message-buffers
145   :type '(choice function (const nil)))
146
147 (defcustom message-fcc-handler-function 'message-output
148   "*A function called to save outgoing articles.
149 This function will be called with the name of the file to store the
150 article in.  The default function is `message-output' which saves in Unix
151 mailbox format."
152   :type '(radio (function-item message-output)
153                 (function :tag "Other"))
154   :group 'message-sending)
155
156 (defcustom message-encode-function 'message-maybe-encode
157   "*A function called to encode messages."
158   :group 'message-sending
159   :type 'function)
160
161 (defcustom message-8bit-encoding-list '(8bit binary)
162   "*8bit encoding type in Content-Transfer-Encoding field."
163   :group 'message-sending
164   :type '(repeat (symbol :tag "Type")))
165
166 (defcustom message-fcc-externalize-attachments nil
167   "If non-nil, attachments are included as external parts in Fcc copies."
168   :type 'boolean
169   :group 'message-sending)
170
171 (defcustom message-courtesy-message
172   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
173   "*This is inserted at the start of a mailed copy of a posted message.
174 If the string contains the format spec \"%s\", the Newsgroups
175 the article has been posted to will be inserted there.
176 If this variable is nil, no such courtesy message will be added."
177   :group 'message-sending
178   :type 'string)
179
180 (defcustom message-ignored-bounced-headers "^\\(Received\\|Return-Path\\):"
181   "*Regexp that matches headers to be removed in resent bounced mail."
182   :group 'message-interface
183   :type 'regexp)
184
185 (defcustom message-bounce-setup-function 'message-bounce-setup-for-mime-edit
186   "Function to setup a re-sending bounced message."
187   :group 'message-sending
188   :type 'function)
189
190 ;;;###autoload
191 (defcustom message-from-style 'default
192   "*Specifies how \"From\" headers look.
193
194 If nil, they contain just the return address like:
195         king@grassland.com
196 If `parens', they look like:
197         king@grassland.com (Elvis Parsley)
198 If `angles', they look like:
199         Elvis Parsley <king@grassland.com>
200
201 Otherwise, most addresses look like `angles', but they look like
202 `parens' if `angles' would need quoting and `parens' would not."
203   :type '(choice (const :tag "simple" nil)
204                  (const parens)
205                  (const angles)
206                  (const default))
207   :group 'message-headers)
208
209 (defcustom message-insert-canlock t
210   "Whether to insert a Cancel-Lock header in news postings."
211   :version "21.3"
212   :group 'message-headers
213   :type 'boolean)
214
215 (defcustom message-syntax-checks 
216   (if message-insert-canlock '((sender . disabled)) nil)
217   ;; Guess this one shouldn't be easy to customize...
218   "*Controls what syntax checks should not be performed on outgoing posts.
219 To disable checking of long signatures, for instance, add
220  `(signature . disabled)' to this list.
221
222 Don't touch this variable unless you really know what you're doing.
223
224 Checks include `subject-cmsg', `multiple-headers', `sendsys',
225 `message-id', `from', `long-lines', `control-chars', `size',
226 `new-text', `quoting-style', `redirected-followup', `signature',
227 `approved', `sender', `empty', `empty-headers', `message-id', `from',
228 `subject', `shorten-followup-to', `existing-newsgroups',
229 `buffer-file-name', `unchanged', `newsgroups', `reply-to'."
230   :group 'message-news
231   :type '(repeat sexp))                 ; Fixme: improve this
232
233 (defcustom message-required-news-headers
234   '(From Newsgroups Subject Date Message-ID
235          (optional . Organization) Lines
236          (optional . User-Agent))
237   "*Headers to be generated or prompted for when posting an article.
238 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
239 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
240 User-Agent are optional.  If don't you want message to insert some
241 header, remove it from this list."
242   :group 'message-news
243   :group 'message-headers
244   :type '(repeat sexp))
245
246 (defcustom message-required-mail-headers
247   '(From Subject Date (optional . In-Reply-To) Message-ID Lines
248          (optional . User-Agent))
249   "*Headers to be generated or prompted for when mailing a message.
250 It is recommended that From, Date, To, Subject and Message-ID be
251 included.  Organization, Lines and User-Agent are optional."
252   :group 'message-mail
253   :group 'message-headers
254   :type '(repeat sexp))
255
256 (defcustom message-deletable-headers '(Message-ID Date Lines)
257   "Headers to be deleted if they already exist and were generated by message previously."
258   :group 'message-headers
259   :type 'sexp)
260
261 (defcustom message-ignored-news-headers
262   "^NNTP-Posting-Host:\\|^Xref:\\|^[BGF]cc:\\|^Resent-Fcc:\\|^X-Draft-From:\\|^X-Gnus-Agent-Meta-Information:"
263   "*Regexp of headers to be removed unconditionally before posting."
264   :group 'message-news
265   :group 'message-headers
266   :type 'regexp)
267
268 (defcustom message-ignored-mail-headers
269   "^[GF]cc:\\|^Resent-Fcc:\\|^Xref:\\|^X-Draft-From:\\|^X-Gnus-Agent-Meta-Information:"
270   "*Regexp of headers to be removed unconditionally before mailing."
271   :group 'message-mail
272   :group 'message-headers
273   :type 'regexp)
274
275 (defcustom message-ignored-supersedes-headers "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|^X-Trace:\\|^X-Complaints-To:\\|Return-Path:\\|^Supersedes:\\|^NNTP-Posting-Date:\\|^X-Trace:\\|^X-Complaints-To:\\|^Cancel-Lock:\\|^Cancel-Key:"
276   "*Header lines matching this regexp will be deleted before posting.
277 It's best to delete old Path and Date headers before posting to avoid
278 any confusion."
279   :group 'message-interface
280   :type 'regexp)
281
282 (defcustom message-supersede-setup-function
283   'message-supersede-setup-for-mime-edit
284   "Function to setup a supersede message."
285   :group 'message-sending
286   :type 'function)
287
288 (defcustom message-subject-re-regexp
289   "^[ \t]*\\([Rr][Ee]\\(\\[[0-9]*\\]\\)*:[ \t]*\\)*[ \t]*"
290   "*Regexp matching \"Re: \" in the subject line."
291   :group 'message-various
292   :type 'regexp)
293
294 ;;; Some sender agents encode the whole subject including leading "Re: ".
295 ;;; And if followup agent does not decode it for some reason (e.g. unknown
296 ;;; charset) and just add a new "Re: " in front of the encoded-word, the
297 ;;; result will contain multiple "Re: "'s.
298 (defcustom message-subject-encoded-re-regexp
299   (concat
300    "^[ \t]*"
301    (regexp-quote "=?")
302    "[-!#$%&'*+0-9A-Z^_`a-z{|}~]+" ; charset
303    (regexp-quote "?")
304    "\\("
305    "[Bb]" (regexp-quote "?") ; B encoding
306    "\\(\\(CQk\\|CSA\\|IAk\\|ICA\\)[Jg]\\)*" ; \([ \t][ \t][ \t]\)*
307    "\\("
308    "[Uc][km]U6" ; [Rr][Ee]:
309    "\\|"
310    "\\(C[VX]\\|I[FH]\\)J[Fl]O[g-v]" ; [ \t][Rr][Ee]:
311    "\\|"
312    "\\(CQl\\|CSB\\|IAl\\|ICB\\)[Sy][RZ]T[o-r]" ; [ \t][ \t][Rr][Ee]:
313    "\\)"
314    "\\|"
315    "[Qb]" (regexp-quote "?") ; Q encoding
316    "\\(_\\|=09\\|=20\\)*"
317    "\\([Rr]\\|=[57]2\\)\\([Ee]\\|=[46]5\\)\\(:\\|=3[Aa]\\)"
318    "\\)"
319    )
320   "*Regexp matching \"Re: \" in the subject line.
321 Unlike `message-subject-re-regexp', this regexp matches \"Re: \" within
322 an encoded-word."
323   :group 'message-various
324   :type 'regexp)
325
326 (defcustom message-use-subject-re t
327   "*If t, remove any (buggy) \"Re: \"'s from the subject of the precursor
328 and add a new \"Re: \".  If it is nil, use the subject \"as-is\".  If it
329 is the symbol `guess', try to detect \"Re: \" within an encoded-word."
330   :group 'message-various
331   :type '(choice (const :tag "off" nil)
332                  (const :tag "on" t)
333                  (const guess)))
334
335 ;;;###autoload
336 (defcustom message-signature-separator "^-- *$"
337   "Regexp matching the signature separator."
338   :type 'regexp
339   :group 'message-various)
340
341 (defcustom message-signature-separator-for-insertion "-- \n"
342   "*Signature separator. This value will be inserted as signature separator
343 when composing message. Default value is \"-- \\n\". Notice: Changing this
344 value may go against RFC-1036 and draft-ietf-usefor-article-05.txt. "
345   :type 'string
346   :group 'message-insertion)
347
348 (defcustom message-elide-ellipsis "\n[...]\n\n"
349   "*The string which is inserted for elided text."
350   :type 'string
351   :group 'message-various)
352
353 (defcustom message-interactive t
354   "Non-nil means when sending a message wait for and display errors.
355 nil means let mailer mail back a message to report errors."
356   :group 'message-sending
357   :group 'message-mail
358   :type 'boolean)
359
360 (defcustom message-generate-new-buffers 'unique
361   "*Non-nil means create a new message buffer whenever `message-setup' is called.
362 If this is a function, call that function with three parameters:  The type,
363 the to address and the group name.  (Any of these may be nil.)  The function
364 should return the new buffer name."
365   :group 'message-buffers
366   :type '(choice (const :tag "off" nil)
367                  (const :tag "unique" unique)
368                  (const :tag "unsent" unsent)
369                  (function fun)))
370
371 (defcustom message-kill-buffer-on-exit nil
372   "*Non-nil means that the message buffer will be killed after sending a message."
373   :group 'message-buffers
374   :type 'boolean)
375
376 (defcustom message-kill-buffer-query-function 'yes-or-no-p
377   "*Function used to prompt user whether to kill the message buffer.  If
378 it is t, the buffer will be killed unconditionally."
379   :type '(radio (function-item yes-or-no-p)
380                 (function-item y-or-n-p)
381                 (function-item nnheader-Y-or-n-p)
382                 (function :tag "Other" t))
383   :group 'message-buffers)
384
385 (defcustom message-kill-buffer-and-remove-file t
386   "*Non-nil means that the associated file will be removed before
387 removing the message buffer.  However, it is treated as nil when the
388 command `message-mimic-kill-buffer' is used."
389   :group 'message-buffers
390   :type 'boolean)
391
392 (eval-when-compile
393   (defvar gnus-local-organization))
394 (defcustom message-user-organization
395   (or (and (boundp 'gnus-local-organization)
396            (stringp gnus-local-organization)
397            gnus-local-organization)
398       (getenv "ORGANIZATION")
399       t)
400   "*String to be used as an Organization header.
401 If t, use `message-user-organization-file'."
402   :group 'message-headers
403   :type '(choice string
404                  (const :tag "consult file" t)))
405
406 ;;;###autoload
407 (defcustom message-user-organization-file "/usr/lib/news/organization"
408   "*Local news organization file."
409   :type 'file
410   :group 'message-headers)
411
412 (defcustom message-forward-start-separator
413   (concat (mime-make-tag "message" "rfc822") "\n")
414   "*Delimiter inserted before forwarded messages."
415   :group 'message-forwarding
416   :type 'string)
417
418 (defcustom message-forward-end-separator
419   (concat (mime-make-tag "text" "plain") "\n")
420   "*Delimiter inserted after forwarded messages."
421   :group 'message-forwarding
422   :type 'string)
423
424 (defcustom message-included-forward-headers
425   "^From:\\|^Newsgroups:\\|^Subject:\\|^Date:\\|^\\(Mail-\\)?Followup-To:\\|^\\(Mail-\\)?Reply-To:\\|^Mail-Copies-To:\\|^Organization:\\|^Summary:\\|^Keywords:\\|^To:\\|^Cc:\\|^Posted-To:\\|^Apparently-To:\\|^Gnus-Warning:\\|^Resent-\\|^Message-ID:\\|^References:\\|^Content-\\|^MIME-Version:"
426   "*Regexp matching headers to be included in forwarded messages."
427   :group 'message-forwarding
428   :type 'regexp)
429
430 (defcustom message-make-forward-subject-function
431   'message-forward-subject-author-subject
432   "*List of functions called to generate subject headers for forwarded messages.
433 The subject generated by the previous function is passed into each
434 successive function.
435
436 The provided functions are:
437
438 * `message-forward-subject-author-subject' (Source of article (author or
439       newsgroup)), in brackets followed by the subject
440 * `message-forward-subject-fwd' (Subject of article with 'Fwd:' prepended
441       to it."
442   :group 'message-forwarding
443   :type '(radio (function-item message-forward-subject-author-subject)
444                 (function-item message-forward-subject-fwd)
445                 (repeat :tag "List of functions" function)))
446
447 (defcustom message-forward-as-mime t
448   "*If non-nil, forward messages as an inline/rfc822 MIME section.  Otherwise, directly inline the old message in the forwarded message."
449   :version "21.1"
450   :group 'message-forwarding
451   :type 'boolean)
452
453 (defcustom message-forward-show-mml t
454   "*If non-nil, forward messages are shown as mml.  Otherwise, forward messages are unchanged."
455   :version "21.1"
456   :group 'message-forwarding
457   :type 'boolean)
458
459 (defcustom message-forward-before-signature t
460   "*If non-nil, put forwarded message before signature, else after."
461   :group 'message-forwarding
462   :type 'boolean)
463
464 (defcustom message-wash-forwarded-subjects nil
465   "*If non-nil, try to remove as much old cruft as possible from the subject of messages before generating the new subject of a forward."
466   :group 'message-forwarding
467   :type 'boolean)
468
469 (defcustom message-ignored-resent-headers "^Return-receipt\\|^X-Gnus\\|^Gnus-Warning:"
470   "*All headers that match this regexp will be deleted when resending a message."
471   :group 'message-interface
472   :type 'regexp)
473
474 (defcustom message-forward-ignored-headers "^Content-Transfer-Encoding:\\|^X-Gnus"
475   "*All headers that match this regexp will be deleted when forwarding a message."
476   :version "21.1"
477   :group 'message-forwarding
478   :type '(choice (const :tag "None" nil)
479                  regexp))
480
481 (defcustom message-ignored-cited-headers "."
482   "*Delete these headers from the messages you yank."
483   :group 'message-insertion
484   :type 'regexp)
485
486 (defcustom message-cite-prefix-regexp
487   (if (string-match "[[:digit:]]" "1") ;; support POSIX?
488       "\\([ \t]*[-_.[:word:]]+>+\\|[ \t]*[]>»|:}+]\\)+"
489     ;; ?-, ?_ or ?. MUST NOT be in syntax entry w.
490     (let ((old-table (syntax-table))
491           non-word-constituents)
492       (set-syntax-table text-mode-syntax-table)
493       (setq non-word-constituents
494             (concat
495              (if (string-match "\\w" "-")  "" "-")
496              (if (string-match "\\w" "_")  "" "_")
497              (if (string-match "\\w" ".")  "" ".")))
498       (set-syntax-table old-table)
499       (if (equal non-word-constituents "")
500           "\\([ \t]*\\(\\w\\)+>+\\|[ \t]*[]>»|:}+]\\)+"
501         (concat "\\([ \t]*\\(\\w\\|["
502                 non-word-constituents
503                 "]\\)+>+\\|[ \t]*[]>»|:}+]\\)+"))))
504   "*Regexp matching the longest possible citation prefix on a line."
505   :group 'message-insertion
506   :type 'regexp)
507
508 (defcustom message-cancel-message "I am canceling my own article.\n"
509   "Message to be inserted in the cancel message."
510   :group 'message-interface
511   :type 'string)
512
513 ;; Useful to set in site-init.el
514 ;;;###autoload
515 (defcustom message-send-mail-function 'message-send-mail-with-sendmail
516   "Function to call to send the current buffer as mail.
517 The headers should be delimited by a line whose contents match the
518 variable `mail-header-separator'.
519
520 Valid values include `message-send-mail-with-sendmail' (the default),
521 `message-send-mail-with-mh', `message-send-mail-with-qmail',
522 `message-send-mail-with-smtp', `smtpmail-send-it' and `feedmail-send-it'.
523
524 See also `send-mail-function'."
525   :type '(radio (function-item message-send-mail-with-sendmail)
526                 (function-item message-send-mail-with-mh)
527                 (function-item message-send-mail-with-qmail)
528                 (function-item message-send-mail-with-smtp)
529                 (function-item smtpmail-send-it)
530                 (function-item feedmail-send-it)
531                 (function :tag "Other"))
532   :group 'message-sending
533   :group 'message-mail)
534
535 ;; 1997-09-29 by MORIOKA Tomohiko
536 (defcustom message-send-news-function 'message-send-news-with-gnus
537   "Function to call to send the current buffer as news.
538 The headers should be delimited by a line whose contents match the
539 variable `mail-header-separator'."
540   :group 'message-sending
541   :group 'message-news
542   :type 'function)
543
544 (defcustom message-reply-to-function nil
545   "If non-nil, function that should return a list of headers.
546 This function should pick out addresses from the To, Cc, and From headers
547 and respond with new To and Cc headers."
548   :group 'message-interface
549   :type '(choice function (const nil)))
550
551 (defcustom message-wide-reply-to-function nil
552   "If non-nil, function that should return a list of headers.
553 This function should pick out addresses from the To, Cc, and From headers
554 and respond with new To and Cc headers."
555   :group 'message-interface
556   :type '(choice function (const nil)))
557
558 (defcustom message-followup-to-function nil
559   "If non-nil, function that should return a list of headers.
560 This function should pick out addresses from the To, Cc, and From headers
561 and respond with new To and Cc headers."
562   :group 'message-interface
563   :type '(choice function (const nil)))
564
565 (defcustom message-use-followup-to 'ask
566   "*Specifies what to do with Followup-To header.
567 If nil, always ignore the header.  If it is t, use its value, but
568 query before using the \"poster\" value.  If it is the symbol `ask',
569 always query the user whether to use the value.  If it is the symbol
570 `use', always use the value."
571   :group 'message-interface
572   :type '(choice (const :tag "ignore" nil)
573                  (const :tag "use & query" t)
574                  (const :tag "maybe" t)
575                  (const :tag "always" use)
576                  (const :tag "ask" ask)))
577
578 (defcustom message-use-mail-copies-to 'ask
579   "*Specifies what to do with Mail-Copies-To header.
580 If nil, always ignore the header.  If it is t, use its value, but
581 query before using the value other than \"always\" or \"never\".
582 If it is the symbol `ask', always query the user whether to use
583 the value.  If it is the symbol `use', always use the value."
584   :group 'message-interface
585   :type '(choice (const :tag "ignore" nil)
586                  (const :tag "maybe" t)
587                  (const :tag "always" use)
588                  (const :tag "ask" ask)))
589
590 ;;; XXX: 'ask and 'use are not implemented yet.
591 (defcustom message-use-mail-reply-to 'ask
592   "*Specifies what to do with Mail-Reply-To/Reply-To header.
593 If nil, always ignore the header.  If it is t or the symbol `use', use
594 its value.  If it is the symbol `ask', always query the user whether to
595 use the value.  Note that if \"Reply-To\" is marked as \"broken\", its value
596 is never used."
597   :group 'message-interface
598   :type '(choice (const :tag "ignore" nil)
599                  (const :tag "maybe" t)
600                  (const :tag "always" use)
601                  (const :tag "ask" ask)))
602
603 (defcustom message-use-mail-followup-to 'use
604   "*Specifies what to do with Mail-Followup-To header.
605 If nil, always ignore the header.  If it is the symbol `ask', always
606 query the user whether to use the value.  If it is t or the symbol
607 `use', always use the value."
608   :group 'message-interface
609   :type '(choice (const :tag "ignore" nil)
610                  (const :tag "maybe" t)
611                  (const :tag "always" use)
612                  (const :tag "ask" ask)))
613
614 (defcustom message-subscribed-address-functions nil
615   "*Specifies functions for determining list subscription.
616 If nil, do not attempt to determine list subscribtion with functions.
617 If non-nil, this variable contains a list of functions which return
618 regular expressions to match lists.  These functions can be used in
619 conjunction with `message-subscribed-regexps' and
620 `message-subscribed-addresses'."
621   :group 'message-interface
622   :type '(repeat sexp))
623
624 (defcustom message-subscribed-address-file nil
625   "*A file containing addresses the user is subscribed to.
626 If nil, do not look at any files to determine list subscriptions.  If
627 non-nil, each line of this file should be a mailing list address."
628   :group 'message-interface
629   :type 'string)
630
631 (defcustom message-subscribed-addresses nil
632   "*Specifies a list of addresses the user is subscribed to.
633 If nil, do not use any predefined list subscriptions.  This list of
634 addresses can be used in conjuction with
635 `message-subscribed-address-functions' and `message-subscribed-regexps'."
636   :group 'message-interface
637   :type '(repeat string))
638
639 (defcustom message-subscribed-regexps nil
640   "*Specifies a list of addresses the user is subscribed to.
641 If nil, do not use any predefined list subscriptions.  This list of
642 regular expressions can be used in conjuction with
643 `message-subscribed-address-functions' and `message-subscribed-addresses'."
644   :group 'message-interface
645   :type '(repeat regexp))
646
647 (defcustom message-allow-no-recipients 'ask
648   "Specifies what to do when there are no recipients other than Gcc/Fcc.
649 If it is the symbol `always', the posting is allowed.  If it is the
650 symbol `never', the posting is not allowed.  If it is the symbol
651 `ask', you are prompted."
652   :group 'message-interface
653   :type '(choice (const always)
654                  (const never)
655                  (const ask)))
656
657 (defcustom message-sendmail-f-is-evil nil
658   "*Non-nil means don't add \"-f username\" to the sendmail command line.
659 Doing so would be even more evil than leaving it out."
660   :group 'message-sending
661   :type 'boolean)
662
663 ;; qmail-related stuff
664 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
665   "Location of the qmail-inject program."
666   :group 'message-sending
667   :type 'file)
668
669 (defcustom message-qmail-inject-args nil
670   "Arguments passed to qmail-inject programs.
671 This should be a list of strings, one string for each argument.  It
672 may also be a function.
673
674 For e.g., if you wish to set the envelope sender address so that bounces
675 go to the right place or to deal with listserv's usage of that address, you
676 might set this variable to '(\"-f\" \"you@some.where\")."
677   :group 'message-sending
678   :type '(choice (function)
679                  (repeat string)))
680
681 (defvar message-cater-to-broken-inn t
682   "Non-nil means Gnus should not fold the `References' header.
683 Folding `References' makes ancient versions of INN create incorrect
684 NOV lines.")
685
686 (eval-when-compile
687   (defvar gnus-post-method)
688   (defvar gnus-select-method))
689 (defcustom message-post-method
690   (cond ((and (boundp 'gnus-post-method)
691               (listp gnus-post-method)
692               gnus-post-method)
693          gnus-post-method)
694         ((boundp 'gnus-select-method)
695          gnus-select-method)
696         (t '(nnspool "")))
697   "*Method used to post news.
698 Note that when posting from inside Gnus, for instance, this
699 variable isn't used."
700   :group 'message-news
701   :group 'message-sending
702   ;; This should be the `gnus-select-method' widget, but that might
703   ;; create a dependence to `gnus.el'.
704   :type 'sexp)
705
706 (defcustom message-generate-headers-first nil
707   "*If non-nil, generate all required headers before composing.
708 The variables `message-required-news-headers' and
709 `message-required-mail-headers' specify which headers to generate.
710
711 Note that the variable `message-deletable-headers' specifies headers which
712 are to be deleted and then re-generated before sending, so this variable
713 will not have a visible effect for those headers."
714   :group 'message-headers
715   :type 'boolean)
716
717 (defcustom message-setup-hook '(turn-on-mime-edit)
718   "Normal hook, run each time a new outgoing message is initialized.
719 The function `message-setup' runs this hook."
720   :group 'message-various
721   :type 'hook)
722
723 (defcustom message-cancel-hook nil
724   "Hook run when cancelling articles."
725   :group 'message-various
726   :type 'hook)
727
728 (defcustom message-signature-setup-hook nil
729   "Normal hook, run each time a new outgoing message is initialized.
730 It is run after the headers have been inserted and before
731 the signature is inserted."
732   :group 'message-various
733   :type 'hook)
734
735 (defcustom message-bounce-setup-hook nil
736   "Normal hook, run each time a re-sending bounced message is initialized.
737 The function `message-bounce' runs this hook."
738   :group 'message-various
739   :type 'hook)
740
741 (defcustom message-supersede-setup-hook nil
742   "Normal hook, run each time a supersede message is initialized.
743 The function `message-supersede' runs this hook."
744   :group 'message-various
745   :type 'hook)
746
747 (defcustom message-mode-hook nil
748   "Hook run in message mode buffers."
749   :group 'message-various
750   :type 'hook)
751
752 (defcustom message-header-hook '((lambda () (eword-encode-header t)))
753   "Hook run in a message mode buffer narrowed to the headers."
754   :group 'message-various
755   :type 'hook)
756
757 (defcustom message-header-setup-hook nil
758   "Hook called narrowed to the headers when setting up a message buffer."
759   :group 'message-various
760   :type 'hook)
761
762 (defcustom message-minibuffer-local-map
763   (let ((map (make-sparse-keymap 'message-minibuffer-local-map)))
764     (set-keymap-parent map minibuffer-local-map)
765     map)
766   "Keymap for `message-read-from-minibuffer'.")
767
768 ;;;###autoload
769 (defcustom message-citation-line-function 'message-insert-citation-line
770   "*Function called to insert the \"Whomever writes:\" line.
771
772 Note that Gnus provides a feature where the reader can click on
773 `writes:' to hide the cited text.  If you change this line too much,
774 people who read your message will have to change their Gnus
775 configuration.  See the variable `gnus-cite-attribution-suffix'."
776   :type 'function
777   :group 'message-insertion)
778
779 ;;;###autoload
780 (defcustom message-yank-prefix "> "
781   "*Prefix inserted on the lines of yanked messages.
782 Fix `message-cite-prefix-regexp' if it is set to an abnormal value.
783 See also `message-yank-cited-prefix'."
784   :type 'string
785   :group 'message-insertion)
786
787 (defcustom message-yank-add-new-references t
788   "Non-nil means new IDs will be added to \"References\" field when an
789 article is yanked by the command `message-yank-original' interactively.
790 If it is a symbol `message-id-only', only an ID from \"Message-ID\" field
791 is used, otherwise IDs extracted from \"References\", \"In-Reply-To\" and
792 \"Message-ID\" fields are used."
793   :type '(radio (const :tag "Do not add anything" nil)
794                 (const :tag "From Message-Id, References and In-Reply-To fields" t)
795                 (const :tag "From only Message-Id field." message-id-only))
796   :group 'message-insertion)
797
798 (defcustom message-list-references-add-position nil
799   "Integer value means position for adding to \"References\" field when
800 an article is yanked by the command `message-yank-original' interactively."
801   :type '(radio (const :tag "Add to last" nil)
802                 (integer :tag "Position from last ID"))
803   :group 'message-insertion)
804
805 (defcustom message-yank-cited-prefix ">"
806   "*Prefix inserted on cited or empty lines of yanked messages.
807 Fix `message-cite-prefix-regexp' if it is set to an abnormal value.
808 See also `message-yank-prefix'."
809   :type 'string
810   :group 'message-insertion)
811
812 (defcustom message-indentation-spaces 3
813   "*Number of spaces to insert at the beginning of each cited line.
814 Used by `message-yank-original' via `message-yank-cite'."
815   :group 'message-insertion
816   :type 'integer)
817
818 ;;;###autoload
819 (defcustom message-cite-function 'message-cite-original
820   "*Function for citing an original message.
821 Predefined functions include `message-cite-original' and
822 `message-cite-original-without-signature'.
823 Note that `message-cite-original' uses `mail-citation-hook' if that is non-nil."
824   :type '(radio (function-item message-cite-original)
825                 (function-item message-cite-original-without-signature)
826                 (function-item mu-cite-original)
827                 (function-item sc-cite-original)
828                 (function :tag "Other"))
829   :group 'message-insertion)
830
831 ;;;###autoload
832 (defcustom message-suspend-font-lock-when-citing nil
833   "Non-nil means suspend font-lock'ing while citing an original message.
834 Some lazy demand-driven fontification tools (or Emacs itself) have a
835 bug that they often miss a buffer to be fontified.  It will mostly
836 occur when Emacs prompts user for any inputs in the minibuffer.
837 Setting this option to non-nil may help you to avoid unpleasant errors
838 even if it is an add-hoc expedient."
839   :type 'boolean
840   :group 'message-insertion)
841
842 ;;;###autoload
843 (defcustom message-indent-citation-function 'message-indent-citation
844   "*Function for modifying a citation just inserted in the mail buffer.
845 This can also be a list of functions.  Each function can find the
846 citation between (point) and (mark t).  And each function should leave
847 point and mark around the citation text as modified."
848   :type 'function
849   :group 'message-insertion)
850
851 ;;;###autoload
852 (defcustom message-signature t
853   "*String to be inserted at the end of the message buffer.
854 If t, the `message-signature-file' file will be inserted instead.
855 If a function, the result from the function will be used instead.
856 If a form, the result from the form will be used instead."
857   :type 'sexp
858   :group 'message-insertion)
859
860 ;;;###autoload
861 (defcustom message-signature-file "~/.signature"
862   "*Name of file containing the text inserted at end of message buffer.
863 Ignored if the named file doesn't exist.
864 If nil, don't insert a signature."
865   :type '(choice file (const :tags "None" nil))
866   :group 'message-insertion)
867
868 (defcustom message-distribution-function nil
869   "*Function called to return a Distribution header."
870   :group 'message-news
871   :group 'message-headers
872   :type '(choice function (const nil)))
873
874 (defcustom message-expires 14
875   "Number of days before your article expires."
876   :group 'message-news
877   :group 'message-headers
878   :link '(custom-manual "(message)News Headers")
879   :type 'integer)
880
881 (defcustom message-user-path nil
882   "If nil, use the NNTP server name in the Path header.
883 If stringp, use this; if non-nil, use no host name (user name only)."
884   :group 'message-news
885   :group 'message-headers
886   :link '(custom-manual "(message)News Headers")
887   :type '(choice (const :tag "nntp" nil)
888                  (string :tag "name")
889                  (sexp :tag "none" :format "%t" t)))
890
891 (defvar message-reply-buffer nil)
892 (defvar message-reply-headers nil
893   "The headers of the current replied article.
894 It is a vector of the following headers:
895 \[number subject from date id references chars lines xref extra].")
896 (defvar message-sent-message-via nil)
897 (defvar message-checksum nil)
898 (defvar message-send-actions nil
899   "A list of actions to be performed upon successful sending of a message.")
900 (defvar message-exit-actions nil
901   "A list of actions to be performed upon exiting after sending a message.")
902 (defvar message-kill-actions nil
903   "A list of actions to be performed before killing a message buffer.")
904 (defvar message-postpone-actions nil
905   "A list of actions to be performed after postponing a message.")
906 (defvar message-original-frame nil)
907 (defvar message-parameter-alist nil)
908 (defvar message-startup-parameter-alist nil)
909
910 (define-widget 'message-header-lines 'text
911   "All header lines must be LFD terminated."
912   :format "%{%t%}:%n%v"
913   :valid-regexp "^\\'"
914   :error "All header lines must be newline terminated")
915
916 (defcustom message-default-headers ""
917   "*A string containing header lines to be inserted in outgoing messages.
918 It is inserted before you edit the message, so you can edit or delete
919 these lines."
920   :group 'message-headers
921   :type 'message-header-lines)
922
923 (defcustom message-default-mail-headers ""
924   "*A string of header lines to be inserted in outgoing mails."
925   :group 'message-headers
926   :group 'message-mail
927   :type 'message-header-lines)
928
929 (defcustom message-default-news-headers ""
930   "*A string of header lines to be inserted in outgoing news articles."
931   :group 'message-headers
932   :group 'message-news
933   :type 'message-header-lines)
934
935 ;; Note: could use /usr/ucb/mail instead of sendmail;
936 ;; options -t, and -v if not interactive.
937 (defcustom message-mailer-swallows-blank-line
938   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)"
939                          system-configuration)
940            (file-readable-p "/etc/sendmail.cf")
941            (let ((buffer (get-buffer-create " *temp*")))
942              (unwind-protect
943                  (save-excursion
944                    (set-buffer buffer)
945                    (insert-file-contents "/etc/sendmail.cf")
946                    (goto-char (point-min))
947                    (let ((case-fold-search nil))
948                      (re-search-forward "^OR\\>" nil t)))
949                (kill-buffer buffer))))
950       ;; According to RFC822, "The field-name must be composed of printable
951       ;; ASCII characters (i. e., characters that have decimal values between
952       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
953       ;; space, or colon.
954       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
955   "*Set this non-nil if the system's mailer runs the header and body together.
956 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
957 The value should be an expression to test whether the problem will
958 actually occur."
959   :group 'message-sending
960   :type 'sexp)
961
962 ;;; XXX: This symbol is overloaded!  See below.
963 (defvar message-user-agent nil
964   "String of the form of PRODUCT/VERSION.  Used for User-Agent header field.")
965
966 (static-when (boundp 'MULE)
967   (require 'reporter));; `define-mail-user-agent' is here.
968
969 ;;;###autoload
970 (define-mail-user-agent 'message-user-agent
971   'message-mail 'message-send-and-exit
972   'message-kill-buffer 'message-send-hook)
973
974 (defvar message-mh-deletable-headers '(Message-ID Date Lines Sender)
975   "If non-nil, delete the deletable headers before feeding to mh.")
976
977 (defvar message-send-method-alist
978   '((news message-news-p message-send-via-news)
979     (mail message-mail-p message-send-via-mail))
980   "Alist of ways to send outgoing messages.
981 Each element has the form
982
983   \(TYPE PREDICATE FUNCTION)
984
985 where TYPE is a symbol that names the method; PREDICATE is a function
986 called without any parameters to determine whether the message is
987 a message of type TYPE; and FUNCTION is a function to be called if
988 PREDICATE returns non-nil.  FUNCTION is called with one parameter --
989 the prefix.")
990
991 (defcustom message-mail-alias-type 'abbrev
992   "*What alias expansion type to use in Message buffers.
993 The default is `abbrev', which uses mailabbrev.  nil switches
994 mail aliases off."
995   :group 'message
996   :link '(custom-manual "(message)Mail Aliases")
997   :type '(choice (const :tag "Use Mailabbrev" abbrev)
998                  (const :tag "No expansion" nil)))
999
1000 (defcustom message-auto-save-directory
1001   (file-name-as-directory (nnheader-concat message-directory "drafts"))
1002   "*Directory where Message auto-saves buffers if Gnus isn't running.
1003 If nil, Message won't auto-save."
1004   :group 'message-buffers
1005   :type '(choice directory (const :tag "Don't auto-save" nil)))
1006
1007 (defcustom message-default-charset
1008   (and (featurep 'xemacs) (not (featurep 'mule)) 'iso-8859-1)
1009   "Default charset used in non-MULE XEmacsen."
1010   :version "21.1"
1011   :group 'message
1012   :type 'symbol)
1013
1014 (defcustom message-dont-reply-to-names
1015   (and (boundp 'rmail-dont-reply-to-names) rmail-dont-reply-to-names)
1016   "*A regexp specifying addresses to prune when doing wide replies.
1017 A value of nil means exclude your own user name only."
1018   :version "21.1"
1019   :group 'message
1020   :type '(choice (const :tag "Yourself" nil)
1021                  regexp))
1022
1023 (defvar message-shoot-gnksa-feet nil
1024   "*A list of GNKSA feet you are allowed to shoot.
1025 Gnus gives you all the opportunity you could possibly want for
1026 shooting yourself in the foot.  Also, Gnus allows you to shoot the
1027 feet of Good Net-Keeping Seal of Approval. The following are foot
1028 candidates:
1029 `empty-article'     Allow you to post an empty article;
1030 `quoted-text-only'  Allow you to post quoted text only;
1031 `multiple-copies'   Allow you to post multiple copies;
1032 `cancel-messages'   Allow you to cancel or supersede messages from 
1033                     your other email addresses.")
1034
1035 (defsubst message-gnksa-enable-p (feature)
1036   (or (not (listp message-shoot-gnksa-feet))
1037       (memq feature message-shoot-gnksa-feet)))
1038
1039 ;;; Internal variables.
1040 ;;; Well, not really internal.
1041
1042 (defvar message-mode-syntax-table
1043   (let ((table (copy-syntax-table text-mode-syntax-table)))
1044     (modify-syntax-entry ?% ". " table)
1045     (modify-syntax-entry ?> ". " table)
1046     (modify-syntax-entry ?< ". " table)
1047     table)
1048   "Syntax table used while in Message mode.")
1049
1050 (defface message-header-to-face
1051   '((((class color)
1052       (background dark))
1053      (:foreground "green2" :bold t))
1054     (((class color)
1055       (background light))
1056      (:foreground "MidnightBlue" :bold t))
1057     (t
1058      (:bold t :italic t)))
1059   "Face used for displaying From headers."
1060   :group 'message-faces)
1061
1062 (defface message-header-cc-face
1063   '((((class color)
1064       (background dark))
1065      (:foreground "green4" :bold t))
1066     (((class color)
1067       (background light))
1068      (:foreground "MidnightBlue"))
1069     (t
1070      (:bold t)))
1071   "Face used for displaying Cc headers."
1072   :group 'message-faces)
1073
1074 (defface message-header-subject-face
1075   '((((class color)
1076       (background dark))
1077      (:foreground "green3"))
1078     (((class color)
1079       (background light))
1080      (:foreground "navy blue" :bold t))
1081     (t
1082      (:bold t)))
1083   "Face used for displaying subject headers."
1084   :group 'message-faces)
1085
1086 (defface message-header-newsgroups-face
1087   '((((class color)
1088       (background dark))
1089      (:foreground "yellow" :bold t :italic t))
1090     (((class color)
1091       (background light))
1092      (:foreground "blue4" :bold t :italic t))
1093     (t
1094      (:bold t :italic t)))
1095   "Face used for displaying newsgroups headers."
1096   :group 'message-faces)
1097
1098 (defface message-header-other-face
1099   '((((class color)
1100       (background dark))
1101      (:foreground "#b00000"))
1102     (((class color)
1103       (background light))
1104      (:foreground "steel blue"))
1105     (t
1106      (:bold t :italic t)))
1107   "Face used for displaying newsgroups headers."
1108   :group 'message-faces)
1109
1110 (defface message-header-name-face
1111   '((((class color)
1112       (background dark))
1113      (:foreground "DarkGreen"))
1114     (((class color)
1115       (background light))
1116      (:foreground "cornflower blue"))
1117     (t
1118      (:bold t)))
1119   "Face used for displaying header names."
1120   :group 'message-faces)
1121
1122 (defface message-header-xheader-face
1123   '((((class color)
1124       (background dark))
1125      (:foreground "blue"))
1126     (((class color)
1127       (background light))
1128      (:foreground "blue"))
1129     (t
1130      (:bold t)))
1131   "Face used for displaying X-Header headers."
1132   :group 'message-faces)
1133
1134 (defface message-separator-face
1135   '((((class color)
1136       (background dark))
1137      (:foreground "blue3"))
1138     (((class color)
1139       (background light))
1140      (:foreground "brown"))
1141     (t
1142      (:bold t)))
1143   "Face used for displaying the separator."
1144   :group 'message-faces)
1145
1146 (defface message-cited-text-face
1147   '((((class color)
1148       (background dark))
1149      (:foreground "red"))
1150     (((class color)
1151       (background light))
1152      (:foreground "red"))
1153     (t
1154      (:bold t)))
1155   "Face used for displaying cited text names."
1156   :group 'message-faces)
1157
1158 (defface message-mml-face
1159   '((((class color)
1160       (background dark))
1161      (:foreground "ForestGreen"))
1162     (((class color)
1163       (background light))
1164      (:foreground "ForestGreen"))
1165     (t
1166      (:bold t)))
1167   "Face used for displaying MML."
1168   :group 'message-faces)
1169
1170 (defun message-font-lock-make-header-matcher (regexp)
1171   (let ((form
1172          `(lambda (limit)
1173             (let ((start (point)))
1174               (save-restriction
1175                 (widen)
1176                 (goto-char (point-min))
1177                 (if (re-search-forward
1178                      (concat "^" (regexp-quote mail-header-separator) "$")
1179                      nil t)
1180                     (setq limit (min limit (match-beginning 0))))
1181                 (goto-char start))
1182               (and (< start limit)
1183                    (re-search-forward ,regexp limit t))))))
1184     (if (featurep 'bytecomp)
1185         (byte-compile form)
1186       form)))
1187
1188 (defvar message-font-lock-keywords
1189   (let ((content "[ \t]*\\(.+\\(\n[ \t].*\\)*\\)\n?"))
1190     `((,(message-font-lock-make-header-matcher
1191          (concat "^\\([Tt]o:\\)" content))
1192        (1 'message-header-name-face)
1193        (2 'message-header-to-face nil t))
1194       (,(message-font-lock-make-header-matcher
1195          (concat "^\\([GBF]?[Cc][Cc]:\\|[Rr]eply-[Tt]o:\\|"
1196                  "[Mm]ail-[Cc]opies-[Tt]o:\\|"
1197                  "[Mm]ail-[Rr]eply-[Tt]o:\\|"
1198                  "[Mm]ail-[Ff]ollowup-[Tt]o:\\)" content))
1199        (1 'message-header-name-face)
1200        (2 'message-header-cc-face nil t))
1201       (,(message-font-lock-make-header-matcher
1202          (concat "^\\([Ss]ubject:\\)" content))
1203        (1 'message-header-name-face)
1204        (2 'message-header-subject-face nil t))
1205       (,(message-font-lock-make-header-matcher
1206          (concat "^\\([Nn]ewsgroups:\\|Followup-[Tt]o:\\)" content))
1207        (1 'message-header-name-face)
1208        (2 'message-header-newsgroups-face nil t))
1209       (,(message-font-lock-make-header-matcher
1210          (concat "^\\([A-Z][^: \n\t]+:\\)" content))
1211        (1 'message-header-name-face)
1212        (2 'message-header-other-face nil t))
1213       (,(message-font-lock-make-header-matcher
1214          (concat "^\\(X-[A-Za-z0-9-]+:\\|In-Reply-To:\\)" content))
1215        (1 'message-header-name-face)
1216        (2 'message-header-name-face))
1217       ,@(if (and mail-header-separator
1218                  (not (equal mail-header-separator "")))
1219             `((,(concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
1220                1 'message-separator-face))
1221           nil)
1222       (,(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     (setq canlock-password-for-verify canlock-password))
3692   canlock-password)
3693
3694 (defun message-insert-canlock ()
3695   (when message-insert-canlock
3696     (message-canlock-password)
3697     (canlock-insert-header)))
3698
3699 (defun message-send-news (&optional arg)
3700   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
3701          (case-fold-search nil)
3702          (method (if (message-functionp message-post-method)
3703                      (funcall message-post-method arg)
3704                    message-post-method))
3705          (newsgroups-field (save-restriction
3706                              (message-narrow-to-headers-or-head)
3707                              (message-fetch-field "Newsgroups")))
3708          (followup-field (save-restriction
3709                            (message-narrow-to-headers-or-head)
3710                            (message-fetch-field "Followup-To")))
3711          ;; BUG: We really need to get the charset for each name in the
3712          ;; Newsgroups and Followup-To lines to allow crossposting
3713          ;; between group namess with incompatible character sets.
3714          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
3715          (group-field-charset
3716           (gnus-group-name-charset method newsgroups-field))
3717          (followup-field-charset
3718           (gnus-group-name-charset method (or followup-field "")))
3719          (mime-field-encoding-method-alist
3720           (append (when group-field-charset
3721                     (list (cons "Newsgroups" group-field-charset)))
3722                   (when followup-field-charset
3723                     (list (cons "Followup-To" followup-field-charset)))
3724                   mime-field-encoding-method-alist))
3725          (message-syntax-checks
3726           (if (and arg
3727                    (listp message-syntax-checks))
3728               (cons '(existing-newsgroups . disabled)
3729                     message-syntax-checks)
3730             message-syntax-checks))
3731          (message-this-is-news t)
3732          result)
3733     (save-restriction
3734       (message-narrow-to-headers)
3735       ;; Insert some headers.
3736       (message-generate-headers message-required-news-headers)
3737       (message-insert-canlock)
3738       ;; Let the user do all of the above.
3739       (run-hooks 'message-header-hook))
3740     ;; Note: This check will be disabled by the ".*" default value for
3741     ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
3742     (when (and group-field-charset
3743                (listp message-syntax-checks))
3744       (setq message-syntax-checks
3745             (cons '(valid-newsgroups . disabled)
3746                   message-syntax-checks)))
3747     (message-cleanup-headers)
3748     (if (not (let ((message-post-method method))
3749                (message-check-news-syntax)))
3750         nil
3751       (unwind-protect
3752           (save-excursion
3753             (set-buffer tembuf)
3754             (buffer-disable-undo)
3755             (erase-buffer)
3756             (insert-buffer-substring message-encoding-buffer)
3757             ;; Remove some headers.
3758             (save-restriction
3759               (message-narrow-to-headers)
3760 ;; We Semi-gnus people have no use for it.
3761 ;;            ;; We (re)generate the Lines header.
3762 ;;            (when (memq 'Lines message-required-mail-headers)
3763 ;;              (message-generate-headers '(Lines)))
3764               ;; Remove some headers.
3765               (message-remove-header message-ignored-news-headers t))
3766             (goto-char (point-max))
3767             ;; require one newline at the end.
3768             (or (= (preceding-char) ?\n)
3769                 (insert ?\n))
3770             (setq result (message-maybe-split-and-send-news method)))
3771         (kill-buffer tembuf))
3772       (set-buffer message-edit-buffer)
3773       (if result
3774           (progn
3775             (message "Couldn't send message via news: %s"
3776                      (nnheader-get-report (car method)))
3777             nil)
3778         (push 'news message-sent-message-via)))))
3779
3780 ;; 1997-09-29 by MORIOKA Tomohiko
3781 (defun message-send-news-with-gnus (method)
3782   (let ((case-fold-search t))
3783     ;; Remove the delimiter.
3784     (goto-char (point-min))
3785     (re-search-forward
3786      (concat "^" (regexp-quote mail-header-separator) "\n"))
3787     (replace-match "\n")
3788     (backward-char 1)
3789     (run-hooks 'message-send-news-hook)
3790     (gnus-open-server method)
3791     (message "Sending news via %s..." (gnus-server-string method))
3792     (gnus-request-post method)
3793     ))
3794
3795 ;;;
3796 ;;; Header generation & syntax checking.
3797 ;;;
3798
3799 (defun message-check-element (type)
3800   "Return non-nil if this TYPE is not to be checked."
3801   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
3802       t
3803     (let ((able (assq type message-syntax-checks)))
3804       (and (consp able)
3805            (eq (cdr able) 'disabled)))))
3806
3807 (defun message-check-news-syntax ()
3808   "Check the syntax of the message."
3809   (save-excursion
3810     (save-restriction
3811       (widen)
3812       (and
3813        ;; We narrow to the headers and check them first.
3814        (save-excursion
3815          (save-restriction
3816            (message-narrow-to-headers)
3817            (message-check-news-header-syntax)))
3818        ;; Check the body.
3819        (save-excursion
3820          (set-buffer message-edit-buffer)
3821          (message-check-news-body-syntax))))))
3822
3823 (defun message-check-news-header-syntax ()
3824   (and
3825    ;; Check Newsgroups header.
3826    (message-check 'newsgroups
3827      (let ((group (message-fetch-field "newsgroups")))
3828        (or
3829         (and group
3830              (not (string-match "\\`[ \t]*\\'" group)))
3831         (ignore
3832          (message
3833           "The newsgroups field is empty or missing.  Posting is denied.")))))
3834    ;; Check the Subject header.
3835    (message-check 'subject
3836      (let* ((case-fold-search t)
3837             (subject (message-fetch-field "subject")))
3838        (or
3839         (and subject
3840              (not (string-match "\\`[ \t]*\\'" subject)))
3841         (ignore
3842          (message
3843           "The subject field is empty or missing.  Posting is denied.")))))
3844    ;; Check for commands in Subject.
3845    (message-check 'subject-cmsg
3846      (if (string-match "^cmsg " (message-fetch-field "subject"))
3847          (y-or-n-p
3848           "The control code \"cmsg\" is in the subject.  Really post? ")
3849        t))
3850    ;; Check for multiple identical headers.
3851    (message-check 'multiple-headers
3852      (let (found)
3853        (while (and (not found)
3854                    (re-search-forward "^[^ \t:]+: " nil t))
3855          (save-excursion
3856            (or (re-search-forward
3857                 (concat "^"
3858                         (regexp-quote
3859                          (setq found
3860                                (buffer-substring
3861                                 (match-beginning 0) (- (match-end 0) 2))))
3862                         ":")
3863                 nil t)
3864                (setq found nil))))
3865        (if found
3866            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
3867          t)))
3868    ;; Check for Version and Sendsys.
3869    (message-check 'sendsys
3870      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
3871          (y-or-n-p
3872           (format "The article contains a %s command.  Really post? "
3873                   (buffer-substring (match-beginning 0)
3874                                     (1- (match-end 0)))))
3875        t))
3876    ;; See whether we can shorten Followup-To.
3877    (message-check 'shorten-followup-to
3878      (let ((newsgroups (message-fetch-field "newsgroups"))
3879            (followup-to (message-fetch-field "followup-to"))
3880            to)
3881        (when (and newsgroups
3882                   (string-match "," newsgroups)
3883                   (not followup-to)
3884                   (not
3885                    (zerop
3886                     (length
3887                      (setq to (completing-read
3888                                "Followups to (default: no Followup-To header) "
3889                                (mapcar (lambda (g) (list g))
3890                                        (cons "poster"
3891                                              (message-tokenize-header
3892                                               newsgroups)))))))))
3893          (goto-char (point-min))
3894          (insert "Followup-To: " to "\n"))
3895        t))
3896    ;; Check "Shoot me".
3897    (message-check 'shoot
3898      (if (re-search-forward
3899           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
3900          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
3901        t))
3902    ;; Check for Approved.
3903    (message-check 'approved
3904      (if (re-search-forward "^Approved:" nil t)
3905          (y-or-n-p "The article contains an Approved header.  Really post? ")
3906        t))
3907    ;; Check the Message-ID header.
3908    (message-check 'message-id
3909      (let* ((case-fold-search t)
3910             (message-id (message-fetch-field "message-id" t)))
3911        (or (not message-id)
3912            ;; Is there an @ in the ID?
3913            (and (string-match "@" message-id)
3914                 ;; Is there a dot in the ID?
3915                 (string-match "@[^.]*\\." message-id)
3916                 ;; Does the ID end with a dot?
3917                 (not (string-match "\\.>" message-id)))
3918            (y-or-n-p
3919             (format "The Message-ID looks strange: \"%s\".  Really post? "
3920                     message-id)))))
3921    ;; Check the Newsgroups & Followup-To headers.
3922    (message-check 'existing-newsgroups
3923      (let* ((case-fold-search t)
3924             (newsgroups (message-fetch-field "newsgroups"))
3925             (followup-to (message-fetch-field "followup-to"))
3926             (groups (message-tokenize-header
3927                      (if followup-to
3928                          (concat newsgroups "," followup-to)
3929                        newsgroups)))
3930             (post-method (if (message-functionp message-post-method)
3931                              (funcall message-post-method)
3932                            message-post-method))
3933             ;; KLUDGE to handle nnvirtual groups.  Doing this right
3934             ;; would probably involve a new nnoo function.
3935             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
3936             (method (if (and (consp post-method)
3937                              (eq (car post-method) 'nnvirtual)
3938                              gnus-message-group-art)
3939                         (let ((group (car (nnvirtual-find-group-art
3940                                            (car gnus-message-group-art)
3941                                            (cdr gnus-message-group-art)))))
3942                           (gnus-find-method-for-group group))
3943                       post-method))
3944             (known-groups
3945              (mapcar (lambda (n)
3946                        (gnus-group-name-decode
3947                         (gnus-group-real-name n)
3948                         (gnus-group-name-charset method n)))
3949                      (gnus-groups-from-server method)))
3950             errors)
3951        (while groups
3952          (unless (or (equal (car groups) "poster")
3953                      (member (car groups) known-groups))
3954            (push (car groups) errors))
3955          (pop groups))
3956        (cond
3957         ;; Gnus is not running.
3958         ((or (not (and (boundp 'gnus-active-hashtb)
3959                        gnus-active-hashtb))
3960              (not (boundp 'gnus-read-active-file)))
3961          t)
3962         ;; We don't have all the group names.
3963         ((and (or (not gnus-read-active-file)
3964                   (eq gnus-read-active-file 'some))
3965               errors)
3966          (y-or-n-p
3967           (format
3968            "Really post to %s possibly unknown group%s: %s? "
3969            (if (= (length errors) 1) "this" "these")
3970            (if (= (length errors) 1) "" "s")
3971            (mapconcat 'identity errors ", "))))
3972         ;; There were no errors.
3973         ((not errors)
3974          t)
3975         ;; There are unknown groups.
3976         (t
3977          (y-or-n-p
3978           (format
3979            "Really post to %s unknown group%s: %s? "
3980            (if (= (length errors) 1) "this" "these")
3981            (if (= (length errors) 1) "" "s")
3982            (mapconcat 'identity errors ", ")))))))
3983    ;; Check the Newsgroups & Followup-To headers for syntax errors.
3984    (message-check 'valid-newsgroups
3985      (let ((case-fold-search t)
3986            (headers '("Newsgroups" "Followup-To"))
3987            header error)
3988        (while (and headers (not error))
3989          (when (setq header (mail-fetch-field (car headers)))
3990            (if (or
3991                 (not
3992                  (string-match
3993                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
3994                   header))
3995                 (memq
3996                  nil (mapcar
3997                       (lambda (g)
3998                         (not (string-match "\\.\\'\\|\\.\\." g)))
3999                       (message-tokenize-header header ","))))
4000                (setq error t)))
4001          (unless error
4002            (pop headers)))
4003        (if (not error)
4004            t
4005          (y-or-n-p
4006           (format "The %s header looks odd: \"%s\".  Really post? "
4007                   (car headers) header)))))
4008    (message-check 'repeated-newsgroups
4009      (let ((case-fold-search t)
4010            (headers '("Newsgroups" "Followup-To"))
4011            header error groups group)
4012        (while (and headers
4013                    (not error))
4014          (when (setq header (mail-fetch-field (pop headers)))
4015            (setq groups (message-tokenize-header header ","))
4016            (while (setq group (pop groups))
4017              (when (member group groups)
4018                (setq error group
4019                      groups nil)))))
4020        (if (not error)
4021            t
4022          (y-or-n-p
4023           (format "Group %s is repeated in headers.  Really post? " error)))))
4024    ;; Check the From header.
4025    (message-check 'from
4026      (let* ((case-fold-search t)
4027             (from (message-fetch-field "from"))
4028             ad)
4029        (cond
4030         ((not from)
4031          (message "There is no From line.  Posting is denied.")
4032          nil)
4033         ((or (not (string-match
4034                    "@[^\\.]*\\."
4035                    (setq ad (nth 1 (mail-extract-address-components
4036                                     from))))) ;larsi@ifi
4037              (string-match "\\.\\." ad) ;larsi@ifi..uio
4038              (string-match "@\\." ad)   ;larsi@.ifi.uio
4039              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4040              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4041              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
4042          (message
4043           "Denied posting -- the From looks strange: \"%s\"." from)
4044          nil)
4045         ((let ((addresses (rfc822-addresses from)))
4046            (while (and addresses
4047                        (not (eq (string-to-char (car addresses)) ?\()))
4048              (setq addresses (cdr addresses)))
4049            addresses)
4050          (message
4051           "Denied posting -- bad From address: \"%s\"." from)
4052          nil)
4053         (t t))))
4054    ;; Check the Reply-To header.
4055    (message-check 'reply-to
4056      (let* ((case-fold-search t)
4057             (reply-to (message-fetch-field "reply-to"))
4058             ad)
4059        (cond
4060         ((not reply-to)
4061          t)
4062         ((string-match "," reply-to)
4063          (y-or-n-p
4064           (format "Multiple Reply-To addresses: \"%s\". Really post? "
4065                   reply-to)))
4066         ((or (not (string-match
4067                    "@[^\\.]*\\."
4068                    (setq ad (nth 1 (mail-extract-address-components
4069                                     reply-to))))) ;larsi@ifi
4070              (string-match "\\.\\." ad) ;larsi@ifi..uio
4071              (string-match "@\\." ad)   ;larsi@.ifi.uio
4072              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4073              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4074              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
4075          (y-or-n-p
4076           (format
4077            "The Reply-To looks strange: \"%s\". Really post? "
4078            reply-to)))
4079         (t t))))))
4080
4081 (defun message-check-news-body-syntax ()
4082   (and
4083    ;; Check for long lines.
4084    (message-check 'long-lines
4085      (goto-char (point-min))
4086      (re-search-forward
4087       (concat "^" (regexp-quote mail-header-separator) "$"))
4088      (forward-line 1)
4089      (while (and
4090              (or (looking-at
4091                   mime-edit-tag-regexp)
4092                  (let ((p (point)))
4093                    (end-of-line)
4094                    (< (- (point) p) 80)))
4095              (zerop (forward-line 1))))
4096      (or (bolp)
4097          (eobp)
4098          (y-or-n-p
4099           "You have lines longer than 79 characters.  Really post? ")))
4100    ;; Check whether the article is empty.
4101    (message-check 'empty
4102      (goto-char (point-min))
4103      (re-search-forward
4104       (concat "^" (regexp-quote mail-header-separator) "$"))
4105      (forward-line 1)
4106      (let ((b (point)))
4107        (goto-char (point-max))
4108        (re-search-backward message-signature-separator nil t)
4109        (beginning-of-line)
4110        (or (re-search-backward "[^ \n\t]" b t)
4111            (if (message-gnksa-enable-p 'empty-article)
4112                (y-or-n-p "Empty article.  Really post? ")
4113              (message "Denied posting -- Empty article.")
4114              nil))))
4115    ;; Check for control characters.
4116    (message-check 'control-chars
4117      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
4118          (y-or-n-p
4119           "The article contains control characters.  Really post? ")
4120        t))
4121    ;; Check 8bit characters.
4122    (message-check '8bit
4123      (message-check-8bit))
4124    ;; Check excessive size.
4125    (message-check 'size
4126      (if (> (buffer-size) 60000)
4127          (y-or-n-p
4128           (format "The article is %d octets long.  Really post? "
4129                   (buffer-size)))
4130        t))
4131    ;; Check whether any new text has been added.
4132    (message-check 'new-text
4133      (or
4134       (not message-checksum)
4135       (not (eq (message-checksum) message-checksum))
4136       (if (message-gnksa-enable-p 'quoted-text-only)
4137           (y-or-n-p
4138            "It looks like no new text has been added.  Really post? ")
4139         (message "Denied posting -- no new text has been added.")
4140         nil)))
4141    ;; Check the length of the signature.
4142    (message-check 'signature
4143      (goto-char (point-max))
4144      (if (> (count-lines (point) (point-max)) 5)
4145          (y-or-n-p
4146           (format
4147            "Your .sig is %d lines; it should be max 4.  Really post? "
4148            (1- (count-lines (point) (point-max)))))
4149        t))
4150    ;; Ensure that text follows last quoted portion.
4151    (message-check 'quoting-style
4152      (goto-char (point-max))
4153      (let ((no-problem t))
4154        (when (search-backward-regexp "^>[^\n]*\n" nil t)
4155          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
4156        (if no-problem
4157            t
4158          (if (message-gnksa-enable-p 'quoted-text-only)
4159              (y-or-n-p "Your text should follow quoted text.  Really post? ")
4160            ;; Ensure that
4161            (goto-char (point-min))
4162            (re-search-forward
4163             (concat "^" (regexp-quote mail-header-separator) "$"))
4164            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
4165                (y-or-n-p "Your text should follow quoted text.  Really post? ")
4166              (message "Denied posting -- only quoted text.")
4167              nil)))))))
4168
4169 (defun message-check-mail-syntax ()
4170   "Check the syntax of the message."
4171   (save-excursion
4172     (save-restriction
4173       (widen)
4174       (and
4175        ;; We narrow to the headers and check them first.
4176        (save-excursion
4177          (save-restriction
4178            (message-narrow-to-headers)
4179            (message-check-mail-header-syntax)))
4180        ;; Check the body.
4181        (save-excursion
4182          (set-buffer message-edit-buffer)
4183          (message-check-mail-body-syntax))))))
4184
4185 (defun message-check-mail-header-syntax ()
4186   t)
4187
4188 (defun message-check-mail-body-syntax ()
4189   (and
4190    ;; Check 8bit characters.
4191    (message-check '8bit
4192      (message-check-8bit)
4193      )))
4194
4195 (defun message-check-8bit ()
4196   "Check the article contains 8bit characters."
4197   (save-excursion
4198     (set-buffer message-encoding-buffer)
4199     (message-narrow-to-headers)
4200     (let* ((case-fold-search t)
4201            (field-value (message-fetch-field "content-transfer-encoding")))
4202       (if (and field-value
4203                (member (downcase field-value) message-8bit-encoding-list))
4204           t
4205         (widen)
4206         (set-buffer (get-buffer-create " message syntax"))
4207         (erase-buffer)
4208         (goto-char (point-min))
4209         (set-buffer-multibyte nil)
4210         (insert-buffer-substring message-encoding-buffer)
4211         (goto-char (point-min))
4212         (if (re-search-forward "[^\x00-\x7f]" nil t)
4213             (y-or-n-p
4214              "The article contains 8bit characters.  Really post? ")
4215           t)))))
4216
4217 (defun message-checksum ()
4218   "Return a \"checksum\" for the current buffer."
4219   (let ((sum 0))
4220     (save-excursion
4221       (goto-char (point-min))
4222       (re-search-forward
4223        (concat "^" (regexp-quote mail-header-separator) "$"))
4224       (while (not (eobp))
4225         (when (not (looking-at "[ \t\n]"))
4226           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
4227                             (char-after))))
4228         (forward-char 1)))
4229     sum))
4230
4231 (defun message-do-fcc ()
4232   "Process Fcc headers in the current buffer."
4233   (let ((case-fold-search t)
4234         (coding-system-for-write 'raw-text)
4235         (output-coding-system 'raw-text)
4236         list file
4237         (mml-externalize-attachments message-fcc-externalize-attachments))
4238     (save-excursion
4239       (save-restriction
4240         (message-narrow-to-headers)
4241         (setq file (message-fetch-field "fcc" t)))
4242       (when file
4243         (set-buffer (get-buffer-create " *message temp*"))
4244         (erase-buffer)
4245         (insert-buffer-substring message-encoding-buffer)
4246         (save-restriction
4247           (message-narrow-to-headers)
4248           (while (setq file (message-fetch-field "fcc"))
4249             (push file list)
4250             (message-remove-header "fcc" nil t)))
4251         (goto-char (point-min))
4252         (when (re-search-forward
4253                (concat "^" (regexp-quote mail-header-separator) "$")
4254                nil t)
4255           (replace-match "" t t))
4256         ;; Process FCC operations.
4257         (while list
4258           (setq file (pop list))
4259           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
4260               ;; Pipe the article to the program in question.
4261               (call-process-region (point-min) (point-max) shell-file-name
4262                                    nil nil nil shell-command-switch
4263                                    (match-string 1 file))
4264             ;; Save the article.
4265             (setq file (expand-file-name file))
4266             (unless (file-exists-p (file-name-directory file))
4267               (make-directory (file-name-directory file) t))
4268             (if (and message-fcc-handler-function
4269                      (not (eq message-fcc-handler-function 'rmail-output)))
4270                 (funcall message-fcc-handler-function file)
4271               (if (and (file-readable-p file) (mail-file-babyl-p file))
4272                   (rmail-output file 1 nil t)
4273                 (let ((mail-use-rfc822 t))
4274                   (rmail-output file 1 t t))))))
4275         (kill-buffer (current-buffer))))))
4276
4277 (defun message-output (filename)
4278   "Append this article to Unix/babyl mail file FILENAME."
4279   (if (and (file-readable-p filename)
4280            (mail-file-babyl-p filename))
4281       (gnus-output-to-rmail filename t)
4282     (gnus-output-to-mail filename t)))
4283
4284 (defun message-cleanup-headers ()
4285   "Do various automatic cleanups of the headers."
4286   ;; Remove empty lines in the header.
4287   (save-restriction
4288     (message-narrow-to-headers)
4289     ;; Remove blank lines.
4290     (while (re-search-forward "^[ \t]*\n" nil t)
4291       (replace-match "" t t))
4292
4293     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
4294     ;; spaces to comma and eliminate spaces around commas.  Eliminate
4295     ;; embedded line breaks.
4296     (goto-char (point-min))
4297     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
4298       (save-restriction
4299         (narrow-to-region
4300          (point)
4301          (if (re-search-forward "^[^ \t]" nil t)
4302              (match-beginning 0)
4303            (forward-line 1)
4304            (point)))
4305         (goto-char (point-min))
4306         (while (re-search-forward "\n[ \t]+" nil t)
4307           (replace-match " " t t))      ;No line breaks (too confusing)
4308         (goto-char (point-min))
4309         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
4310           (replace-match "," t t))
4311         (goto-char (point-min))
4312         ;; Remove trailing commas.
4313         (when (re-search-forward ",+$" nil t)
4314           (replace-match "" t t))))))
4315
4316 (defun message-make-date (&optional now)
4317   "Make a valid data header.
4318 If NOW, use that time instead."
4319   (let* ((now (or now (current-time)))
4320          (zone (nth 8 (decode-time now)))
4321          (sign "+"))
4322     (when (< zone 0)
4323       (setq sign "-")
4324       (setq zone (- zone)))
4325     (concat
4326      ;; The day name of the %a spec is locale-specific.  Pfff.
4327      (format "%s, " (capitalize (car (rassoc (nth 6 (decode-time now))
4328                                              parse-time-weekdays))))
4329      (format-time-string "%d" now)
4330      ;; The month name of the %b spec is locale-specific.  Pfff.
4331      (format " %s "
4332              (capitalize (car (rassoc (nth 4 (decode-time now))
4333                                       parse-time-months))))
4334      (format-time-string "%Y %H:%M:%S " now)
4335      ;; We do all of this because XEmacs doesn't have the %z spec.
4336      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
4337
4338 (defun message-make-followup-subject (subject)
4339   "Make a followup Subject."
4340   (cond
4341    ((and (eq message-use-subject-re 'guess)
4342          (string-match message-subject-encoded-re-regexp subject))
4343     subject)
4344    (message-use-subject-re
4345     (concat "Re: " (message-strip-subject-re subject)))
4346    (t subject)))
4347
4348 (defun message-make-message-id ()
4349   "Make a unique Message-ID."
4350   (concat "<" (message-unique-id)
4351           (let ((psubject (save-excursion (message-fetch-field "subject")))
4352                 (psupersedes
4353                  (save-excursion (message-fetch-field "supersedes"))))
4354             (if (or
4355                  (and message-reply-headers
4356                       (mail-header-references message-reply-headers)
4357                       (mail-header-subject message-reply-headers)
4358                       psubject
4359                       (not (string=
4360                             (message-strip-subject-re
4361                              (mail-header-subject message-reply-headers))
4362                             (message-strip-subject-re psubject))))
4363                  (and psupersedes
4364                       (string-match "_-_@" psupersedes)))
4365                 "_-_" ""))
4366           "@" (message-make-fqdn) ">"))
4367
4368 (defvar message-unique-id-char nil)
4369
4370 ;; If you ever change this function, make sure the new version
4371 ;; cannot generate IDs that the old version could.
4372 ;; You might for example insert a "." somewhere (not next to another dot
4373 ;; or string boundary), or modify the "fsf" string.
4374 (defun message-unique-id ()
4375   ;; Don't use microseconds from (current-time), they may be unsupported.
4376   ;; Instead we use this randomly inited counter.
4377   (setq message-unique-id-char
4378         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
4379            ;; (current-time) returns 16-bit ints,
4380            ;; and 2^16*25 just fits into 4 digits i base 36.
4381            (* 25 25)))
4382   (let ((tm (current-time)))
4383     (concat
4384      (if (memq system-type '(ms-dos emx vax-vms))
4385          (let ((user (downcase (user-login-name))))
4386            (while (string-match "[^a-z0-9_]" user)
4387              (aset user (match-beginning 0) ?_))
4388            user)
4389        (message-number-base36 (user-uid) -1))
4390      (message-number-base36 (+ (car tm)
4391                                (lsh (% message-unique-id-char 25) 16)) 4)
4392      (message-number-base36 (+ (nth 1 tm)
4393                                (lsh (/ message-unique-id-char 25) 16)) 4)
4394      ;; Append the newsreader name, because while the generated
4395      ;; ID is unique to this newsreader, other newsreaders might
4396      ;; otherwise generate the same ID via another algorithm.
4397      ".fsf")))
4398
4399 (defun message-number-base36 (num len)
4400   (if (if (< len 0)
4401           (<= num 0)
4402         (= len 0))
4403       ""
4404     (concat (message-number-base36 (/ num 36) (1- len))
4405             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
4406                                   (% num 36))))))
4407
4408 (defun message-make-organization ()
4409   "Make an Organization header."
4410   (let* ((organization
4411           (when message-user-organization
4412             (if (message-functionp message-user-organization)
4413                 (funcall message-user-organization)
4414               message-user-organization))))
4415     (save-excursion
4416       (message-set-work-buffer)
4417       (cond ((stringp organization)
4418              (insert organization))
4419             ((and (eq t organization)
4420                   message-user-organization-file
4421                   (file-exists-p message-user-organization-file))
4422              (insert-file-contents message-user-organization-file)))
4423       (goto-char (point-min))
4424       (while (re-search-forward "[\t\n]+" nil t)
4425         (replace-match "" t t))
4426       (unless (zerop (buffer-size))
4427         (buffer-string)))))
4428
4429 (defun message-make-lines ()
4430   "Count the number of lines and return numeric string."
4431   (save-excursion
4432     (save-restriction
4433       (widen)
4434       (message-goto-body)
4435       (int-to-string (count-lines (point) (point-max))))))
4436
4437 (defun message-make-in-reply-to ()
4438   "Return the In-Reply-To header for this message."
4439   (when message-reply-headers
4440     (let ((from (mail-header-from message-reply-headers))
4441           (date (mail-header-date message-reply-headers))
4442           (msg-id (mail-header-message-id message-reply-headers)))
4443       (when msg-id
4444         (concat msg-id
4445                 (when from
4446                   (let ((pair (std11-extract-address-components from)))
4447                     (concat "\n ("
4448                             (or (car pair) (cadr pair))
4449                             "'s message of \""
4450                             (if (or (not date) (string= date ""))
4451                                 "(unknown date)" date)
4452                             "\")"))))))))
4453
4454 (defun message-make-distribution ()
4455   "Make a Distribution header."
4456   (let ((orig-distribution (message-fetch-reply-field "distribution")))
4457     (cond ((message-functionp message-distribution-function)
4458            (funcall message-distribution-function))
4459           (t orig-distribution))))
4460
4461 (defun message-make-expires ()
4462   "Return an Expires header based on `message-expires'."
4463   (let ((current (current-time))
4464         (future (* 1.0 message-expires 60 60 24)))
4465     ;; Add the future to current.
4466     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
4467     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
4468     (message-make-date current)))
4469
4470 (defun message-make-path ()
4471   "Return uucp path."
4472   (let ((login-name (user-login-name)))
4473     (cond ((null message-user-path)
4474            (concat (system-name) "!" login-name))
4475           ((stringp message-user-path)
4476            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
4477            (concat message-user-path "!" login-name))
4478           (t login-name))))
4479
4480 (defun message-make-from ()
4481   "Make a From header."
4482   (let* ((style message-from-style)
4483          (login (message-make-address))
4484          (fullname
4485           (or (and (boundp 'user-full-name)
4486                    user-full-name)
4487               (user-full-name))))
4488     (when (string= fullname "&")
4489       (setq fullname (user-login-name)))
4490     (save-excursion
4491       (message-set-work-buffer)
4492       (cond
4493        ((or (null style)
4494             (equal fullname ""))
4495         (insert login))
4496        ((or (eq style 'angles)
4497             (and (not (eq style 'parens))
4498                  ;; Use angles if no quoting is needed, or if parens would
4499                  ;; need quoting too.
4500                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
4501                      (let ((tmp (concat fullname nil)))
4502                        (while (string-match "([^()]*)" tmp)
4503                          (aset tmp (match-beginning 0) ?-)
4504                          (aset tmp (1- (match-end 0)) ?-))
4505                        (string-match "[\\()]" tmp)))))
4506         (insert fullname)
4507         (insert " <" login ">"))
4508        (t                               ; 'parens or default
4509         (insert login " (")
4510         (let ((fullname-start (point)))
4511           (insert fullname)
4512           (goto-char fullname-start)
4513           ;; RFC 822 says \ and nonmatching parentheses
4514           ;; must be escaped in comments.
4515           ;; Escape every instance of ()\ ...
4516           (while (re-search-forward "[()\\]" nil 1)
4517             (replace-match "\\\\\\&" t))
4518           ;; ... then undo escaping of matching parentheses,
4519           ;; including matching nested parentheses.
4520           (goto-char fullname-start)
4521           (while (re-search-forward
4522                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
4523                   nil 1)
4524             (replace-match "\\1(\\3)" t)
4525             (goto-char fullname-start)))
4526         (insert ")")))
4527       (buffer-string))))
4528
4529 (defun message-make-sender ()
4530   "Return the \"real\" user address.
4531 This function tries to ignore all user modifications, and
4532 give as trustworthy answer as possible."
4533   (concat (user-login-name) "@" (system-name)))
4534
4535 (defun message-make-address ()
4536   "Make the address of the user."
4537   (or (message-user-mail-address)
4538       (concat (user-login-name) "@" (message-make-domain))))
4539
4540 (defun message-user-mail-address ()
4541   "Return the pertinent part of `user-mail-address'."
4542   (when user-mail-address
4543     (if (string-match " " user-mail-address)
4544         (nth 1 (std11-extract-address-components user-mail-address))
4545       user-mail-address)))
4546
4547 (defun message-make-fqdn ()
4548   "Return user's fully qualified domain name."
4549   (let ((system-name (system-name))
4550         (user-mail (message-user-mail-address)))
4551     (cond
4552      ((and (string-match "[^.]\\.[^.]" system-name)
4553            (not (string-match message-bogus-system-names system-name)))
4554       ;; `system-name' returned the right result.
4555       system-name)
4556      ;; Try `mail-host-address'.
4557      ((and (boundp 'mail-host-address)
4558            (stringp mail-host-address)
4559            (string-match "\\." mail-host-address))
4560       mail-host-address)
4561      ;; We try `user-mail-address' as a backup.
4562      ((and user-mail
4563            (string-match "\\." user-mail)
4564            (string-match "@\\(.*\\)\\'" user-mail))
4565       (match-string 1 user-mail))
4566      ;; Default to this bogus thing.
4567      (t
4568       (concat system-name ".i-did-not-set--mail-host-address--so-tickle-me")))))
4569
4570 (defun message-make-host-name ()
4571   "Return the name of the host."
4572   (let ((fqdn (message-make-fqdn)))
4573     (string-match "^[^.]+\\." fqdn)
4574     (substring fqdn 0 (1- (match-end 0)))))
4575
4576 (defun message-make-domain ()
4577   "Return the domain name."
4578   (or mail-host-address
4579       (message-make-fqdn)))
4580
4581 (defun message-to-list-only ()
4582   (interactive)
4583   (let ((listaddr (message-make-mft t)))
4584     (when listaddr
4585       (save-excursion
4586         (message-remove-header "to")
4587         (message-remove-header "cc")
4588         (message-position-on-field "To" "X-Draft-From")
4589         (insert listaddr)))))
4590
4591 (defun message-make-mft (&optional only-show-subscribed)
4592   "Return the Mail-Followup-To header. If passed the optional
4593 argument `only-show-subscribed' only return the subscribed address (and
4594 not the additional To and Cc header contents)."
4595   (let* ((case-fold-search t)
4596          (to (message-fetch-field "To"))
4597          (cc (message-fetch-field "cc"))
4598          (msg-recipients (concat to (and to cc ", ") cc))
4599          (recipients
4600           (mapcar 'mail-strip-quoted-names
4601                   (message-tokenize-header msg-recipients)))
4602          (file-regexps
4603           (if message-subscribed-address-file
4604               (let (begin end item re)
4605                 (save-excursion
4606                   (with-temp-buffer
4607                     (insert-file-contents message-subscribed-address-file)
4608                     (while (not (eobp))
4609                       (setq begin (point))
4610                       (forward-line 1)
4611                       (setq end (point))
4612                       (if (bolp) (setq end (1- end)))
4613                       (setq item (regexp-quote (buffer-substring begin end)))
4614                       (if re (setq re (concat re "\\|" item))
4615                         (setq re (concat "\\`\\(" item))))
4616                     (and re (list (concat re "\\)\\'"))))))))
4617          (mft-regexps (apply 'append message-subscribed-regexps
4618                              (mapcar 'regexp-quote
4619                                      message-subscribed-addresses)
4620                              file-regexps
4621                              (mapcar 'funcall
4622                                      message-subscribed-address-functions))))
4623     (save-match-data
4624       (let ((subscribed-lists nil)
4625             (list
4626              (loop for recipient in recipients
4627                when (loop for regexp in mft-regexps
4628                       when (string-match regexp recipient) return t)
4629                return recipient)))
4630         (when list
4631           (if only-show-subscribed
4632               list
4633             msg-recipients))))))
4634
4635 ;; Dummy to avoid byte-compile warning.
4636 (defvar mule-version)
4637 (defvar emacs-beta-version)
4638 (defvar xemacs-codename)
4639 (defvar gnus-inviolable-extended-version)
4640
4641 (defun message-make-user-agent ()
4642   "Return user-agent info if the value `message-user-agent' is non-nil. If the
4643 \"User-Agent\" field has already exist, it's value will be added in the return
4644 string."
4645   (when message-user-agent
4646     (save-excursion
4647       (goto-char (point-min))
4648       (let ((case-fold-search t)
4649             user-agent start p end)
4650         (if (re-search-forward
4651              (concat "^User-Agent:[\t ]*\\("
4652                      (regexp-quote gnus-product-name)
4653                      "/[0-9.]+\\([ \t\r\n]*([^)]+)\\)*\\)?[\t ]*")
4654              nil t)
4655             (progn
4656               (setq start (match-beginning 0)
4657                     p (match-end 0)
4658                     end (std11-field-end)
4659                     user-agent (buffer-substring-no-properties p end))
4660               (delete-region start (1+ end))
4661               (concat message-user-agent " " user-agent))
4662           message-user-agent)))))
4663
4664 (defun message-generate-headers (headers)
4665   "Prepare article HEADERS.
4666 Headers already prepared in the buffer are not modified."
4667   (save-restriction
4668     (message-narrow-to-headers)
4669     (let* ((Date (message-make-date))
4670            (Message-ID (message-make-message-id))
4671            (Organization (message-make-organization))
4672            (From (message-make-from))
4673            (Path (message-make-path))
4674            (Subject nil)
4675            (Newsgroups nil)
4676            (In-Reply-To (message-make-in-reply-to))
4677            (To nil)
4678            (Distribution (message-make-distribution))
4679            (Lines (message-make-lines))
4680            (User-Agent (message-make-user-agent))
4681            (Expires (message-make-expires))
4682            (case-fold-search t)
4683            header value elem)
4684       ;; First we remove any old generated headers.
4685       (let ((headers message-deletable-headers))
4686         (unless (buffer-modified-p)
4687           (setq headers (delq 'Message-ID (copy-sequence headers))))
4688         (while headers
4689           (goto-char (point-min))
4690           (and (re-search-forward
4691                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4692                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
4693                (message-delete-line))
4694           (pop headers)))
4695       ;; Go through all the required headers and see if they are in the
4696       ;; articles already.  If they are not, or are empty, they are
4697       ;; inserted automatically - except for Subject, Newsgroups and
4698       ;; Distribution.
4699       (while headers
4700         (goto-char (point-min))
4701         (setq elem (pop headers))
4702         (if (consp elem)
4703             (if (eq (car elem) 'optional)
4704                 (setq header (cdr elem))
4705               (setq header (car elem)))
4706           (setq header elem))
4707         (when (or (not (re-search-forward
4708                         (concat "^"
4709                                 (regexp-quote
4710                                  (downcase
4711                                   (if (stringp header)
4712                                       header
4713                                     (symbol-name header))))
4714                                 ":")
4715                         nil t))
4716                   (progn
4717                     ;; The header was found.  We insert a space after the
4718                     ;; colon, if there is none.
4719                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
4720                     ;; Find out whether the header is empty...
4721                     (looking-at "[ \t]*\n[^ \t]")))
4722           ;; So we find out what value we should insert.
4723           (setq value
4724                 (cond
4725                  ((and (consp elem) (eq (car elem) 'optional))
4726                   ;; This is an optional header.  If the cdr of this
4727                   ;; is something that is nil, then we do not insert
4728                   ;; this header.
4729                   (setq header (cdr elem))
4730                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
4731                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
4732                  ((consp elem)
4733                   ;; The element is a cons.  Either the cdr is a
4734                   ;; string to be inserted verbatim, or it is a
4735                   ;; function, and we insert the value returned from
4736                   ;; this function.
4737                   (or (and (stringp (cdr elem)) (cdr elem))
4738                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
4739                  ((and (boundp header) (symbol-value header))
4740                   ;; The element is a symbol.  We insert the value
4741                   ;; of this symbol, if any.
4742                   (symbol-value header))
4743                  ((not (message-check-element header))
4744                   ;; We couldn't generate a value for this header,
4745                   ;; so we just ask the user.
4746                   (read-from-minibuffer
4747                    (format "Empty header for %s; enter value: " header)))))
4748           ;; Finally insert the header.
4749           (when (and value
4750                      (not (equal value "")))
4751             (save-excursion
4752               (if (bolp)
4753                   (progn
4754                     ;; This header didn't exist, so we insert it.
4755                     (goto-char (point-max))
4756                     (insert (if (stringp header) header (symbol-name header))
4757                             ": " value)
4758                     ;; We check whether the value was ended by a
4759                     ;; newline.  If now, we insert one.
4760                     (unless (bolp)
4761                       (insert "\n"))
4762                     (forward-line -1))
4763                 ;; The value of this header was empty, so we clear
4764                 ;; totally and insert the new value.
4765                 (delete-region (point) (gnus-point-at-eol))
4766                 (insert value)
4767                 (when (bolp)
4768                   (delete-char -1)))
4769               ;; Add the deletable property to the headers that require it.
4770               (and (memq header message-deletable-headers)
4771                    (progn (beginning-of-line) (looking-at "[^:]+: "))
4772                    (add-text-properties
4773                     (point) (match-end 0)
4774                     '(message-deletable t face italic) (current-buffer)))))))
4775       ;; Insert new Sender if the From is strange.
4776       (let ((from (message-fetch-field "from"))
4777             (sender (message-fetch-field "sender"))
4778             (secure-sender (message-make-sender)))
4779         (when (and from
4780                    (not (message-check-element 'sender))
4781                    (not (string=
4782                          (downcase
4783                           (cadr (std11-extract-address-components from)))
4784                          (downcase secure-sender)))
4785                    (or (null sender)
4786                        (not
4787                         (string=
4788                          (downcase
4789                           (cadr (std11-extract-address-components sender)))
4790                          (downcase secure-sender)))))
4791           (goto-char (point-min))
4792           ;; Rename any old Sender headers to Original-Sender.
4793           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
4794             (beginning-of-line)
4795             (insert "Original-")
4796             (beginning-of-line))
4797           (when (or (message-news-p)
4798                     (string-match "@.+\\.." secure-sender))
4799             (insert "Sender: " secure-sender "\n")))))))
4800
4801 (defun message-insert-courtesy-copy ()
4802   "Insert a courtesy message in mail copies of combined messages."
4803   (let (newsgroups)
4804     (save-excursion
4805       (save-restriction
4806         (message-narrow-to-headers)
4807         (when (setq newsgroups (message-fetch-field "newsgroups"))
4808           (goto-char (point-max))
4809           (insert "Posted-To: " newsgroups "\n")))
4810       (forward-line 1)
4811       (when message-courtesy-message
4812         (cond
4813          ((string-match "%s" message-courtesy-message)
4814           (insert (format message-courtesy-message newsgroups)))
4815          (t
4816           (insert message-courtesy-message)))))))
4817
4818 ;;;
4819 ;;; Setting up a message buffer
4820 ;;;
4821
4822 (defun message-fill-address (header value)
4823   (save-restriction
4824     (narrow-to-region (point) (point))
4825     (insert (capitalize (symbol-name header))
4826             ": "
4827             (if (consp value) (car value) value)
4828             "\n")
4829     (narrow-to-region (point-min) (1- (point-max)))
4830     (let (quoted last)
4831       (goto-char (point-min))
4832       (while (not (eobp))
4833         (skip-chars-forward "^,\"" (point-max))
4834         (if (or (eq (char-after) ?,)
4835                 (eobp))
4836             (when (not quoted)
4837               (if (and (> (current-column) 78)
4838                        last)
4839                   (save-excursion
4840                     (goto-char last)
4841                     (looking-at "[ \t]*")
4842                     (replace-match "\n " t t)))
4843               (setq last (1+ (point))))
4844           (setq quoted (not quoted)))
4845         (unless (eobp)
4846           (forward-char 1))))
4847     (goto-char (point-max))
4848     (widen)
4849     (forward-line 1)))
4850
4851 (defun message-fill-references (header value)
4852   (insert (capitalize (symbol-name header))
4853           ": "
4854           (std11-fill-msg-id-list-string
4855            (if (consp value) (car value) value))
4856           "\n"))
4857
4858 (defun message-fill-header (header value)
4859   (let ((begin (point))
4860         (fill-column 78)
4861         (fill-prefix " "))
4862     (insert (capitalize (symbol-name header))
4863             ": "
4864             (if (consp value) (car value) value)
4865             "\n")
4866     (save-restriction
4867       (narrow-to-region begin (point))
4868       (fill-region-as-paragraph begin (point))
4869       ;; Tapdance around looong Message-IDs.
4870       (forward-line -1)
4871       (when (looking-at "[ \t]*$")
4872         (message-delete-line))
4873       (goto-char begin)
4874       (re-search-forward ":" nil t)
4875       (when (looking-at "\n[ \t]+")
4876         (replace-match " " t t))
4877       (goto-char (point-max)))))
4878
4879 (defun message-shorten-1 (list cut surplus)
4880   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
4881   (setcdr (nthcdr (- cut 2) list)
4882           (nthcdr (+ (- cut 2) surplus 1) list)))
4883
4884 (defun message-shorten-references (header references)
4885   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
4886 If folding is disallowed, also check that the REFERENCES are less
4887 than 988 characters long, and if they are not, trim them until they are."
4888   (let ((maxcount 21)
4889         (count 0)
4890         (cut 2)
4891         refs)
4892     (with-temp-buffer
4893       (insert references)
4894       (goto-char (point-min))
4895       ;; Cons a list of valid references.
4896       (while (re-search-forward "<[^>]+>" nil t)
4897         (push (match-string 0) refs))
4898       (setq refs (nreverse refs)
4899             count (length refs)))
4900
4901     ;; If the list has more than MAXCOUNT elements, trim it by
4902     ;; removing the CUTth element and the required number of
4903     ;; elements that follow.
4904     (when (> count maxcount)
4905       (let ((surplus (- count maxcount)))
4906         (message-shorten-1 refs cut surplus)
4907         (decf count surplus)))
4908
4909     ;; If folding is disallowed, make sure the total length (including
4910     ;; the spaces between) will be less than MAXSIZE characters.
4911     ;;
4912     ;; Only disallow folding for News messages. At this point the headers
4913     ;; have not been generated, thus we use message-this-is-news directly.
4914     (when (and message-this-is-news message-cater-to-broken-inn)
4915       (let ((maxsize 988)
4916             (totalsize (+ (apply #'+ (mapcar #'length refs))
4917                           (1- count)))
4918             (surplus 0)
4919             (ptr (nthcdr (1- cut) refs)))
4920         ;; Decide how many elements to cut off...
4921         (while (> totalsize maxsize)
4922           (decf totalsize (1+ (length (car ptr))))
4923           (incf surplus)
4924           (setq ptr (cdr ptr)))
4925         ;; ...and do it.
4926         (when (> surplus 0)
4927           (message-shorten-1 refs cut surplus))))
4928
4929     ;; Finally, collect the references back into a string and insert
4930     ;; it into the buffer.
4931     (let ((refstring (mapconcat #'identity refs " ")))
4932       (if (and message-this-is-news message-cater-to-broken-inn)
4933           (insert (capitalize (symbol-name header)) ": "
4934                   refstring "\n")
4935         (message-fill-header header refstring)))))
4936
4937 (defun message-position-point ()
4938   "Move point to where the user probably wants to find it."
4939   (message-narrow-to-headers)
4940   (cond
4941    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
4942     (search-backward ":" )
4943     (widen)
4944     (forward-char 1)
4945     (if (eq (char-after) ? )
4946         (forward-char 1)
4947       (insert " ")))
4948    (t
4949     (goto-char (point-max))
4950     (widen)
4951     (forward-line 1)
4952     (unless (looking-at "$")
4953       (forward-line 2)))
4954    (sit-for 0)))
4955
4956 (defun message-beginning-of-line (&optional n)
4957   "Move point to beginning of header value or to beginning of line."
4958   (interactive "p")
4959   (let ((zrs 'zmacs-region-stays))
4960     (when (and (interactive-p) (boundp zrs))
4961       (set zrs t)))
4962   (if (message-point-in-header-p)
4963       (let* ((here (point))
4964              (bol (progn (beginning-of-line n) (point)))
4965              (eol (gnus-point-at-eol))
4966              (eoh (re-search-forward ": *" eol t)))
4967         (if (or (not eoh) (equal here eoh))
4968             (goto-char bol)
4969           (goto-char eoh)))
4970     (beginning-of-line n)))
4971
4972 (defun message-buffer-name (type &optional to group)
4973   "Return a new (unique) buffer name based on TYPE and TO."
4974   (cond
4975    ;; Generate a new buffer name The Message Way.
4976    ((eq message-generate-new-buffers 'unique)
4977     (generate-new-buffer-name
4978      (concat "*" type
4979              (if to
4980                  (concat " to "
4981                          (or (car (std11-extract-address-components to))
4982                              to) "")
4983                "")
4984              (if (and group (not (string= group ""))) (concat " on " group) "")
4985              "*")))
4986    ;; Check whether `message-generate-new-buffers' is a function,
4987    ;; and if so, call it.
4988    ((message-functionp message-generate-new-buffers)
4989     (funcall message-generate-new-buffers type to group))
4990    ((eq message-generate-new-buffers 'unsent)
4991     (generate-new-buffer-name
4992      (concat "*unsent " type
4993              (if to
4994                  (concat " to "
4995                          (or (car (mail-extract-address-components to))
4996                              to) "")
4997                "")
4998              (if (and group (not (string= group ""))) (concat " on " group) "")
4999              "*")))
5000    ;; Use standard name.
5001    (t
5002     (format "*%s message*" type))))
5003
5004 (defmacro message-pop-to-buffer-1 (buffer)
5005   `(if pop-up-frames
5006        (let (special-display-buffer-names
5007              special-display-regexps
5008              same-window-buffer-names
5009              same-window-regexps)
5010          (pop-to-buffer ,buffer))
5011      (pop-to-buffer ,buffer)))
5012
5013 (defun message-pop-to-buffer (name)
5014   "Pop to buffer NAME, and warn if it already exists and is modified."
5015   (let ((buffer (get-buffer name))
5016         (pop-up-frames (and (or (static-if (featurep 'xemacs)
5017                                     (device-on-window-system-p)
5018                                   window-system)
5019                                 (>= emacs-major-version 20))
5020                             message-use-multi-frames)))
5021     (if (and buffer
5022              (buffer-name buffer))
5023         (progn
5024           (message-pop-to-buffer-1 buffer)
5025           (when (and (buffer-modified-p)
5026                      (not (y-or-n-p
5027                            "Message already being composed; erase? ")))
5028             (error "Message being composed")))
5029       (message-pop-to-buffer-1 name))
5030     (erase-buffer)
5031     (message-mode)
5032     (when pop-up-frames
5033       (set (make-local-variable 'message-original-frame) (selected-frame)))))
5034
5035 (defun message-do-send-housekeeping ()
5036   "Kill old message buffers."
5037   ;; We might have sent this buffer already.  Delete it from the
5038   ;; list of buffers.
5039   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
5040   (while (and message-max-buffers
5041               message-buffer-list
5042               (>= (length message-buffer-list) message-max-buffers))
5043     ;; Kill the oldest buffer -- unless it has been changed.
5044     (let ((buffer (pop message-buffer-list)))
5045       (when (and (buffer-name buffer)
5046                  (not (buffer-modified-p buffer)))
5047         (kill-buffer buffer))))
5048   ;; Rename the buffer.
5049   (if message-send-rename-function
5050       (funcall message-send-rename-function)
5051     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
5052     (when (string-match
5053            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
5054            (buffer-name))
5055       (let ((name (match-string 2 (buffer-name)))
5056             to group)
5057         (if (not (or (null name)
5058                      (string-equal name "mail")
5059                      (string-equal name "posting")))
5060             (setq name (concat "*sent " name "*"))
5061           (message-narrow-to-headers)
5062           (setq to (message-fetch-field "to"))
5063           (setq group (message-fetch-field "newsgroups"))
5064           (widen)
5065           (setq name
5066                 (cond
5067                  (to (concat "*sent mail to "
5068                              (or (car (mail-extract-address-components to))
5069                                  to) "*"))
5070                  ((and group (not (string= group "")))
5071                   (concat "*sent posting on " group "*"))
5072                  (t "*sent mail*"))))
5073         (unless (string-equal name (buffer-name))
5074           (rename-buffer name t)))))
5075   ;; Push the current buffer onto the list.
5076   (when message-max-buffers
5077     (setq message-buffer-list
5078           (nconc message-buffer-list (list (current-buffer))))))
5079
5080 (defun message-mail-user-agent ()
5081   (let ((mua (cond
5082               ((not message-mail-user-agent) nil)
5083               ((eq message-mail-user-agent t) mail-user-agent)
5084               (t message-mail-user-agent))))
5085     (if (memq mua '(message-user-agent gnus-user-agent))
5086         nil
5087       mua)))
5088
5089 (defun message-setup (headers &optional replybuffer actions switch-function)
5090   (let ((mua (message-mail-user-agent))
5091         subject to field yank-action)
5092     (if (not (and message-this-is-mail mua))
5093         (message-setup-1 headers replybuffer actions)
5094       (if replybuffer
5095           (setq yank-action (list 'insert-buffer replybuffer)))
5096       (setq headers (copy-sequence headers))
5097       (setq field (assq 'Subject headers))
5098       (when field
5099         (setq subject (cdr field))
5100         (setq headers (delq field headers)))
5101       (setq field (assq 'To headers))
5102       (when field
5103         (setq to (cdr field))
5104         (setq headers (delq field headers)))
5105       (let ((mail-user-agent mua))
5106         (compose-mail to subject
5107                       (mapcar (lambda (item)
5108                                 (cons
5109                                  (format "%s" (car item))
5110                                  (cdr item)))
5111                               headers)
5112                       nil switch-function yank-action actions)))))
5113
5114 (defun message-setup-1 (headers &optional replybuffer actions)
5115   (dolist (action actions)
5116     (condition-case nil
5117         (add-to-list 'message-send-actions
5118                      `(apply ',(car action) ',(cdr action)))))
5119   (setq message-reply-buffer
5120         (or (message-get-parameter 'reply-buffer)
5121             replybuffer))
5122   (goto-char (point-min))
5123   ;; Insert all the headers.
5124   (mail-header-format
5125    (let ((h headers)
5126          (alist message-header-format-alist))
5127      (while h
5128        (unless (assq (caar h) message-header-format-alist)
5129          (push (list (caar h)) alist))
5130        (pop h))
5131      alist)
5132    headers)
5133   (delete-region (point) (progn (forward-line -1) (point)))
5134   (when message-default-headers
5135     (insert message-default-headers)
5136     (or (bolp) (insert ?\n)))
5137   (put-text-property
5138    (point)
5139    (progn
5140      (insert mail-header-separator "\n")
5141      (1- (point)))
5142    'read-only nil)
5143   (forward-line -1)
5144   (when (message-news-p)
5145     (when message-default-news-headers
5146       (insert message-default-news-headers)
5147       (or (bolp) (insert ?\n)))
5148     (when message-generate-headers-first
5149       (message-generate-headers
5150        (delq 'Lines
5151              (delq 'Subject
5152                    (copy-sequence message-required-news-headers))))))
5153   (when (message-mail-p)
5154     (when message-default-mail-headers
5155       (insert message-default-mail-headers)
5156       (or (bolp) (insert ?\n)))
5157     (when message-generate-headers-first
5158       (message-generate-headers
5159        (delq 'Lines
5160              (delq 'Subject
5161                    (copy-sequence message-required-mail-headers))))))
5162   (run-hooks 'message-signature-setup-hook)
5163   (message-insert-signature)
5164   (save-restriction
5165     (message-narrow-to-headers)
5166     (if message-alternative-emails
5167         (message-use-alternative-email-as-from))
5168     (run-hooks 'message-header-setup-hook))
5169   (set-buffer-modified-p nil)
5170   (setq buffer-undo-list nil)
5171   (run-hooks 'message-setup-hook)
5172   (message-position-point)
5173   (undo-boundary))
5174
5175 (defun message-set-auto-save-file-name ()
5176   "Associate the message buffer with a file in the drafts directory."
5177   (when message-auto-save-directory
5178     (unless (file-directory-p
5179              (directory-file-name message-auto-save-directory))
5180       (gnus-make-directory message-auto-save-directory))
5181     (if (gnus-alive-p)
5182         (setq message-draft-article
5183               (nndraft-request-associate-buffer "drafts"))
5184       (setq buffer-file-name (expand-file-name
5185                               (if (memq system-type
5186                                         '(ms-dos ms-windows windows-nt
5187                                                  cygwin32 win32 w32
5188                                                  mswindows))
5189                                   "message"
5190                                 "*message*")
5191                               message-auto-save-directory))
5192       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
5193     (clear-visited-file-modtime)
5194     (static-if (boundp 'MULE)
5195         (set-file-coding-system message-draft-coding-system)
5196       (setq buffer-file-coding-system message-draft-coding-system))))
5197
5198 (defun message-disassociate-draft ()
5199   "Disassociate the message buffer from the drafts directory."
5200   (when message-draft-article
5201     (nndraft-request-expire-articles
5202      (list message-draft-article) "drafts" nil t)))
5203
5204 (defun message-insert-headers ()
5205   "Generate the headers for the article."
5206   (interactive)
5207   (save-excursion
5208     (save-restriction
5209       (message-narrow-to-headers)
5210       (when (message-news-p)
5211         (message-generate-headers
5212          (delq 'Lines
5213                (delq 'Subject
5214                      (copy-sequence message-required-news-headers)))))
5215       (when (message-mail-p)
5216         (message-generate-headers
5217          (delq 'Lines
5218                (delq 'Subject
5219                      (copy-sequence message-required-mail-headers))))))))
5220
5221 \f
5222
5223 ;;;
5224 ;;; Commands for interfacing with message
5225 ;;;
5226
5227 ;;;###autoload
5228 (defun message-mail (&optional to subject
5229                                other-headers continue switch-function
5230                                yank-action send-actions)
5231   "Start editing a mail message to be sent.
5232 OTHER-HEADERS is an alist of header/value pairs."
5233   (interactive)
5234   (let ((message-this-is-mail t) replybuffer)
5235     (unless (message-mail-user-agent)
5236       (message-pop-to-buffer (message-buffer-name "mail" to)))
5237     ;; FIXME: message-mail should do something if YANK-ACTION is not
5238     ;; insert-buffer.
5239     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
5240          (setq replybuffer (nth 1 yank-action)))
5241     (message-setup
5242      (nconc
5243       `((To . ,(or to "")) (Subject . ,(or subject "")))
5244       (when other-headers other-headers))
5245      replybuffer send-actions)
5246     ;; FIXME: Should return nil if failure.
5247     t))
5248
5249 ;;;###autoload
5250 (defun message-news (&optional newsgroups subject)
5251   "Start editing a news article to be sent."
5252   (interactive)
5253   (let ((message-this-is-news t))
5254     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
5255     (message-setup `((Newsgroups . ,(or newsgroups ""))
5256                      (Subject . ,(or subject ""))))))
5257
5258 (defun message-get-reply-headers (wide &optional to-address)
5259   (let (follow-to mct never-mct to cc author mft recipients)
5260     ;; Find all relevant headers we need.
5261     (let ((mrt (when message-use-mail-reply-to
5262                  (message-fetch-field "mail-reply-to")))
5263           (reply-to (message-fetch-field "reply-to")))
5264       (setq to (message-fetch-field "to")
5265             cc (message-fetch-field "cc")
5266             mct (when message-use-mail-copies-to
5267                   (message-fetch-field "mail-copies-to"))
5268             author (or mrt
5269                        reply-to
5270                        (message-fetch-field "from")
5271                        "")
5272             mft (when (and (not (or to-address mrt reply-to))
5273                            message-use-mail-followup-to)
5274                   (message-fetch-field "mail-followup-to"))))
5275
5276     (save-match-data
5277       ;; Handle special values of Mail-Copies-To.
5278       (when mct
5279         (cond ((or (equal (downcase mct) "never")
5280                    (equal (downcase mct) "nobody"))
5281                (when (or (not (eq message-use-mail-copies-to 'ask))
5282                          (message-y-or-n-p
5283                           (concat "Obey Mail-Copies-To: never? ") t "\
5284 You should normally obey the Mail-Copies-To: header.
5285
5286         `Mail-Copies-To: " mct "'
5287 directs you not to send your response to the author."))
5288                  (setq never-mct t))
5289                (setq mct nil))
5290               ((or (equal (downcase mct) "always")
5291                    (equal (downcase mct) "poster"))
5292                (if (or (not (eq message-use-mail-copies-to 'ask))
5293                        (message-y-or-n-p
5294                         (concat "Obey Mail-Copies-To: always? ") t "\
5295 You should normally obey the Mail-Copies-To: header.
5296
5297         `Mail-Copies-To: " mct "'
5298 sends a copy of your response to the author."))
5299                    (setq mct author)
5300                  (setq mct nil)))
5301               ((and (eq message-use-mail-copies-to 'ask)
5302                     (not (message-y-or-n-p
5303                           (concat "Obey Mail-Copies-To: " mct " ? ") t "\
5304 You should normally obey the Mail-Copies-To: header.
5305
5306         `Mail-Copies-To: " mct "'
5307 sends a copy of your response to " (if (string-match "," mct)
5308                                        "the specified addresses"
5309                                      "that address") ".")))
5310                (setq mct nil))))
5311
5312       ;; Build (textual) list of new recipient addresses.
5313       (cond
5314        ((not wide)
5315         (setq recipients (concat ", " author)))
5316        ((and mft
5317              (string-match "[^ \t,]" mft)
5318              (or (not (eq message-use-mail-followup-to 'ask))
5319                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
5320 You should normally obey the Mail-Followup-To: header.  In this
5321 article, it has the value of
5322
5323 " mft "
5324
5325 which directs your response to " (if (string-match "," mft)
5326                                      "the specified addresses"
5327                                    "that address only") ".
5328
5329 Most commonly, Mail-Followup-To is used by a mailing list poster to
5330 express that responses should be sent to just the list, and not the
5331 poster as well.
5332
5333 If a message is posted to several mailing lists, Mail-Followup-To may
5334 also be used to direct the following discussion to one list only,
5335 because discussions that are spread over several lists tend to be
5336 fragmented and very difficult to follow.
5337
5338 Also, some source/announcement lists are not intended for discussion;
5339 responses here are directed to other addresses.")))
5340         (setq recipients (concat ", " mft)))
5341        (to-address
5342         (setq recipients (concat ", " to-address))
5343         ;; If the author explicitly asked for a copy, we don't deny it to them.
5344         (if mct (setq recipients (concat recipients ", " mct))))
5345        (t
5346         (setq recipients (if never-mct "" (concat ", " author)))
5347         (if to  (setq recipients (concat recipients ", " to)))
5348         (if cc  (setq recipients (concat recipients ", " cc)))
5349         (if mct (setq recipients (concat recipients ", " mct)))))
5350       (if (>= (length recipients) 2)
5351           ;; Strip the leading ", ".
5352           (setq recipients (substring recipients 2)))
5353       ;; Squeeze whitespace.
5354       (while (string-match "[ \t][ \t]+" recipients)
5355         (setq recipients (replace-match " " t t recipients)))
5356       ;; Remove addresses that match `rmail-dont-reply-to-names'.
5357       (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
5358         (setq recipients (rmail-dont-reply-to recipients)))
5359       ;; Perhaps "Mail-Copies-To: never" removed the only address?
5360       (if (string-equal recipients "")
5361           (setq recipients author))
5362       ;; Convert string to a list of (("foo@bar" . "Name <Foo@BAR>") ...).
5363       (setq recipients
5364             (mapcar
5365              (lambda (addr)
5366                (cons (downcase (mail-strip-quoted-names addr)) addr))
5367              (message-tokenize-header recipients)))
5368       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
5369       (let ((s recipients))
5370         (while s
5371           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
5372
5373       ;; Remove hierarchical lists that are contained within each other,
5374       ;; if message-hierarchical-addresses is defined.
5375       (when message-hierarchical-addresses
5376         (let ((plain-addrs (mapcar 'car recipients))
5377               subaddrs recip)
5378           (while plain-addrs
5379             (setq subaddrs (assoc (car plain-addrs)
5380                                   message-hierarchical-addresses)
5381                   plain-addrs (cdr plain-addrs))
5382             (when subaddrs
5383               (setq subaddrs (cdr subaddrs))
5384               (while subaddrs
5385                 (setq recip (assoc (car subaddrs) recipients)
5386                       subaddrs (cdr subaddrs))
5387                 (if recip
5388                     (setq recipients (delq recip recipients))))))))
5389
5390       ;; Build the header alist.  Allow the user to be asked whether
5391       ;; or not to reply to all recipients in a wide reply.
5392       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
5393       (when (and recipients
5394                  (or (not message-wide-reply-confirm-recipients)
5395                      (y-or-n-p "Reply to all recipients? ")))
5396         (setq recipients (mapconcat
5397                           (lambda (addr) (cdr addr)) recipients ", "))
5398         (if (string-match "^ +" recipients)
5399             (setq recipients (substring recipients (match-end 0))))
5400         (push (cons 'Cc recipients) follow-to)))
5401     follow-to))
5402
5403 ;;;###autoload
5404 (defun message-reply (&optional to-address wide)
5405   "Start editing a reply to the article in the current buffer."
5406   (interactive)
5407   (require 'gnus-sum)                   ; for gnus-list-identifiers
5408   (let ((cur (current-buffer))
5409         from subject date
5410         references message-id follow-to
5411         (inhibit-point-motion-hooks t)
5412         (message-this-is-mail t)
5413         gnus-warning in-reply-to)
5414     (save-restriction
5415       (message-narrow-to-head-1)
5416       ;; Allow customizations to have their say.
5417       (if (not wide)
5418           ;; This is a regular reply.
5419           (when (message-functionp message-reply-to-function)
5420             (save-excursion
5421               (setq follow-to (funcall message-reply-to-function))))
5422         ;; This is a followup.
5423         (when (message-functionp message-wide-reply-to-function)
5424           (save-excursion
5425             (setq follow-to
5426                   (funcall message-wide-reply-to-function)))))
5427       (setq message-id (message-fetch-field "message-id" t)
5428             references (message-fetch-field "references")
5429             date (message-fetch-field "date")
5430             from (message-fetch-field "from")
5431             subject (or (message-fetch-field "subject") "none"))
5432       (when gnus-list-identifiers
5433         (setq subject (message-strip-list-identifiers subject)))
5434       (setq subject (message-make-followup-subject subject))
5435
5436       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
5437                  (string-match "<[^>]+>" gnus-warning))
5438         (setq message-id (match-string 0 gnus-warning)))
5439
5440       (unless follow-to
5441         (setq follow-to (message-get-reply-headers wide to-address)))
5442
5443       ;; Get the references from "In-Reply-To" field if there were
5444       ;; no references and "In-Reply-To" field looks promising.
5445       (unless references
5446         (when (and (setq in-reply-to (message-fetch-field "in-reply-to"))
5447                    (string-match "<[^>]+>" in-reply-to))
5448           (setq references (match-string 0 in-reply-to)))))
5449
5450     (unless (message-mail-user-agent)
5451       (message-pop-to-buffer
5452        (message-buffer-name
5453         (if wide "wide reply" "reply") from
5454         (if wide to-address nil))))
5455
5456     (setq message-reply-headers
5457           (make-full-mail-header-from-decoded-header
5458            0 subject from date message-id references 0 0 ""))
5459
5460     (message-setup
5461      `((Subject . ,subject)
5462        ,@follow-to
5463        ,@(if (or references message-id)
5464              `((References . ,(concat (or references "") (and references " ")
5465                                       (or message-id ""))))
5466            nil))
5467      cur)))
5468
5469 ;;;###autoload
5470 (defun message-wide-reply (&optional to-address)
5471   "Make a \"wide\" reply to the message in the current buffer."
5472   (interactive)
5473   (message-reply to-address t))
5474
5475 ;;;###autoload
5476 (defun message-followup (&optional to-newsgroups)
5477   "Follow up to the message in the current buffer.
5478 If TO-NEWSGROUPS, use that as the new Newsgroups line."
5479   (interactive)
5480   (require 'gnus-sum)                   ; for gnus-list-identifiers
5481   (let ((cur (current-buffer))
5482         from subject date reply-to mrt mct mft
5483         references message-id follow-to
5484         (inhibit-point-motion-hooks t)
5485         (message-this-is-news t)
5486         followup-to distribution newsgroups gnus-warning posted-to)
5487     (save-restriction
5488       (message-narrow-to-head)
5489       (when (message-functionp message-followup-to-function)
5490         (setq follow-to
5491               (funcall message-followup-to-function)))
5492       (setq from (message-fetch-field "from")
5493             date (message-fetch-field "date")
5494             subject (or (message-fetch-field "subject") "none")
5495             references (message-fetch-field "references")
5496             message-id (message-fetch-field "message-id" t)
5497             followup-to (message-fetch-field "followup-to")
5498             newsgroups (message-fetch-field "newsgroups")
5499             posted-to (message-fetch-field "posted-to")
5500             reply-to (message-fetch-field "reply-to")
5501             mrt (when message-use-mail-reply-to
5502                   (message-fetch-field "mail-reply-to"))
5503             distribution (message-fetch-field "distribution")
5504             mct (when message-use-mail-copies-to
5505                   (message-fetch-field "mail-copies-to"))
5506             mft (when message-use-mail-followup-to
5507                   (message-fetch-field "mail-followup-to")))
5508       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
5509                  (string-match "<[^>]+>" gnus-warning))
5510         (setq message-id (match-string 0 gnus-warning)))
5511       ;; Remove bogus distribution.
5512       (when (and (stringp distribution)
5513                  (let ((case-fold-search t))
5514                    (string-match "world" distribution)))
5515         (setq distribution nil))
5516       (if gnus-list-identifiers
5517           (setq subject (message-strip-list-identifiers subject)))
5518       (setq subject (message-make-followup-subject subject))
5519       (widen))
5520
5521     ;; Handle special values of Mail-Copies-To.
5522     (when mct
5523       (cond
5524        ((and (or (equal (downcase mct) "never")
5525                  (equal (downcase mct) "nobody")))
5526         (setq mct nil))
5527        ((and (or (equal (downcase mct) "always")
5528                  (equal (downcase mct) "poster")))
5529         (if (or (not (eq message-use-mail-copies-to 'ask))
5530                 (message-y-or-n-p
5531                  (concat "Obey Mail-Copies-To: always? ") t "\
5532 You should normally obey the Mail-Copies-To: header.
5533
5534         `Mail-Copies-To: " mct "'
5535 sends a copy of your response to the author."))
5536             (setq mct (or mrt reply-to from))
5537           (setq mct nil)))
5538        ((and (eq message-use-mail-copies-to 'ask)
5539              (not
5540               (message-y-or-n-p
5541                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
5542 You should normally obey the Mail-Copies-To: header.
5543
5544         `Mail-Copies-To: " mct "'
5545 sends a copy of your response to " (if (string-match "," mct)
5546                                        "the specified addresses"
5547                                      "that address") ".")))
5548         (setq mct nil))))
5549
5550     (unless follow-to
5551       (cond
5552        (to-newsgroups (setq follow-to (list (cons 'Newsgroups to-newsgroups))))
5553        ;; Handle Followup-To.
5554        (followup-to
5555         (cond
5556          ((equal (downcase followup-to) "poster")
5557           (if (or (and followup-to (eq message-use-followup-to 'use))
5558                   (message-y-or-n-p "Obey Followup-To: poster? " t "\
5559 You should normally obey the Followup-To: header.
5560
5561         `Followup-To: poster'
5562 sends your response via e-mail instead of news.
5563
5564 A typical situation where `Followup-To: poster' is used is when the author
5565 does not read the newsgroup, so he wouldn't see any replies sent to it."))
5566               (setq message-this-is-news nil
5567                     distribution nil
5568                     follow-to (list (cons 'To (or mrt reply-to from ""))))
5569             (setq follow-to (list (cons 'Newsgroups newsgroups)))))
5570          (t
5571           (if (or (equal followup-to newsgroups)
5572                   (not (and followup-to (eq message-use-followup-to 'ask)))
5573                   (message-y-or-n-p
5574                    (concat "Obey Followup-To: " followup-to "? ") t "\
5575 You should normally obey the Followup-To: header.
5576
5577         `Followup-To: " followup-to "'
5578 directs your response to " (if (string-match "," followup-to)
5579                                "the specified newsgroups"
5580                              "that newsgroup only") ".
5581
5582 If a message is posted to several newsgroups, Followup-To is often
5583 used to direct the following discussion to one newsgroup only,
5584 because discussions that are spread over several newsgroup tend to
5585 be fragmented and very difficult to follow.
5586
5587 Also, some source/announcement newsgroups are not intended for discussion;
5588 responses here are directed to other newsgroups."))
5589               (setq follow-to (list (cons 'Newsgroups followup-to)))
5590             (setq follow-to (list (cons 'Newsgroups newsgroups)))))))
5591        ;; Handle Mail-Followup-To, followup via e-mail.
5592        ((and mft
5593              (or (not (eq message-use-mail-followup-to 'ask))
5594                  (message-y-or-n-p
5595                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
5596 You should normally obey the Mail-Followup-To: header.
5597
5598         `Mail-Followup-To: " mft "'
5599 directs your response to " (if (string-match "," mft)
5600                                "the specified addresses"
5601                              "that address only") " instead of news.
5602
5603 A typical situation where Mail-Followup-To is used is when the author thinks
5604 that further discussion should take place only in "
5605                              (if (string-match "," mft)
5606                                  "the specified mailing lists"
5607                                "that mailing list") ".")))
5608         (setq message-this-is-news nil
5609               distribution nil
5610               follow-to (list (cons 'To mft))))
5611        (posted-to (setq follow-to (list (cons 'Newsgroups posted-to))))
5612        (t
5613         (setq follow-to (list (cons 'Newsgroups newsgroups))))))
5614
5615     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
5616
5617     (message-setup
5618      `((Subject . ,subject)
5619        ,@follow-to
5620        ,@(and mct (list (cons 'Cc mct)))
5621        ,@(and distribution (list (cons 'Distribution distribution)))
5622        ,@(if (or references message-id)
5623              `((References . ,(concat (or references "") (and references " ")
5624                                       (or message-id ""))))))
5625      cur)
5626
5627     (setq message-reply-headers
5628           (make-full-mail-header-from-decoded-header
5629            0 subject from date message-id references 0 0 ""))))
5630
5631 ;;;###autoload
5632 (defun message-cancel-news (&optional arg)
5633   "Cancel an article you posted.
5634 If ARG, allow editing of the cancellation message."
5635   (interactive "P")
5636   (unless (message-news-p)
5637     (error "This is not a news article; canceling is impossible"))
5638   (let (from newsgroups message-id distribution buf sender)
5639     (save-excursion
5640       ;; Get header info from original article.
5641       (save-restriction
5642         (message-narrow-to-head-1)
5643         (setq from (message-fetch-field "from")
5644               sender (message-fetch-field "sender")
5645               newsgroups (message-fetch-field "newsgroups")
5646               message-id (message-fetch-field "message-id" t)
5647               distribution (message-fetch-field "distribution")))
5648       ;; Make sure that this article was written by the user.
5649       (unless (or
5650                ;; Canlock-logic as suggested by Per Abrahamsen
5651                ;; <abraham@dina.kvl.dk>
5652                ;;
5653                ;; IF article has cancel-lock THEN
5654                ;;   IF we can verify it THEN
5655                ;;     issue cancel
5656                ;;   ELSE
5657                ;;     error: cancellock: article is not yours
5658                ;; ELSE
5659                ;;   Use old rules, comparing sender...
5660                (if (message-fetch-field "Cancel-Lock")
5661                    (if (null (canlock-verify))
5662                        t
5663                      (error "Failed to verify Cancel-lock: This article is not yours"))
5664                  nil)
5665                (message-gnksa-enable-p 'cancel-messages)
5666                (and sender
5667                     (string-equal
5668                      (downcase sender)
5669                      (downcase (message-make-sender))))
5670                (string-equal
5671                 (downcase (cadr (std11-extract-address-components from)))
5672                 (downcase (cadr (std11-extract-address-components
5673                                  (message-make-from))))))
5674         (error "This article is not yours"))
5675       (when (yes-or-no-p "Do you really want to cancel this article? ")
5676         ;; Make control message.
5677         (if arg
5678             (message-news)
5679           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
5680         (erase-buffer)
5681         (insert "Newsgroups: " newsgroups "\n"
5682                 "From: " from "\n"
5683                 "Subject: cmsg cancel " message-id "\n"
5684                 "Control: cancel " message-id "\n"
5685                 (if distribution
5686                     (concat "Distribution: " distribution "\n")
5687                   "")
5688                 mail-header-separator "\n"
5689                 message-cancel-message)
5690         (run-hooks 'message-cancel-hook)
5691         (unless arg
5692           (message "Canceling your article...")
5693           (if (let ((message-syntax-checks
5694                      'dont-check-for-anything-just-trust-me)
5695                     (message-encoding-buffer (current-buffer))
5696                     (message-edit-buffer (current-buffer)))
5697                 (message-send-news))
5698               (message "Canceling your article...done"))
5699           (kill-buffer buf))))))
5700
5701 (defun message-supersede-setup-for-mime-edit ()
5702   (set (make-local-variable 'message-setup-hook) nil)
5703   (mime-edit-again))
5704
5705 ;;;###autoload
5706 (defun message-supersede ()
5707   "Start composing a message to supersede the current message.
5708 This is done simply by taking the old article and adding a Supersedes
5709 header line with the old Message-ID."
5710   (interactive)
5711   (let ((cur (current-buffer))
5712         (sender (message-fetch-field "sender"))
5713         (from (message-fetch-field "from")))
5714     ;; Check whether the user owns the article that is to be superseded.
5715     (unless (or
5716              ;; Canlock-logic as suggested by Per Abrahamsen
5717              ;; <abraham@dina.kvl.dk>
5718              ;;
5719              ;; IF article has cancel-lock THEN
5720              ;;   IF we can verify it THEN
5721              ;;     issue cancel
5722              ;;   ELSE
5723              ;;     error: cancellock: article is not yours
5724              ;; ELSE
5725              ;;   Use old rules, comparing sender...
5726              (if (message-fetch-field "Cancel-Lock")
5727                  (if (null (canlock-verify))
5728                      t
5729                    (error "Failed to verify Cancel-lock: This article is not yours"))
5730                nil)
5731              (message-gnksa-enable-p 'cancel-messages)
5732              (and sender
5733                   (string-equal
5734                    (downcase sender)
5735                    (downcase (message-make-sender))))
5736              (string-equal
5737               (downcase (cadr (std11-extract-address-components from)))
5738               (downcase (cadr (std11-extract-address-components
5739                                (message-make-from))))))
5740       (error "This article is not yours"))
5741     ;; Get a normal message buffer.
5742     (message-pop-to-buffer (message-buffer-name "supersede"))
5743     (insert-buffer-substring cur)
5744     (message-narrow-to-head-1)
5745     ;; Remove unwanted headers.
5746     (when message-ignored-supersedes-headers
5747       (message-remove-header message-ignored-supersedes-headers t))
5748     (goto-char (point-min))
5749     (if (not (re-search-forward "^Message-ID: " nil t))
5750         (error "No Message-ID in this article")
5751       (replace-match "Supersedes: " t t))
5752     (goto-char (point-max))
5753     (insert mail-header-separator)
5754     (widen)
5755     (when message-supersede-setup-function
5756       (funcall message-supersede-setup-function))
5757     (run-hooks 'message-supersede-setup-hook)
5758     (goto-char (point-min))
5759     (search-forward (concat "\n" mail-header-separator "\n") nil t)))
5760
5761 ;;;###autoload
5762 (defun message-recover ()
5763   "Reread contents of current buffer from its last auto-save file."
5764   (interactive)
5765   (let ((file-name (make-auto-save-file-name)))
5766     (cond ((save-window-excursion
5767              (if (not (eq system-type 'vax-vms))
5768                  (with-output-to-temp-buffer "*Directory*"
5769                    (with-current-buffer standard-output
5770                      (fundamental-mode)) ; for Emacs 20.4+
5771                    (buffer-disable-undo standard-output)
5772                    (let ((default-directory "/"))
5773                      (call-process
5774                       "ls" nil standard-output nil "-l" file-name))))
5775              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
5776            (let ((buffer-read-only nil))
5777              (erase-buffer)
5778              (insert-file-contents file-name nil)))
5779           (t (error "message-recover cancelled")))))
5780
5781 ;;; Washing Subject:
5782
5783 (defun message-wash-subject (subject)
5784   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
5785 Previous forwarders, replyers, etc. may add it."
5786   (with-temp-buffer
5787     (insert subject)
5788     (goto-char (point-min))
5789     ;; strip Re/Fwd stuff off the beginning
5790     (while (re-search-forward
5791             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
5792       (replace-match ""))
5793
5794     ;; and gnus-style forwards [foo@bar.com] subject
5795     (goto-char (point-min))
5796     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
5797       (replace-match ""))
5798
5799     ;; and off the end
5800     (goto-char (point-max))
5801     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
5802       (replace-match ""))
5803
5804     ;; and finally, any whitespace that was left-over
5805     (goto-char (point-min))
5806     (while (re-search-forward "^[ \t]+" nil t)
5807       (replace-match ""))
5808     (goto-char (point-max))
5809     (while (re-search-backward "[ \t]+$" nil t)
5810       (replace-match ""))
5811
5812     (buffer-string)))
5813
5814 ;;; Forwarding messages.
5815
5816 (defvar message-forward-decoded-p nil
5817   "Non-nil means the original message is decoded.")
5818
5819 (defun message-forward-subject-author-subject (subject)
5820   "Generate a SUBJECT for a forwarded message.
5821 The form is: [Source] Subject, where if the original message was mail,
5822 Source is the sender, and if the original message was news, Source is
5823 the list of newsgroups is was posted to."
5824   (concat "["
5825           (let ((prefix (message-fetch-field "newsgroups")))
5826             (or prefix
5827                 (and (setq prefix (message-fetch-field "from"))
5828                      (nnheader-decode-from prefix))
5829                 "(nowhere)"))
5830           "] " subject))
5831
5832 (defun message-forward-subject-fwd (subject)
5833   "Generate a SUBJECT for a forwarded message.
5834 The form is: Fwd: Subject, where Subject is the original subject of
5835 the message."
5836   (concat "Fwd: " subject))
5837
5838 (defun message-make-forward-subject ()
5839   "Return a Subject header suitable for the message in the current buffer."
5840   (save-excursion
5841     (save-restriction
5842       (message-narrow-to-head-1)
5843       (let ((funcs message-make-forward-subject-function)
5844             (subject (message-fetch-field "Subject")))
5845         (setq subject
5846               (if subject
5847                   (if message-forward-decoded-p
5848                       subject
5849                     (nnheader-decode-subject subject))
5850                 ""))
5851         (if message-wash-forwarded-subjects
5852             (setq subject (message-wash-subject subject)))
5853         ;; Make sure funcs is a list.
5854         (and funcs
5855              (not (listp funcs))
5856              (setq funcs (list funcs)))
5857         ;; Apply funcs in order, passing subject generated by previous
5858         ;; func to the next one.
5859         (while funcs
5860           (when (message-functionp (car funcs))
5861             (setq subject (funcall (car funcs) subject)))
5862           (setq funcs (cdr funcs)))
5863         subject))))
5864
5865 ;;;###autoload
5866 (defun message-forward (&optional news)
5867   "Forward the current message via mail.
5868 Optional NEWS will use news to forward instead of mail."
5869   (interactive "P")
5870   (let ((cur (current-buffer))
5871         (subject (message-make-forward-subject)))
5872     (if news
5873         (message-news nil subject)
5874       (message-mail nil subject))
5875     (message-forward-make-body cur)))
5876
5877 ;;;###autoload
5878 (defun message-forward-make-body (forward-buffer)
5879   ;; Put point where we want it before inserting the forwarded
5880   ;; message.
5881   ;; Note that this function definition for T-gnus is totally different
5882   ;; from the original Gnus."
5883   (if message-forward-before-signature
5884       (message-goto-body)
5885     (goto-char (point-max)))
5886   ;; Make sure we're at the start of the line.
5887   (unless (bolp)
5888     (insert "\n"))
5889   ;; Narrow to the area we are to insert.
5890   (narrow-to-region (point) (point))
5891   ;; Insert the separators and the forwarded buffer.
5892   (insert message-forward-start-separator)
5893   (let ((art-beg (point)))
5894     (insert-buffer-substring forward-buffer)
5895     (goto-char (point-max))
5896     (insert message-forward-end-separator)
5897     (set-text-properties (point-min) (point-max) nil)
5898     ;; Remove all unwanted headers.
5899     (goto-char art-beg)
5900     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
5901                                   (1- (point))
5902                                 (point)))
5903     (goto-char (point-min))
5904     (message-remove-header message-included-forward-headers t nil t)
5905     (widen)
5906     (message-position-point)))
5907
5908 ;;;###autoload
5909 (defun message-forward-rmail-make-body (forward-buffer)
5910   (save-window-excursion
5911     (set-buffer forward-buffer)
5912     ;; Rmail doesn't have rmail-msg-restore-non-pruned-header in Emacs
5913     ;; 20.  FIXIT, or we drop support for rmail in Emacs 20.
5914     (if (rmail-msg-is-pruned)
5915         (rmail-msg-restore-non-pruned-header)))
5916   (message-forward-make-body forward-buffer))
5917
5918 ;;;###autoload
5919 (defun message-insinuate-rmail ()
5920   "Let RMAIL uses message to forward."
5921   (interactive)
5922   (setq rmail-enable-mime-composing t)
5923   (setq rmail-insert-mime-forwarded-message-function
5924         'message-forward-rmail-make-body))
5925
5926 ;;;###autoload
5927 (defun message-resend (address)
5928   "Resend the current article to ADDRESS."
5929   (interactive
5930    (list (message-read-from-minibuffer "Resend message to: ")))
5931   (message "Resending message to %s..." address)
5932   (save-excursion
5933     (let ((cur (current-buffer))
5934           beg)
5935       ;; We first set up a normal mail buffer.
5936       (unless (message-mail-user-agent)
5937         (set-buffer (get-buffer-create " *message resend*"))
5938         (erase-buffer)
5939         (let ((message-this-is-mail t)
5940               ;; avoid to turn-on-mime-edit
5941               message-setup-hook)
5942           (message-setup `((To . ,address)))))
5943       ;; Insert our usual headers.
5944       (message-generate-headers '(From Date To))
5945       (message-narrow-to-headers)
5946       ;; Rename them all to "Resent-*".
5947       (while (re-search-forward "^[A-Za-z]" nil t)
5948         (forward-char -1)
5949         (insert "Resent-"))
5950       (widen)
5951       (forward-line)
5952       (delete-region (point) (point-max))
5953       (setq beg (point))
5954       ;; Insert the message to be resent.
5955       (insert-buffer-substring cur)
5956       (goto-char (point-min))
5957       (search-forward "\n\n")
5958       (forward-char -1)
5959       (save-restriction
5960         (narrow-to-region beg (point))
5961         (message-remove-header message-ignored-resent-headers t)
5962         (goto-char (point-max)))
5963       (insert mail-header-separator)
5964       ;; Rename all old ("Also-")Resent headers.
5965       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
5966         (beginning-of-line)
5967         (insert "Also-"))
5968       ;; Quote any "From " lines at the beginning.
5969       (goto-char beg)
5970       (when (looking-at "From ")
5971         (replace-match "X-From-Line: "))
5972       ;; Send it.
5973       (let ((message-encoding-buffer (current-buffer))
5974             (message-edit-buffer (current-buffer))
5975             message-required-mail-headers)
5976         (message-send-mail))
5977       (kill-buffer (current-buffer)))
5978     (message "Resending message to %s...done" address)))
5979
5980 (defun message-bounce-setup-for-mime-edit ()
5981   (set (make-local-variable 'message-setup-hook) nil)
5982   (mime-edit-again))
5983
5984 ;;;###autoload
5985 (defun message-bounce ()
5986   "Re-mail the current message.
5987 This only makes sense if the current message is a bounce message that
5988 contains some mail you have written which has been bounced back to
5989 you."
5990   (interactive)
5991   (let ((cur (current-buffer))
5992         boundary)
5993     (message-pop-to-buffer (message-buffer-name "bounce"))
5994     (insert-buffer-substring cur)
5995     (undo-boundary)
5996     (message-narrow-to-head)
5997     (if (and (message-fetch-field "MIME-Version")
5998              (setq boundary (message-fetch-field "Content-Type")))
5999         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
6000             (setq boundary (concat (match-string 1 boundary) " *\n"
6001                                    "Content-Type: message/rfc822"))
6002           (setq boundary nil)))
6003     (widen)
6004     (goto-char (point-min))
6005     (search-forward "\n\n" nil t)
6006     (if (or (and boundary
6007                  (re-search-forward boundary nil t)
6008                  (forward-line 2))
6009             (and (re-search-forward message-unsent-separator nil t)
6010                  (forward-line 1))
6011             (re-search-forward "^Return-Path:.*\n" nil t))
6012         ;; We remove everything before the bounced mail.
6013         (delete-region
6014          (point-min)
6015          (if (re-search-forward "^[^ \n\t]+:" nil t)
6016              (match-beginning 0)
6017            (point)))
6018       (when (re-search-backward "^.?From .*\n" nil t)
6019         (delete-region (match-beginning 0) (match-end 0))))
6020     (save-restriction
6021       (message-narrow-to-head-1)
6022       (message-remove-header message-ignored-bounced-headers t)
6023       (goto-char (point-max))
6024       (insert mail-header-separator))
6025     (when message-bounce-setup-function
6026       (funcall message-bounce-setup-function))
6027     (run-hooks 'message-bounce-setup-hook)
6028     (message-position-point)))
6029
6030 ;;;
6031 ;;; Interactive entry points for new message buffers.
6032 ;;;
6033
6034 ;;;###autoload
6035 (defun message-mail-other-window (&optional to subject)
6036   "Like `message-mail' command, but display mail buffer in another window."
6037   (interactive)
6038   (unless (message-mail-user-agent)
6039     (let ((pop-up-windows t)
6040           (special-display-buffer-names nil)
6041           (special-display-regexps nil)
6042           (same-window-buffer-names nil)
6043           (same-window-regexps nil))
6044       (message-pop-to-buffer (message-buffer-name "mail" to))))
6045   (let ((message-this-is-mail t))
6046     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6047                    nil nil 'switch-to-buffer-other-window)))
6048
6049 ;;;###autoload
6050 (defun message-mail-other-frame (&optional to subject)
6051   "Like `message-mail' command, but display mail buffer in another frame."
6052   (interactive)
6053   (unless (message-mail-user-agent)
6054     (let ((pop-up-frames t)
6055           (special-display-buffer-names nil)
6056           (special-display-regexps nil)
6057           (same-window-buffer-names nil)
6058           (same-window-regexps nil))
6059       (message-pop-to-buffer (message-buffer-name "mail" to))))
6060   (let ((message-this-is-mail t))
6061     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6062                    nil nil 'switch-to-buffer-other-frame)))
6063
6064 ;;;###autoload
6065 (defun message-news-other-window (&optional newsgroups subject)
6066   "Start editing a news article to be sent."
6067   (interactive)
6068   (let ((pop-up-windows t)
6069         (special-display-buffer-names nil)
6070         (special-display-regexps nil)
6071         (same-window-buffer-names nil)
6072         (same-window-regexps nil))
6073     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6074   (let ((message-this-is-news t))
6075     (message-setup `((Newsgroups . ,(or newsgroups ""))
6076                      (Subject . ,(or subject ""))))))
6077
6078 ;;;###autoload
6079 (defun message-news-other-frame (&optional newsgroups subject)
6080   "Start editing a news article to be sent."
6081   (interactive)
6082   (let ((pop-up-frames t)
6083         (special-display-buffer-names nil)
6084         (special-display-regexps nil)
6085         (same-window-buffer-names nil)
6086         (same-window-regexps nil))
6087     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6088   (let ((message-this-is-news t))
6089     (message-setup `((Newsgroups . ,(or newsgroups ""))
6090                      (Subject . ,(or subject ""))))))
6091
6092 ;;; underline.el
6093
6094 ;; This code should be moved to underline.el (from which it is stolen).
6095
6096 ;;;###autoload
6097 (defun bold-region (start end)
6098   "Bold all nonblank characters in the region.
6099 Works by overstriking characters.
6100 Called from program, takes two arguments START and END
6101 which specify the range to operate on."
6102   (interactive "r")
6103   (save-excursion
6104     (let ((end1 (make-marker)))
6105       (move-marker end1 (max start end))
6106       (goto-char (min start end))
6107       (while (< (point) end1)
6108         (or (looking-at "[_\^@- ]")
6109             (insert (char-after) "\b"))
6110         (forward-char 1)))))
6111
6112 ;;;###autoload
6113 (defun unbold-region (start end)
6114   "Remove all boldness (overstruck characters) in the region.
6115 Called from program, takes two arguments START and END
6116 which specify the range to operate on."
6117   (interactive "r")
6118   (save-excursion
6119     (let ((end1 (make-marker)))
6120       (move-marker end1 (max start end))
6121       (goto-char (min start end))
6122       (while (re-search-forward "\b" end1 t)
6123         (if (eq (char-after) (char-after (- (point) 2)))
6124             (delete-char -2))))))
6125
6126 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
6127
6128 ;; Support for toolbar
6129 (eval-when-compile
6130   (defvar tool-bar-map)
6131   (defvar tool-bar-mode))
6132
6133 (defun message-tool-bar-map ()
6134   (or message-tool-bar-map
6135       (setq message-tool-bar-map
6136             (and
6137              (condition-case nil (require 'tool-bar) (error nil))
6138              (fboundp 'tool-bar-add-item-from-menu)
6139              tool-bar-mode
6140              (let ((tool-bar-map (copy-keymap tool-bar-map))
6141                    (load-path (mm-image-load-path)))
6142                ;; Zap some items which aren't so relevant and take
6143                ;; up space.
6144                (dolist (key '(print-buffer kill-buffer save-buffer
6145                                            write-file dired open-file))
6146                  (define-key tool-bar-map (vector key) nil))
6147                (tool-bar-add-item-from-menu
6148                 'message-send-and-exit "mail_send" message-mode-map)
6149                (tool-bar-add-item-from-menu
6150                 'message-kill-buffer "close" message-mode-map)
6151                (tool-bar-add-item-from-menu
6152                 'message-dont-send "cancel" message-mode-map)
6153                (tool-bar-add-item-from-menu
6154                 'mime-edit-insert-file "attach" message-mode-map)
6155                (tool-bar-add-item-from-menu
6156                 'ispell-message "spell" message-mode-map)
6157                (tool-bar-add-item-from-menu
6158                 'message-insert-importance-high "important"
6159                 message-mode-map)
6160                (tool-bar-add-item-from-menu
6161                 'message-insert-importance-low "unimportant"
6162                 message-mode-map)
6163                (tool-bar-add-item-from-menu
6164                 'message-insert-disposition-notification-to "receipt"
6165                 message-mode-map)
6166                tool-bar-map)))))
6167
6168 ;;; Group name completion.
6169
6170 (defcustom message-newgroups-header-regexp
6171   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
6172   "Regexp that match headers that lists groups."
6173   :group 'message
6174   :type 'regexp)
6175
6176 (defcustom message-completion-alist
6177   (list (cons message-newgroups-header-regexp 'message-expand-group)
6178         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name))
6179   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
6180   :group 'message
6181   :type '(alist :key-type regexp :value-type function))
6182
6183 (defcustom message-expand-name-function
6184   (if (fboundp 'bbdb-complete-name)
6185       'bbdb-complete-name
6186     (if (fboundp 'lsdb-complete-name)
6187         'lsdb-complete-name
6188       'expand-abbrev))
6189   "*A function called to expand addresses in field body."
6190   :group 'message
6191   :type 'function)
6192
6193 (defcustom message-tab-body-function nil
6194   "*Function to execute when `message-tab' (TAB) is executed in the body.
6195 If nil, the function bound in `text-mode-map' or `global-map' is executed."
6196   :group 'message
6197   :type 'function)
6198
6199 (defun message-tab ()
6200   "Complete names according to `message-completion-alist'.
6201 Execute function specified by `message-tab-body-function' when not in
6202 those headers."
6203   (interactive)
6204   (let ((alist message-completion-alist))
6205     (while (and alist
6206                 (let ((mail-abbrev-mode-regexp (caar alist)))
6207                   (not (mail-abbrev-in-expansion-header-p))))
6208       (setq alist (cdr alist)))
6209     (funcall (or (cdar alist) message-tab-body-function
6210                  (lookup-key text-mode-map "\t")
6211                  (lookup-key global-map "\t")
6212                  'indent-relative))))
6213
6214 (defun message-expand-group ()
6215   "Expand the group name under point."
6216   (let* ((b (save-excursion
6217               (save-restriction
6218                 (narrow-to-region
6219                  (save-excursion
6220                    (beginning-of-line)
6221                    (skip-chars-forward "^:")
6222                    (1+ (point)))
6223                  (point))
6224                 (skip-chars-backward "^, \t\n") (point))))
6225          (completion-ignore-case t)
6226          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
6227                                             (point))))
6228          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
6229          (completions (all-completions string hashtb))
6230          comp)
6231     (delete-region b (point))
6232     (cond
6233      ((= (length completions) 1)
6234       (if (string= (car completions) string)
6235           (progn
6236             (insert string)
6237             (message "Only matching group"))
6238         (insert (car completions))))
6239      ((and (setq comp (try-completion string hashtb))
6240            (not (string= comp string)))
6241       (insert comp))
6242      (t
6243       (insert string)
6244       (if (not comp)
6245           (message "No matching groups")
6246         (save-selected-window
6247           (pop-to-buffer "*Completions*")
6248           (buffer-disable-undo)
6249           (let ((buffer-read-only nil))
6250             (erase-buffer)
6251             (let ((standard-output (current-buffer)))
6252               (display-completion-list (sort completions 'string<)))
6253             (goto-char (point-min))
6254             (delete-region (point) (progn (forward-line 3) (point))))))))))
6255
6256 (defun message-expand-name ()
6257   (funcall message-expand-name-function))
6258
6259 ;;; Help stuff.
6260
6261 (defun message-talkative-question (ask question show &rest text)
6262   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
6263 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
6264 The following arguments may contain lists of values."
6265   (if (and show
6266            (setq text (message-flatten-list text)))
6267       (save-window-excursion
6268         (save-excursion
6269           (with-output-to-temp-buffer " *MESSAGE information message*"
6270             (set-buffer " *MESSAGE information message*")
6271             (fundamental-mode)          ; for Emacs 20.4+
6272             (mapcar 'princ text)
6273             (goto-char (point-min))))
6274         (funcall ask question))
6275     (funcall ask question)))
6276
6277 (defun message-flatten-list (list)
6278   "Return a new, flat list that contains all elements of LIST.
6279
6280 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
6281 => (1 2 3 4 5 6 7)"
6282   (cond ((consp list)
6283          (apply 'append (mapcar 'message-flatten-list list)))
6284         (list
6285          (list list))))
6286
6287 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
6288   "Create and return a buffer with name based on NAME using `generate-new-buffer.'
6289 Then clone the local variables and values from the old buffer to the
6290 new one, cloning only the locals having a substring matching the
6291 regexp varstr."
6292   (let ((oldbuf (current-buffer)))
6293     (save-excursion
6294       (set-buffer (generate-new-buffer name))
6295       (message-clone-locals oldbuf varstr)
6296       (current-buffer))))
6297
6298 (defun message-clone-locals (buffer &optional varstr)
6299   "Clone the local variables from BUFFER to the current buffer."
6300   (let ((locals (save-excursion
6301                   (set-buffer buffer)
6302                   (buffer-local-variables)))
6303         (regexp
6304          "^\\(gnus\\|nn\\|message\\|user-\\(mail-address\\|full-name\\)\\)"))
6305     (mapcar
6306      (lambda (local)
6307        (when (and (consp local)
6308                   (car local)
6309                   (string-match regexp (symbol-name (car local)))
6310                   (or (null varstr)
6311                       (string-match varstr (symbol-name (car local)))))
6312          (ignore-errors
6313            (set (make-local-variable (car local))
6314                 (cdr local)))))
6315      locals)))
6316
6317
6318 ;;; @ for MIME Edit mode
6319 ;;;
6320
6321 (defun message-maybe-encode ()
6322   (when message-mime-mode
6323     ;; Inherit the buffer local variable `mime-edit-pgp-processing'.
6324     (let ((pgp-processing (with-current-buffer message-edit-buffer
6325                             mime-edit-pgp-processing)))
6326       (setq mime-edit-pgp-processing pgp-processing))
6327     (run-hooks 'mime-edit-translate-hook)
6328     (if (catch 'mime-edit-error
6329           (save-excursion
6330             (mime-edit-pgp-enclose-buffer)
6331             (mime-edit-translate-body)))
6332         (error "Translation error!"))
6333     (run-hooks 'mime-edit-exit-hook)))
6334
6335 (defun message-mime-insert-article (&optional full-headers)
6336   (interactive "P")
6337   (let ((message-cite-function 'mime-edit-inserted-message-filter)
6338         (message-reply-buffer
6339          (message-get-parameter-with-eval 'original-buffer))
6340         (start (point)))
6341     (message-yank-original nil)
6342     (save-excursion
6343       (narrow-to-region (goto-char start)
6344                         (if (search-forward "\n\n" nil t)
6345                             (1- (point))
6346                           (point-max)))
6347       (goto-char (point-min))
6348       (let ((message-included-forward-headers
6349              (if full-headers "" message-included-forward-headers)))
6350         (message-remove-header message-included-forward-headers t nil t))
6351       (widen))))
6352
6353 (set-alist 'mime-edit-message-inserter-alist
6354            'message-mode (function message-mime-insert-article))
6355
6356 ;;; Miscellaneous functions
6357
6358 ;; stolen (and renamed) from nnheader.el
6359 (static-if (fboundp 'subst-char-in-string)
6360     (defsubst message-replace-chars-in-string (string from to)
6361       (subst-char-in-string from to string))
6362   (defun message-replace-chars-in-string (string from to)
6363     "Replace characters in STRING from FROM to TO."
6364     (let ((string (substring string 0)) ;Copy string.
6365           (len (length string))
6366           (idx 0))
6367       ;; Replace all occurrences of FROM with TO.
6368       (while (< idx len)
6369         (when (= (aref string idx) from)
6370           (aset string idx to))
6371         (setq idx (1+ idx)))
6372       string)))
6373
6374 ;;;
6375 ;;; MIME functions
6376 ;;;
6377
6378 (defvar message-inhibit-body-encoding t)
6379
6380 (defun message-encode-message-body ()
6381   (unless message-inhibit-body-encoding
6382     (let ((mail-parse-charset (or mail-parse-charset
6383                                   message-default-charset))
6384           (case-fold-search t)
6385           lines content-type-p)
6386       (message-goto-body)
6387       (save-restriction
6388         (narrow-to-region (point) (point-max))
6389         (let ((new (mml-generate-mime)))
6390           (when new
6391             (delete-region (point-min) (point-max))
6392             (insert new)
6393             (goto-char (point-min))
6394             (if (eq (aref new 0) ?\n)
6395                 (delete-char 1)
6396               (search-forward "\n\n")
6397               (setq lines (buffer-substring (point-min) (1- (point))))
6398               (delete-region (point-min) (point))))))
6399       (save-restriction
6400         (message-narrow-to-headers-or-head)
6401         (message-remove-header "Mime-Version")
6402         (goto-char (point-max))
6403         (insert "MIME-Version: 1.0\n")
6404         (when lines
6405           (insert lines))
6406         (setq content-type-p
6407               (or mml-boundary
6408                   (re-search-backward "^Content-Type:" nil t))))
6409       (save-restriction
6410         (message-narrow-to-headers-or-head)
6411         (message-remove-first-header "Content-Type")
6412         (message-remove-first-header "Content-Transfer-Encoding"))
6413       ;; We always make sure that the message has a Content-Type
6414       ;; header.  This is because some broken MTAs and MUAs get
6415       ;; awfully confused when confronted with a message with a
6416       ;; MIME-Version header and without a Content-Type header.  For
6417       ;; instance, Solaris' /usr/bin/mail.
6418       (unless content-type-p
6419         (goto-char (point-min))
6420         ;; For unknown reason, MIME-Version doesn't exist.
6421         (when (re-search-forward "^MIME-Version:" nil t)
6422           (forward-line 1)
6423           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
6424
6425 (defun message-read-from-minibuffer (prompt &optional initial-contents)
6426   "Read from the minibuffer while providing abbrev expansion."
6427   (if (fboundp 'mail-abbrevs-setup)
6428       (let ((mail-abbrev-mode-regexp "")
6429             (minibuffer-setup-hook 'mail-abbrevs-setup)
6430             (minibuffer-local-map message-minibuffer-local-map))
6431         (read-from-minibuffer prompt initial-contents))
6432     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
6433           (minibuffer-local-map message-minibuffer-local-map))
6434       (read-string prompt initial-contents))))
6435
6436 (defun message-use-alternative-email-as-from ()
6437   (require 'mail-utils)
6438   (let* ((fields '("To" "Cc"))
6439          (emails
6440           (split-string
6441            (mail-strip-quoted-names
6442             (mapconcat 'message-fetch-reply-field fields ","))
6443            "[ \f\t\n\r\v,]+"))
6444          email)
6445     (while emails
6446       (if (string-match message-alternative-emails (car emails))
6447           (setq email (car emails)
6448                 emails nil))
6449       (pop emails))
6450     (unless (or (not email) (equal email user-mail-address))
6451       (goto-char (point-max))
6452       (insert "From: " email "\n"))))
6453
6454 (defun message-options-get (symbol)
6455   (cdr (assq symbol message-options)))
6456
6457 (defun message-options-set (symbol value)
6458   (let ((the-cons (assq symbol message-options)))
6459     (if the-cons
6460         (if value
6461             (setcdr the-cons value)
6462           (setq message-options (delq the-cons message-options)))
6463       (and value
6464            (push (cons symbol value) message-options))))
6465   value)
6466
6467 (defun message-options-set-recipient ()
6468   (save-restriction
6469     (message-narrow-to-headers-or-head)
6470     (message-options-set 'message-sender
6471                          (mail-strip-quoted-names
6472                           (message-fetch-field "from")))
6473     (message-options-set 'message-recipients
6474                          (mail-strip-quoted-names
6475                           (let ((to (message-fetch-field "to"))
6476                                 (cc (message-fetch-field "cc"))
6477                                 (bcc (message-fetch-field "bcc")))
6478                             (concat
6479                              (or to "")
6480                              (if (and to cc) ", ")
6481                              (or cc "")
6482                              (if (and (or to cc) bcc) ", ")
6483                              (or bcc "")))))))
6484
6485 (when (featurep 'xemacs)
6486   (require 'messagexmas)
6487   (message-xmas-redefine))
6488
6489 (provide 'message)
6490
6491 (run-hooks 'message-load-hook)
6492
6493 ;; Local Variables:
6494 ;; coding: iso-8859-1
6495 ;; End:
6496
6497 ;;; message.el ends here