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