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