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