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