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