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