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