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