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