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   "Send mail 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     (when 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        (while groups
3571          (when (and (not (boundp (intern (car groups) hashtb)))
3572                     (not (equal (car groups) "poster")))
3573            (push (car groups) errors))
3574          (pop groups))
3575        (cond
3576         ;; Gnus is not running.
3577         ((or (not hashtb)
3578              (not (boundp 'gnus-read-active-file)))
3579          t)
3580         ;; We don't have all the group names.
3581         ((and (or (not gnus-read-active-file)
3582                   (eq gnus-read-active-file 'some))
3583               errors)
3584          (y-or-n-p
3585           (format
3586            "Really post to %s possibly unknown group%s: %s? "
3587            (if (= (length errors) 1) "this" "these")
3588            (if (= (length errors) 1) "" "s")
3589            (mapconcat 'identity errors ", "))))
3590         ;; There were no errors.
3591         ((not errors)
3592          t)
3593         ;; There are unknown groups.
3594         (t
3595          (y-or-n-p
3596           (format
3597            "Really post to %s unknown group%s: %s? "
3598            (if (= (length errors) 1) "this" "these")
3599            (if (= (length errors) 1) "" "s")
3600            (mapconcat 'identity errors ", ")))))))
3601      ;; Check the Newsgroups & Followup-To headers for syntax errors.
3602      (message-check 'valid-newsgroups
3603        (let ((case-fold-search t)
3604              (headers '("Newsgroups" "Followup-To"))
3605              header error)
3606          (while (and headers (not error))
3607            (when (setq header (mail-fetch-field (car headers)))
3608              (if (or
3609                   (not
3610                    (string-match
3611                     "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
3612                     header))
3613                   (memq
3614                    nil (mapcar
3615                         (lambda (g)
3616                           (not (string-match "\\.\\'\\|\\.\\." g)))
3617                         (message-tokenize-header header ","))))
3618                  (setq error t)))
3619            (unless error
3620              (pop headers)))
3621          (if (not error)
3622              t
3623            (y-or-n-p
3624             (format "The %s header looks odd: \"%s\".  Really post? "
3625                     (car headers) header)))))
3626      (message-check 'repeated-newsgroups
3627        (let ((case-fold-search t)
3628              (headers '("Newsgroups" "Followup-To"))
3629              header error groups group)
3630          (while (and headers
3631                      (not error))
3632            (when (setq header (mail-fetch-field (pop headers)))
3633              (setq groups (message-tokenize-header header ","))
3634              (while (setq group (pop groups))
3635                (when (member group groups)
3636                  (setq error group
3637                        groups nil)))))
3638          (if (not error)
3639              t
3640            (y-or-n-p
3641             (format "Group %s is repeated in headers.  Really post? " error)))))
3642      ;; Check the From header.
3643      (message-check 'from
3644        (let* ((case-fold-search t)
3645               (from (message-fetch-field "from"))
3646               ad)
3647          (cond
3648           ((not from)
3649            (message "There is no From line.  Posting is denied.")
3650            nil)
3651           ((or (not (string-match
3652                      "@[^\\.]*\\."
3653                      (setq ad (nth 1 (mail-extract-address-components
3654                                       from))))) ;larsi@ifi
3655                (string-match "\\.\\." ad) ;larsi@ifi..uio
3656                (string-match "@\\." ad) ;larsi@.ifi.uio
3657                (string-match "\\.$" ad) ;larsi@ifi.uio.
3658                (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
3659                (string-match "(.*).*(.*)" from)) ;(lars) (lars)
3660            (message
3661             "Denied posting -- the From looks strange: \"%s\"." from)
3662            nil)
3663           (t t))))))
3664
3665 (defun message-check-news-body-syntax ()
3666   (and
3667    ;; Check for long lines.
3668    (message-check 'long-lines
3669      (goto-char (point-min))
3670      (re-search-forward
3671       (concat "^" (regexp-quote mail-header-separator) "$"))
3672      (forward-line 1)
3673      (while (and
3674              (or (looking-at
3675                   mime-edit-tag-regexp)
3676                  (let ((p (point)))
3677                    (end-of-line)
3678                    (< (- (point) p) 80)))
3679              (zerop (forward-line 1))))
3680      (or (bolp)
3681          (eobp)
3682          (y-or-n-p
3683           "You have lines longer than 79 characters.  Really post? ")))
3684    ;; Check whether the article is empty.
3685    (message-check 'empty
3686      (goto-char (point-min))
3687      (re-search-forward
3688       (concat "^" (regexp-quote mail-header-separator) "$"))
3689      (forward-line 1)
3690      (let ((b (point)))
3691        (goto-char (point-max))
3692        (re-search-backward message-signature-separator nil t)
3693        (beginning-of-line)
3694        (or (re-search-backward "[^ \n\t]" b t)
3695            (if (message-gnksa-enable-p 'empty-article)
3696                (y-or-n-p "Empty article.  Really post? ")
3697              (message "Denied posting -- Empty article.")
3698              nil))))
3699    ;; Check for control characters.
3700    (message-check 'control-chars
3701      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
3702          (y-or-n-p
3703           "The article contains control characters.  Really post? ")
3704        t))
3705    ;; Check 8bit characters.
3706    (message-check '8bit
3707      (message-check-8bit))
3708    ;; Check excessive size.
3709    (message-check 'size
3710      (if (> (buffer-size) 60000)
3711          (y-or-n-p
3712           (format "The article is %d octets long.  Really post? "
3713                   (buffer-size)))
3714        t))
3715    ;; Check whether any new text has been added.
3716    (message-check 'new-text
3717      (or
3718       (not message-checksum)
3719       (not (eq (message-checksum) message-checksum))
3720       (if (message-gnksa-enable-p 'quoted-text-only)
3721           (y-or-n-p
3722            "It looks like no new text has been added.  Really post? ")
3723         (message "Denied posting -- no new text has been added.")
3724         nil)))
3725    ;; Check the length of the signature.
3726    (message-check 'signature
3727      (goto-char (point-max))
3728      (if (> (count-lines (point) (point-max)) 5)
3729          (y-or-n-p
3730           (format
3731            "Your .sig is %d lines; it should be max 4.  Really post? "
3732            (1- (count-lines (point) (point-max)))))
3733        t))
3734    ;; Ensure that text follows last quoted portion.
3735    (message-check 'quoting-style
3736      (goto-char (point-max))
3737      (let ((no-problem t))
3738        (when (search-backward-regexp "^>[^\n]*\n" nil t)
3739          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
3740        (if no-problem
3741            t
3742          (if (message-gnksa-enable-p 'quoted-text-only)
3743              (y-or-n-p "Your text should follow quoted text.  Really post? ")
3744            ;; Ensure that
3745            (goto-char (point-min))
3746            (re-search-forward
3747             (concat "^" (regexp-quote mail-header-separator) "$"))
3748            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
3749                (y-or-n-p "Your text should follow quoted text.  Really post? ")
3750              (message "Denied posting -- only quoted text.")
3751              nil)))))))
3752
3753 (defun message-check-mail-syntax ()
3754   "Check the syntax of the message."
3755   (save-excursion
3756     (save-restriction
3757       (widen)
3758       (and
3759        ;; We narrow to the headers and check them first.
3760        (save-excursion
3761          (save-restriction
3762            (message-narrow-to-headers)
3763            (message-check-mail-header-syntax)))
3764        ;; Check the body.
3765        (save-excursion
3766          (set-buffer message-edit-buffer)
3767          (message-check-mail-body-syntax))))))
3768
3769 (defun message-check-mail-header-syntax ()
3770   t)
3771
3772 (defun message-check-mail-body-syntax ()
3773   (and
3774    ;; Check 8bit characters.
3775    (message-check '8bit
3776      (message-check-8bit)
3777      )))
3778
3779 (defun message-check-8bit ()
3780   "Check the article contains 8bit characters."
3781   (save-excursion
3782     (set-buffer message-encoding-buffer)
3783     (message-narrow-to-headers)
3784     (let* ((case-fold-search t)
3785            (field-value (message-fetch-field "content-transfer-encoding")))
3786       (if (and field-value
3787                (member (downcase field-value) message-8bit-encoding-list))
3788           t
3789         (widen)
3790         (set-buffer (get-buffer-create " message syntax"))
3791         (erase-buffer)
3792         (goto-char (point-min))
3793         (set-buffer-multibyte nil)
3794         (insert-buffer message-encoding-buffer)
3795         (goto-char (point-min))
3796         (if (re-search-forward "[^\x00-\x7f]" nil t)
3797             (y-or-n-p
3798              "The article contains 8bit characters.  Really post? ")
3799           t)))))
3800
3801 (defun message-checksum ()
3802   "Return a \"checksum\" for the current buffer."
3803   (let ((sum 0))
3804     (save-excursion
3805       (goto-char (point-min))
3806       (re-search-forward
3807        (concat "^" (regexp-quote mail-header-separator) "$"))
3808       (while (not (eobp))
3809         (when (not (looking-at "[ \t\n]"))
3810           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
3811                             (char-after))))
3812         (forward-char 1)))
3813     sum))
3814
3815 (defun message-do-fcc ()
3816   "Process Fcc headers in the current buffer."
3817   (let ((case-fold-search t)
3818         (coding-system-for-write 'raw-text)
3819         (output-coding-system 'raw-text)
3820         list file)
3821     (save-excursion
3822       (set-buffer (get-buffer-create " *message temp*"))
3823       (erase-buffer)
3824       (insert-buffer-substring message-encoding-buffer)
3825       (save-restriction
3826         (message-narrow-to-headers)
3827         (while (setq file (message-fetch-field "fcc"))
3828           (push file list)
3829           (message-remove-header "fcc" nil t)))
3830       (goto-char (point-min))
3831       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
3832       (replace-match "" t t)
3833       ;; Process FCC operations.
3834       (while list
3835         (setq file (pop list))
3836         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
3837             ;; Pipe the article to the program in question.
3838             (call-process-region (point-min) (point-max) shell-file-name
3839                                  nil nil nil shell-command-switch
3840                                  (match-string 1 file))
3841           ;; Save the article.
3842           (setq file (expand-file-name file))
3843           (unless (file-exists-p (file-name-directory file))
3844             (make-directory (file-name-directory file) t))
3845           (if (and message-fcc-handler-function
3846                    (not (eq message-fcc-handler-function 'rmail-output)))
3847               (funcall message-fcc-handler-function file)
3848             (if (and (file-readable-p file) (mail-file-babyl-p file))
3849                 (rmail-output file 1 nil t)
3850               (let ((mail-use-rfc822 t))
3851                 (rmail-output file 1 t t))))))
3852       (kill-buffer (current-buffer)))))
3853
3854 (defun message-output (filename)
3855   "Append this article to Unix/babyl mail file FILENAME."
3856   (if (and (file-readable-p filename)
3857            (mail-file-babyl-p filename))
3858       (gnus-output-to-rmail filename t)
3859     (gnus-output-to-mail filename t)))
3860
3861 (defun message-cleanup-headers ()
3862   "Do various automatic cleanups of the headers."
3863   ;; Remove empty lines in the header.
3864   (save-restriction
3865     (message-narrow-to-headers)
3866     ;; Remove blank lines.
3867     (while (re-search-forward "^[ \t]*\n" nil t)
3868       (replace-match "" t t))
3869
3870     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
3871     ;; spaces to comma and eliminate spaces around commas.  Eliminate
3872     ;; embedded line breaks.
3873     (goto-char (point-min))
3874     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
3875       (save-restriction
3876         (narrow-to-region
3877          (point)
3878          (if (re-search-forward "^[^ \t]" nil t)
3879              (match-beginning 0)
3880            (forward-line 1)
3881            (point)))
3882         (goto-char (point-min))
3883         (while (re-search-forward "\n[ \t]+" nil t)
3884           (replace-match " " t t))      ;No line breaks (too confusing)
3885         (goto-char (point-min))
3886         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
3887           (replace-match "," t t))
3888         (goto-char (point-min))
3889         ;; Remove trailing commas.
3890         (when (re-search-forward ",+$" nil t)
3891           (replace-match "" t t))))))
3892
3893 (defun message-make-date (&optional now)
3894   "Make a valid data header.
3895 If NOW, use that time instead."
3896   (let* ((now (or now (current-time)))
3897          (zone (nth 8 (decode-time now)))
3898          (sign "+"))
3899     (when (< zone 0)
3900       (setq sign "-")
3901       (setq zone (- zone)))
3902     (concat
3903      (format-time-string "%d" now)
3904      ;; The month name of the %b spec is locale-specific.  Pfff.
3905      (format " %s "
3906              (capitalize (car (rassoc (nth 4 (decode-time now))
3907                                       parse-time-months))))
3908      (format-time-string "%Y %H:%M:%S " now)
3909      ;; We do all of this because XEmacs doesn't have the %z spec.
3910      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
3911
3912 (defun message-make-followup-subject (subject)
3913   "Make a followup Subject."
3914   (cond
3915    ((and (eq message-use-subject-re 'guess)
3916          (string-match message-subject-encoded-re-regexp subject))
3917     subject)
3918    (message-use-subject-re
3919     (concat "Re: " (message-strip-subject-re subject)))
3920    (t subject)))
3921
3922 (defun message-make-message-id ()
3923   "Make a unique Message-ID."
3924   (concat "<" (message-unique-id)
3925           (let ((psubject (save-excursion (message-fetch-field "subject")))
3926                 (psupersedes
3927                  (save-excursion (message-fetch-field "supersedes"))))
3928             (if (or
3929                  (and message-reply-headers
3930                       (mail-header-references message-reply-headers)
3931                       (mail-header-subject message-reply-headers)
3932                       psubject
3933                       (not (string=
3934                             (message-strip-subject-re
3935                              (mail-header-subject message-reply-headers))
3936                             (message-strip-subject-re psubject))))
3937                  (and psupersedes
3938                       (string-match "_-_@" psupersedes)))
3939                 "_-_" ""))
3940           "@" (message-make-fqdn) ">"))
3941
3942 (defvar message-unique-id-char nil)
3943
3944 ;; If you ever change this function, make sure the new version
3945 ;; cannot generate IDs that the old version could.
3946 ;; You might for example insert a "." somewhere (not next to another dot
3947 ;; or string boundary), or modify the "fsf" string.
3948 (defun message-unique-id ()
3949   ;; Don't use microseconds from (current-time), they may be unsupported.
3950   ;; Instead we use this randomly inited counter.
3951   (setq message-unique-id-char
3952         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
3953            ;; (current-time) returns 16-bit ints,
3954            ;; and 2^16*25 just fits into 4 digits i base 36.
3955            (* 25 25)))
3956   (let ((tm (current-time)))
3957     (concat
3958      (if (memq system-type '(ms-dos emx vax-vms))
3959          (let ((user (downcase (user-login-name))))
3960            (while (string-match "[^a-z0-9_]" user)
3961              (aset user (match-beginning 0) ?_))
3962            user)
3963        (message-number-base36 (user-uid) -1))
3964      (message-number-base36 (+ (car   tm)
3965                                (lsh (% message-unique-id-char 25) 16)) 4)
3966      (message-number-base36 (+ (nth 1 tm)
3967                                (lsh (/ message-unique-id-char 25) 16)) 4)
3968      ;; Append the newsreader name, because while the generated
3969      ;; ID is unique to this newsreader, other newsreaders might
3970      ;; otherwise generate the same ID via another algorithm.
3971      ".fsf")))
3972
3973 (defun message-number-base36 (num len)
3974   (if (if (< len 0)
3975           (<= num 0)
3976         (= len 0))
3977       ""
3978     (concat (message-number-base36 (/ num 36) (1- len))
3979             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
3980                                   (% num 36))))))
3981
3982 (defun message-make-organization ()
3983   "Make an Organization header."
3984   (let* ((organization
3985           (when message-user-organization
3986             (if (message-functionp message-user-organization)
3987                 (funcall message-user-organization)
3988               message-user-organization))))
3989     (save-excursion
3990       (message-set-work-buffer)
3991       (cond ((stringp organization)
3992              (insert organization))
3993             ((and (eq t organization)
3994                   message-user-organization-file
3995                   (file-exists-p message-user-organization-file))
3996              (insert-file-contents message-user-organization-file)))
3997       (goto-char (point-min))
3998       (while (re-search-forward "[\t\n]+" nil t)
3999         (replace-match "" t t))
4000       (unless (zerop (buffer-size))
4001         (buffer-string)))))
4002
4003 (defun message-make-lines ()
4004   "Count the number of lines and return numeric string."
4005   (save-excursion
4006     (save-restriction
4007       (widen)
4008       (message-goto-body)
4009       (int-to-string (count-lines (point) (point-max))))))
4010
4011 (defun message-make-in-reply-to ()
4012   "Return the In-Reply-To header for this message."
4013   (when message-reply-headers
4014     (let ((from (mail-header-from message-reply-headers))
4015           (date (mail-header-date message-reply-headers))
4016           (msg-id (mail-header-message-id message-reply-headers)))
4017       (when msg-id
4018         (concat msg-id
4019                 (when from
4020                   (let ((pair (std11-extract-address-components from)))
4021                     (concat "\n ("
4022                             (or (car pair) (cadr pair))
4023                             "'s message of \""
4024                             (if (or (not date) (string= date ""))
4025                                 "(unknown date)" date)
4026                             "\")"))))))))
4027
4028 (defun message-make-distribution ()
4029   "Make a Distribution header."
4030   (let ((orig-distribution (message-fetch-reply-field "distribution")))
4031     (cond ((message-functionp message-distribution-function)
4032            (funcall message-distribution-function))
4033           (t orig-distribution))))
4034
4035 (defun message-make-expires ()
4036   "Return an Expires header based on `message-expires'."
4037   (let ((current (current-time))
4038         (future (* 1.0 message-expires 60 60 24)))
4039     ;; Add the future to current.
4040     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
4041     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
4042     (message-make-date current)))
4043
4044 (defun message-make-path ()
4045   "Return uucp path."
4046   (let ((login-name (user-login-name)))
4047     (cond ((null message-user-path)
4048            (concat (system-name) "!" login-name))
4049           ((stringp message-user-path)
4050            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
4051            (concat message-user-path "!" login-name))
4052           (t login-name))))
4053
4054 (defun message-make-from ()
4055   "Make a From header."
4056   (let* ((style message-from-style)
4057          (login (message-make-address))
4058          (fullname
4059           (or (and (boundp 'user-full-name)
4060                    user-full-name)
4061               (user-full-name))))
4062     (when (string= fullname "&")
4063       (setq fullname (user-login-name)))
4064     (save-excursion
4065       (message-set-work-buffer)
4066       (cond
4067        ((or (null style)
4068             (equal fullname ""))
4069         (insert login))
4070        ((or (eq style 'angles)
4071             (and (not (eq style 'parens))
4072                  ;; Use angles if no quoting is needed, or if parens would
4073                  ;; need quoting too.
4074                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
4075                      (let ((tmp (concat fullname nil)))
4076                        (while (string-match "([^()]*)" tmp)
4077                          (aset tmp (match-beginning 0) ?-)
4078                          (aset tmp (1- (match-end 0)) ?-))
4079                        (string-match "[\\()]" tmp)))))
4080         (insert fullname)
4081         (goto-char (point-min))
4082         ;; Look for a character that cannot appear unquoted
4083         ;; according to RFC 822.
4084         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
4085           ;; Quote fullname, escaping specials.
4086           (goto-char (point-min))
4087           (insert "\"")
4088           (while (re-search-forward "[\"\\]" nil 1)
4089             (replace-match "\\\\\\&" t))
4090           (insert "\""))
4091         (insert " <" login ">"))
4092        (t                               ; 'parens or default
4093         (insert login " (")
4094         (let ((fullname-start (point)))
4095           (insert fullname)
4096           (goto-char fullname-start)
4097           ;; RFC 822 says \ and nonmatching parentheses
4098           ;; must be escaped in comments.
4099           ;; Escape every instance of ()\ ...
4100           (while (re-search-forward "[()\\]" nil 1)
4101             (replace-match "\\\\\\&" t))
4102           ;; ... then undo escaping of matching parentheses,
4103           ;; including matching nested parentheses.
4104           (goto-char fullname-start)
4105           (while (re-search-forward
4106                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
4107                   nil 1)
4108             (replace-match "\\1(\\3)" t)
4109             (goto-char fullname-start)))
4110         (insert ")")))
4111       (buffer-string))))
4112
4113 (defun message-make-sender ()
4114   "Return the \"real\" user address.
4115 This function tries to ignore all user modifications, and
4116 give as trustworthy answer as possible."
4117   (concat (user-login-name) "@" (system-name)))
4118
4119 (defun message-make-address ()
4120   "Make the address of the user."
4121   (or (message-user-mail-address)
4122       (concat (user-login-name) "@" (message-make-domain))))
4123
4124 (defun message-user-mail-address ()
4125   "Return the pertinent part of `user-mail-address'."
4126   (when user-mail-address
4127     (if (string-match " " user-mail-address)
4128         (nth 1 (std11-extract-address-components user-mail-address))
4129       user-mail-address)))
4130
4131 (defun message-make-fqdn ()
4132   "Return user's fully qualified domain name."
4133   (let ((system-name (system-name))
4134         (user-mail (message-user-mail-address)))
4135     (cond
4136      ((string-match "[^.]\\.[^.]" system-name)
4137       ;; `system-name' returned the right result.
4138       system-name)
4139      ;; Try `mail-host-address'.
4140      ((and (boundp 'mail-host-address)
4141            (stringp mail-host-address)
4142            (string-match "\\." mail-host-address))
4143       mail-host-address)
4144      ;; We try `user-mail-address' as a backup.
4145      ((and user-mail
4146            (string-match "\\." user-mail)
4147            (string-match "@\\(.*\\)\\'" user-mail))
4148       (match-string 1 user-mail))
4149      ;; Default to this bogus thing.
4150      (t
4151       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
4152
4153 (defun message-make-host-name ()
4154   "Return the name of the host."
4155   (let ((fqdn (message-make-fqdn)))
4156     (string-match "^[^.]+\\." fqdn)
4157     (substring fqdn 0 (1- (match-end 0)))))
4158
4159 (defun message-make-domain ()
4160   "Return the domain name."
4161   (or mail-host-address
4162       (message-make-fqdn)))
4163
4164 ;; Dummy to avoid byte-compile warning.
4165 (defvar mule-version)
4166 (defvar emacs-beta-version)
4167 (defvar xemacs-codename)
4168 (defvar gnus-inviolable-extended-version)
4169
4170 (defun message-make-user-agent ()
4171   "Return user-agent info if the value `message-user-agent' is non-nil. If the
4172 \"User-Agent\" field has already exist, it's value will be added in the return
4173 string."
4174   (when message-user-agent
4175     (save-excursion
4176       (goto-char (point-min))
4177       (let ((case-fold-search t)
4178             user-agent start p end)
4179         (if (re-search-forward "^User-Agent:[\t ]*" nil t)
4180             (progn
4181               (setq start (match-beginning 0)
4182                     p (match-end 0)
4183                     end (std11-field-end)
4184                     user-agent (buffer-substring-no-properties p end))
4185               (delete-region start (1+ end))
4186               (concat message-user-agent " " user-agent))
4187           message-user-agent)))))
4188
4189 (defun message-generate-headers (headers)
4190   "Prepare article HEADERS.
4191 Headers already prepared in the buffer are not modified."
4192   (save-restriction
4193     (message-narrow-to-headers)
4194     (let* ((Date (message-make-date))
4195            (Message-ID (message-make-message-id))
4196            (Organization (message-make-organization))
4197            (From (message-make-from))
4198            (Path (message-make-path))
4199            (Subject nil)
4200            (Newsgroups nil)
4201            (In-Reply-To (message-make-in-reply-to))
4202            (To nil)
4203            (Distribution (message-make-distribution))
4204            (Lines (message-make-lines))
4205            (User-Agent (message-make-user-agent))
4206            (Expires (message-make-expires))
4207            (case-fold-search t)
4208            header value elem)
4209       ;; First we remove any old generated headers.
4210       (let ((headers message-deletable-headers))
4211         (unless (buffer-modified-p)
4212           (setq headers (delq 'Message-ID (copy-sequence headers))))
4213         (while headers
4214           (goto-char (point-min))
4215           (and (re-search-forward
4216                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4217                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
4218                (message-delete-line))
4219           (pop headers)))
4220       ;; Go through all the required headers and see if they are in the
4221       ;; articles already.  If they are not, or are empty, they are
4222       ;; inserted automatically - except for Subject, Newsgroups and
4223       ;; Distribution.
4224       (while headers
4225         (goto-char (point-min))
4226         (setq elem (pop headers))
4227         (if (consp elem)
4228             (if (eq (car elem) 'optional)
4229                 (setq header (cdr elem))
4230               (setq header (car elem)))
4231           (setq header elem))
4232         (when (or (not (re-search-forward
4233                         (concat "^"
4234                                 (regexp-quote
4235                                  (downcase
4236                                   (if (stringp header)
4237                                       header
4238                                     (symbol-name header))))
4239                                 ":")
4240                         nil t))
4241                   (progn
4242                     ;; The header was found.  We insert a space after the
4243                     ;; colon, if there is none.
4244                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
4245                     ;; Find out whether the header is empty...
4246                     (looking-at "[ \t]*\n[^ \t]")))
4247           ;; So we find out what value we should insert.
4248           (setq value
4249                 (cond
4250                  ((and (consp elem) (eq (car elem) 'optional))
4251                   ;; This is an optional header.  If the cdr of this
4252                   ;; is something that is nil, then we do not insert
4253                   ;; this header.
4254                   (setq header (cdr elem))
4255                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
4256                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
4257                  ((consp elem)
4258                   ;; The element is a cons.  Either the cdr is a
4259                   ;; string to be inserted verbatim, or it is a
4260                   ;; function, and we insert the value returned from
4261                   ;; this function.
4262                   (or (and (stringp (cdr elem)) (cdr elem))
4263                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
4264                  ((and (boundp header) (symbol-value header))
4265                   ;; The element is a symbol.  We insert the value
4266                   ;; of this symbol, if any.
4267                   (symbol-value header))
4268                  ((not (message-check-element header))
4269                   ;; We couldn't generate a value for this header,
4270                   ;; so we just ask the user.
4271                   (read-from-minibuffer
4272                    (format "Empty header for %s; enter value: " header)))))
4273           ;; Finally insert the header.
4274           (when (and value
4275                      (not (equal value "")))
4276             (save-excursion
4277               (if (bolp)
4278                   (progn
4279                     ;; This header didn't exist, so we insert it.
4280                     (goto-char (point-max))
4281                     (insert (if (stringp header) header (symbol-name header))
4282                             ": " value)
4283                     (unless (bolp)
4284                       (insert "\n"))
4285                     (forward-line -1))
4286                 ;; The value of this header was empty, so we clear
4287                 ;; totally and insert the new value.
4288                 (delete-region (point) (gnus-point-at-eol))
4289                 (insert value)
4290                 (when (bolp)
4291                   (delete-char -1)))
4292               ;; Add the deletable property to the headers that require it.
4293               (and (memq header message-deletable-headers)
4294                    (progn (beginning-of-line) (looking-at "[^:]+: "))
4295                    (add-text-properties
4296                     (point) (match-end 0)
4297                     '(message-deletable t face italic) (current-buffer)))))))
4298       ;; Insert new Sender if the From is strange.
4299       (let ((from (message-fetch-field "from"))
4300             (sender (message-fetch-field "sender"))
4301             (secure-sender (message-make-sender)))
4302         (when (and from
4303                    (not (message-check-element 'sender))
4304                    (not (string=
4305                          (downcase
4306                           (cadr (std11-extract-address-components from)))
4307                          (downcase secure-sender)))
4308                    (or (null sender)
4309                        (not
4310                         (string=
4311                          (downcase
4312                           (cadr (std11-extract-address-components sender)))
4313                          (downcase secure-sender)))))
4314           (goto-char (point-min))
4315           ;; Rename any old Sender headers to Original-Sender.
4316           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
4317             (beginning-of-line)
4318             (insert "Original-")
4319             (beginning-of-line))
4320           (when (or (message-news-p)
4321                     (string-match "@.+\\.." secure-sender))
4322             (insert "Sender: " secure-sender "\n")))))))
4323
4324 (defun message-insert-courtesy-copy ()
4325   "Insert a courtesy message in mail copies of combined messages."
4326   (let (newsgroups)
4327     (save-excursion
4328       (save-restriction
4329         (message-narrow-to-headers)
4330         (when (setq newsgroups (message-fetch-field "newsgroups"))
4331           (goto-char (point-max))
4332           (insert "Posted-To: " newsgroups "\n")))
4333       (forward-line 1)
4334       (when message-courtesy-message
4335         (cond
4336          ((string-match "%s" message-courtesy-message)
4337           (insert (format message-courtesy-message newsgroups)))
4338          (t
4339           (insert message-courtesy-message)))))))
4340
4341 ;;;
4342 ;;; Setting up a message buffer
4343 ;;;
4344
4345 (defun message-fill-address (header value)
4346   (save-restriction
4347     (narrow-to-region (point) (point))
4348     (insert (capitalize (symbol-name header))
4349             ": "
4350             (if (consp value) (car value) value)
4351             "\n")
4352     (narrow-to-region (point-min) (1- (point-max)))
4353     (let (quoted last)
4354       (goto-char (point-min))
4355       (while (not (eobp))
4356         (skip-chars-forward "^,\"" (point-max))
4357         (if (or (eq (char-after) ?,)
4358                 (eobp))
4359             (when (not quoted)
4360               (if (and (> (current-column) 78)
4361                        last)
4362                   (save-excursion
4363                     (goto-char last)
4364                     (looking-at "[ \t]*")
4365                     (replace-match "\n " t t)))
4366               (setq last (1+ (point))))
4367           (setq quoted (not quoted)))
4368         (unless (eobp)
4369           (forward-char 1))))
4370     (goto-char (point-max))
4371     (widen)
4372     (forward-line 1)))
4373
4374 (defun message-fill-references (header value)
4375   (insert (capitalize (symbol-name header))
4376           ": "
4377           (std11-fill-msg-id-list-string
4378           (if (consp value) (car value) value))
4379           "\n"))
4380
4381 (defun message-fill-header (header value)
4382   (let ((begin (point))
4383         (fill-column 78)
4384         (fill-prefix " "))
4385     (insert (capitalize (symbol-name header))
4386             ": "
4387             (if (consp value) (car value) value)
4388             "\n")
4389     (save-restriction
4390       (narrow-to-region begin (point))
4391       (fill-region-as-paragraph begin (point))
4392       ;; Tapdance around looong Message-IDs.
4393       (forward-line -1)
4394       (when (looking-at "[ \t]*$")
4395         (message-delete-line))
4396       (goto-char begin)
4397       (re-search-forward ":" nil t)
4398       (when (looking-at "\n[ \t]+")
4399         (replace-match " " t t))
4400       (goto-char (point-max)))))
4401
4402 (defun message-shorten-1 (list cut surplus)
4403   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
4404   (setcdr (nthcdr (- cut 2) list)
4405           (nthcdr (+ (- cut 2) surplus 1) list)))
4406
4407 (defun message-shorten-references (header references)
4408   "Trim REFERENCES to be less than 31 Message-ID long, and fold them.
4409 If folding is disallowed, also check that the REFERENCES are less
4410 than 988 characters long, and if they are not, trim them until they are."
4411   (let ((maxcount 31)
4412         (count 0)
4413         (cut 6)
4414         refs)
4415     (with-temp-buffer
4416       (insert references)
4417       (goto-char (point-min))
4418       ;; Cons a list of valid references.
4419       (while (re-search-forward "<[^>]+>" nil t)
4420         (push (match-string 0) refs))
4421       (setq refs (nreverse refs)
4422             count (length refs)))
4423
4424     ;; If the list has more than MAXCOUNT elements, trim it by
4425     ;; removing the CUTth element and the required number of
4426     ;; elements that follow.
4427     (when (> count maxcount)
4428       (let ((surplus (- count maxcount)))
4429         (message-shorten-1 refs cut surplus)
4430         (decf count surplus)))
4431
4432     ;; If folding is disallowed, make sure the total length (including
4433     ;; the spaces between) will be less than MAXSIZE characters.
4434     ;;
4435     ;; Only disallow folding for News messages. At this point the headers
4436     ;; have not been generated, thus we use message-this-is-news directly.
4437     (when (and message-this-is-news message-cater-to-broken-inn)
4438       (let ((maxsize 988)
4439             (totalsize (+ (apply #'+ (mapcar #'length refs))
4440                           (1- count)))
4441             (surplus 0)
4442             (ptr (nthcdr (1- cut) refs)))
4443         ;; Decide how many elements to cut off...
4444         (while (> totalsize maxsize)
4445           (decf totalsize (1+ (length (car ptr))))
4446           (incf surplus)
4447           (setq ptr (cdr ptr)))
4448         ;; ...and do it.
4449         (when (> surplus 0)
4450           (message-shorten-1 refs cut surplus))))
4451
4452     ;; Finally, collect the references back into a string and insert
4453     ;; it into the buffer.
4454     (let ((refstring (mapconcat #'identity refs " ")))
4455       (if (and message-this-is-news message-cater-to-broken-inn)
4456           (insert (capitalize (symbol-name header)) ": "
4457                   refstring "\n")
4458         (message-fill-header header refstring)))))
4459
4460 (defun message-position-point ()
4461   "Move point to where the user probably wants to find it."
4462   (message-narrow-to-headers)
4463   (cond
4464    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
4465     (search-backward ":" )
4466     (widen)
4467     (forward-char 1)
4468     (if (eq (char-after) ? )
4469         (forward-char 1)
4470       (insert " ")))
4471    (t
4472     (goto-char (point-max))
4473     (widen)
4474     (forward-line 1)
4475     (unless (looking-at "$")
4476       (forward-line 2)))
4477    (sit-for 0)))
4478
4479 (defun message-buffer-name (type &optional to group)
4480   "Return a new (unique) buffer name based on TYPE and TO."
4481   (cond
4482    ;; Generate a new buffer name The Message Way.
4483    ((eq message-generate-new-buffers 'unique)
4484     (generate-new-buffer-name
4485      (concat "*" type
4486              (if to
4487                  (concat " to "
4488                          (or (car (std11-extract-address-components to))
4489                              to) "")
4490                "")
4491              (if (and group (not (string= group ""))) (concat " on " group) "")
4492              "*")))
4493    ;; Check whether `message-generate-new-buffers' is a function,
4494    ;; and if so, call it.
4495    ((message-functionp message-generate-new-buffers)
4496     (funcall message-generate-new-buffers type to group))
4497    ((eq message-generate-new-buffers 'unsent)
4498     (generate-new-buffer-name
4499      (concat "*unsent " type
4500              (if to
4501                  (concat " to "
4502                          (or (car (mail-extract-address-components to))
4503                              to) "")
4504                "")
4505              (if (and group (not (string= group ""))) (concat " on " group) "")
4506              "*")))
4507    ;; Use standard name.
4508    (t
4509     (format "*%s message*" type))))
4510
4511 (defmacro message-pop-to-buffer-1 (buffer)
4512   `(if pop-up-frames
4513        (let (special-display-buffer-names
4514              special-display-regexps
4515              same-window-buffer-names
4516              same-window-regexps)
4517          (pop-to-buffer ,buffer))
4518      (pop-to-buffer ,buffer)))
4519
4520 (defun message-pop-to-buffer (name)
4521   "Pop to buffer NAME, and warn if it already exists and is modified."
4522   (let ((buffer (get-buffer name))
4523         (pop-up-frames (and (or (static-if (featurep 'xemacs)
4524                                     (device-on-window-system-p)
4525                                   window-system)
4526                                 (>= emacs-major-version 20))
4527                             message-use-multi-frames)))
4528     (if (and buffer
4529              (buffer-name buffer))
4530         (progn
4531           (message-pop-to-buffer-1 buffer)
4532           (when (and (buffer-modified-p)
4533                      (not (y-or-n-p
4534                            "Message already being composed; erase? ")))
4535             (error "Message being composed")))
4536       (message-pop-to-buffer-1 name))
4537     (erase-buffer)
4538     (message-mode)
4539     (when pop-up-frames
4540       (set (make-local-variable 'message-original-frame) (selected-frame)))))
4541
4542 (defun message-do-send-housekeeping ()
4543   "Kill old message buffers."
4544   ;; We might have sent this buffer already.  Delete it from the
4545   ;; list of buffers.
4546   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
4547   (while (and message-max-buffers
4548               message-buffer-list
4549               (>= (length message-buffer-list) message-max-buffers))
4550     ;; Kill the oldest buffer -- unless it has been changed.
4551     (let ((buffer (pop message-buffer-list)))
4552       (when (and (buffer-name buffer)
4553                  (not (buffer-modified-p buffer)))
4554         (kill-buffer buffer))))
4555   ;; Rename the buffer.
4556   (if message-send-rename-function
4557       (funcall message-send-rename-function)
4558     (when (string-match "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*"
4559                         (buffer-name))
4560       (let ((name (match-string 2 (buffer-name)))
4561             to group)
4562         (if (not (or (string-equal name "mail")
4563                      (string-equal name "news")))
4564             (setq name (concat "*sent " name "*"))
4565           (setq to (message-fetch-field "to"))
4566           (setq group (message-fetch-field "newsgroups"))
4567           (setq name
4568                 (cond
4569                  (to (concat "*sent mail to "
4570                              (or (car (mail-extract-address-components to))
4571                                  to) "*"))
4572                  ((and group (not (string= group "")))
4573                   (concat "*sent news on " group "*"))
4574                  (t "*sent mail*"))))
4575         (unless (string-equal name (buffer-name))
4576           (rename-buffer name t)))))
4577   ;; Push the current buffer onto the list.
4578   (when message-max-buffers
4579     (setq message-buffer-list
4580           (nconc message-buffer-list (list (current-buffer))))))
4581
4582 (defun message-mail-user-agent ()
4583   (let ((mua (cond
4584               ((not message-mail-user-agent) nil)
4585               ((eq message-mail-user-agent t) mail-user-agent)
4586               (t message-mail-user-agent))))
4587     (if (memq mua '(message-user-agent gnus-user-agent))
4588         nil
4589       mua)))
4590
4591 (defun message-setup (headers &optional replybuffer actions switch-function)
4592   (let ((mua (message-mail-user-agent))
4593         subject to field yank-action)
4594     (if (not (and message-this-is-mail mua))
4595         (message-setup-1 headers replybuffer actions)
4596       (if replybuffer
4597           (setq yank-action (list 'insert-buffer replybuffer)))
4598       (setq headers (copy-sequence headers))
4599       (setq field (assq 'Subject headers))
4600       (when field
4601         (setq subject (cdr field))
4602         (setq headers (delq field headers)))
4603       (setq field (assq 'To headers))
4604       (when field
4605         (setq to (cdr field))
4606         (setq headers (delq field headers)))
4607       (let ((mail-user-agent mua))
4608         (compose-mail to subject
4609                       (mapcar (lambda (item)
4610                                 (cons
4611                                  (format "%s" (car item))
4612                                  (cdr item)))
4613                               headers)
4614                       nil switch-function yank-action actions)))))
4615
4616 ;;;(defvar mc-modes-alist)
4617 (defun message-setup-1 (headers &optional replybuffer actions)
4618 ;;;   (when (and (boundp 'mc-modes-alist)
4619 ;;;          (not (assq 'message-mode mc-modes-alist)))
4620 ;;;     (push '(message-mode (encrypt . mc-encrypt-message)
4621 ;;;                      (sign . mc-sign-message))
4622 ;;;       mc-modes-alist))
4623   (when actions
4624     (setq message-send-actions actions))
4625   (setq message-reply-buffer
4626         (or (message-get-parameter 'reply-buffer)
4627             replybuffer))
4628   (goto-char (point-min))
4629   ;; Insert all the headers.
4630   (mail-header-format
4631    (let ((h headers)
4632          (alist message-header-format-alist))
4633      (while h
4634        (unless (assq (caar h) message-header-format-alist)
4635          (push (list (caar h)) alist))
4636        (pop h))
4637      alist)
4638    headers)
4639   (delete-region (point) (progn (forward-line -1) (point)))
4640   (when message-default-headers
4641     (insert message-default-headers)
4642     (or (bolp) (insert ?\n)))
4643   (put-text-property
4644    (point)
4645    (progn
4646      (insert mail-header-separator "\n")
4647      (1- (point)))
4648    'read-only nil)
4649   (forward-line -1)
4650   (when (message-news-p)
4651     (when message-default-news-headers
4652       (insert message-default-news-headers)
4653       (or (bolp) (insert ?\n)))
4654     (when message-generate-headers-first
4655       (message-generate-headers
4656        (delq 'Lines
4657              (delq 'Subject
4658                    (copy-sequence message-required-news-headers))))))
4659   (when (message-mail-p)
4660     (when message-default-mail-headers
4661       (insert message-default-mail-headers)
4662       (or (bolp) (insert ?\n)))
4663     (when message-generate-headers-first
4664       (message-generate-headers
4665        (delq 'Lines
4666              (delq 'Subject
4667                    (copy-sequence message-required-mail-headers))))))
4668   (run-hooks 'message-signature-setup-hook)
4669   (message-insert-signature)
4670   (save-restriction
4671     (message-narrow-to-headers)
4672     (if message-alternative-emails
4673         (message-use-alternative-email-as-from))
4674     (run-hooks 'message-header-setup-hook))
4675   (set-buffer-modified-p nil)
4676   (setq buffer-undo-list nil)
4677   (run-hooks 'message-setup-hook)
4678   (message-position-point)
4679   (undo-boundary))
4680
4681 (defun message-set-auto-save-file-name ()
4682   "Associate the message buffer with a file in the drafts directory."
4683   (when message-auto-save-directory
4684     (unless (file-directory-p
4685              (directory-file-name message-auto-save-directory))
4686       (gnus-make-directory message-auto-save-directory))
4687     (if (gnus-alive-p)
4688         (setq message-draft-article
4689               (nndraft-request-associate-buffer "drafts"))
4690       (setq buffer-file-name (expand-file-name
4691                               (if (eq system-type 'windows-nt)
4692                                   "message"
4693                                 "*message*")
4694                               message-auto-save-directory))
4695       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
4696     (clear-visited-file-modtime)
4697     (static-if (boundp 'MULE)
4698         (set-file-coding-system message-draft-coding-system)
4699       (setq buffer-file-coding-system message-draft-coding-system))))
4700
4701 (defun message-disassociate-draft ()
4702   "Disassociate the message buffer from the drafts directory."
4703   (when message-draft-article
4704     (nndraft-request-expire-articles
4705      (list message-draft-article) "drafts" nil t)))
4706
4707 (defun message-insert-headers ()
4708   "Generate the headers for the article."
4709   (interactive)
4710   (save-excursion
4711     (save-restriction
4712       (message-narrow-to-headers)
4713       (when (message-news-p)
4714         (message-generate-headers
4715          (delq 'Lines
4716                (delq 'Subject
4717                      (copy-sequence message-required-news-headers)))))
4718       (when (message-mail-p)
4719         (message-generate-headers
4720          (delq 'Lines
4721                (delq 'Subject
4722                      (copy-sequence message-required-mail-headers))))))))
4723
4724 \f
4725
4726 ;;;
4727 ;;; Commands for interfacing with message
4728 ;;;
4729
4730 ;;;###autoload
4731 (defun message-mail (&optional to subject
4732                                other-headers continue switch-function
4733                                yank-action send-actions)
4734   "Start editing a mail message to be sent.
4735 OTHER-HEADERS is an alist of header/value pairs."
4736   (interactive)
4737   (let ((message-this-is-mail t) replybuffer)
4738     (unless (message-mail-user-agent)
4739       (message-pop-to-buffer (message-buffer-name "mail" to)))
4740     ;; FIXME: message-mail should do something if YANK-ACTION is not
4741     ;; insert-buffer.
4742     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
4743          (setq replybuffer (nth 1 yank-action)))
4744     (message-setup
4745      (nconc
4746       `((To . ,(or to "")) (Subject . ,(or subject "")))
4747       (when other-headers other-headers))
4748      replybuffer)
4749     ;; FIXME: Should return nil if failure.
4750     t))
4751
4752 ;;;###autoload
4753 (defun message-news (&optional newsgroups subject)
4754   "Start editing a news article to be sent."
4755   (interactive)
4756   (let ((message-this-is-news t))
4757     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
4758     (message-setup `((Newsgroups . ,(or newsgroups ""))
4759                      (Subject . ,(or subject ""))))))
4760
4761 (defun message-get-reply-headers (wide &optional to-address)
4762   (let (follow-to mct never-mct from to cc reply-to mrt mft)
4763     ;; Find all relevant headers we need.
4764     (setq from (message-fetch-field "from")
4765           to (message-fetch-field "to")
4766           cc (message-fetch-field "cc")
4767           mct (when message-use-mail-copies-to
4768                 (message-fetch-field "mail-copies-to"))
4769           reply-to (message-fetch-field "reply-to")
4770           mrt (when message-use-mail-reply-to
4771                 (message-fetch-field "mail-reply-to"))
4772           mft (when (and (not (or to-address mrt reply-to))
4773                          (or message-use-followup-to
4774                              message-use-mail-followup-to))
4775                 (message-fetch-field "mail-followup-to")))
4776
4777     ;; Handle special values of Mail-Copies-To.
4778     (when mct
4779       (cond
4780        ((and (or (equal (downcase mct) "never")
4781                  (equal (downcase mct) "nobody")))
4782         (when (or (not (eq message-use-mail-copies-to 'ask))
4783                   (message-y-or-n-p
4784                    (concat "Obey Mail-Copies-To: never? ") t "\
4785 You should normally obey the Mail-Copies-To: header.
4786
4787         `Mail-Copies-To: " mct "'
4788 directs you not to send your response to the author."))
4789           (setq never-mct t))
4790         (setq mct nil))
4791        ((and (or (equal (downcase mct) "always")
4792                  (equal (downcase mct) "poster")))
4793         (if (or (not (eq message-use-mail-copies-to 'ask))
4794                 (message-y-or-n-p
4795                  (concat "Obey Mail-Copies-To: always? ") t "\
4796 You should normally obey the Mail-Copies-To: header.
4797
4798         `Mail-Copies-To: " mct "'
4799 sends a copy of your response to the author."))
4800             (setq mct (or mrt reply-to from))
4801           (setq mct nil)))
4802        ((and (eq message-use-mail-copies-to 'ask)
4803              (not (message-y-or-n-p
4804                    (concat "Obey Mail-Copies-To: " mct " ? ") t "\
4805 You should normally obey the Mail-Copies-To: header.
4806
4807         `Mail-Copies-To: " mct "'
4808 sends a copy of your response to " (if (string-match "," mct)
4809                                        "the specified addresses"
4810                                      "that address") ".")))
4811         (setq mct nil))))
4812
4813     ;; Handle Mail-Followup-To.
4814     (when (and mft
4815                (eq (or message-use-followup-to
4816                        message-use-mail-followup-to) 'ask)
4817                (not (message-y-or-n-p
4818                      (concat "Obey Mail-Followup-To: " mft "? ") t "\
4819 You should normally obey the Mail-Followup-To: header.
4820
4821         `Mail-Followup-To: " mft "'
4822 directs your response to " (if (string-match "," mft)
4823                                "the specified addresses"
4824                              "that address only") ".
4825
4826 A typical situation where Mail-Followup-To is used is when the author thinks
4827 that further discussion should take place only in "
4828                              (if (string-match "," mft)
4829                                  "the specified mailing lists"
4830                                "that mailing list") ".")))
4831       (setq mft nil))
4832
4833     (if (and (not mft)
4834              (or (not wide)
4835                  to-address))
4836         (progn
4837           (setq follow-to (list (cons 'To
4838                                       (or to-address mrt reply-to mft from))))
4839           (when (and wide mct
4840                      (not (member (cons 'To mct) follow-to)))
4841             (push (cons 'Cc mct) follow-to)))
4842       (let (ccalist)
4843         (save-excursion
4844           (message-set-work-buffer)
4845           (if (and mft
4846                    message-use-followup-to
4847                    (or (not (eq message-use-followup-to 'ask))
4848                        (message-y-or-n-p "Obey Mail-Followup-To? " t "\
4849 You should normally obey the Mail-Followup-To: header.  In this
4850 article, it has the value of
4851
4852 " mft "
4853
4854 which directs your response to " (if (string-match "," mft)
4855                                      "the specified addresses"
4856                                    "that address only") ".
4857
4858 If a message is posted to several mailing lists, Mail-Followup-To is
4859 often used to direct the following discussion to one list only,
4860 because discussions that are spread over several lists tend to be
4861 fragmented and very difficult to follow.
4862
4863 Also, some source/announcement lists are not indented for discussion;
4864 responses here are directed to other addresses.")))
4865               (insert mft)
4866             (unless never-mct
4867               (insert (or mrt reply-to from "")))
4868             (insert (if to (concat (if (bolp) "" ", ") to) ""))
4869             (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
4870             (insert (if cc (concat (if (bolp) "" ", ") cc) "")))
4871           (goto-char (point-min))
4872           (while (re-search-forward "[ \t]+" nil t)
4873             (replace-match " " t t))
4874           ;; Remove addresses that match `rmail-dont-reply-to-names'.
4875           (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
4876             (insert (prog1 (rmail-dont-reply-to (buffer-string))
4877                       (erase-buffer))))
4878           (goto-char (point-min))
4879           ;; Perhaps "Mail-Copies-To: never" removed the only address?
4880           (when (eobp)
4881             (insert (or mrt reply-to from "")))
4882           (setq ccalist
4883                 (mapcar
4884                  (lambda (addr)
4885                    (cons (mail-strip-quoted-names addr) addr))
4886                  (message-tokenize-header (buffer-string))))
4887           (let ((s ccalist))
4888             (while s
4889               (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
4890         (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
4891         (when ccalist
4892           (let ((ccs (cons 'Cc (mapconcat
4893                                 (lambda (addr) (cdr addr)) ccalist ", "))))
4894             (when (string-match "^ +" (cdr ccs))
4895               (setcdr ccs (substring (cdr ccs) (match-end 0))))
4896             (push ccs follow-to)))))
4897     follow-to))
4898
4899 ;;;###autoload
4900 (defun message-reply (&optional to-address wide)
4901   "Start editing a reply to the article in the current buffer."
4902   (interactive)
4903   (require 'gnus-sum)                   ; for gnus-list-identifiers
4904   (let ((cur (current-buffer))
4905         from subject date
4906         references message-id follow-to
4907         (inhibit-point-motion-hooks t)
4908         (message-this-is-mail t)
4909         gnus-warning in-reply-to)
4910     (save-restriction
4911       (message-narrow-to-head-1)
4912       ;; Allow customizations to have their say.
4913       (if (not wide)
4914           ;; This is a regular reply.
4915           (when (message-functionp message-reply-to-function)
4916             (save-excursion
4917               (setq follow-to (funcall message-reply-to-function))))
4918         ;; This is a followup.
4919         (when (message-functionp message-wide-reply-to-function)
4920           (save-excursion
4921             (setq follow-to
4922                   (funcall message-wide-reply-to-function)))))
4923       (setq message-id (message-fetch-field "message-id" t)
4924             references (message-fetch-field "references")
4925             date (message-fetch-field "date")
4926             from (message-fetch-field "from")
4927             subject (or (message-fetch-field "subject") "none"))
4928       (when gnus-list-identifiers
4929         (setq subject (message-strip-list-identifiers subject)))
4930       (setq subject (message-make-followup-subject subject))
4931
4932       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
4933                  (string-match "<[^>]+>" gnus-warning))
4934         (setq message-id (match-string 0 gnus-warning)))
4935
4936       (unless follow-to
4937         (setq follow-to (message-get-reply-headers wide to-address)))
4938
4939       ;; Get the references from "In-Reply-To" field if there were
4940       ;; no references and "In-Reply-To" field looks promising.
4941       (unless references
4942         (when (and (setq in-reply-to (message-fetch-field "in-reply-to"))
4943                    (string-match "<[^>]+>" in-reply-to))
4944           (setq references (match-string 0 in-reply-to)))))
4945
4946     (unless (message-mail-user-agent)
4947       (message-pop-to-buffer
4948        (message-buffer-name
4949         (if wide "wide reply" "reply") from
4950         (if wide to-address nil))))
4951
4952     (setq message-reply-headers
4953           (make-full-mail-header-from-decoded-header
4954            0 subject from date message-id references 0 0 ""))
4955
4956     (message-setup
4957      `((Subject . ,subject)
4958        ,@follow-to
4959        ,@(if (or references message-id)
4960              `((References . ,(concat (or references "") (and references " ")
4961                                       (or message-id ""))))
4962            nil))
4963      cur)))
4964
4965 ;;;###autoload
4966 (defun message-wide-reply (&optional to-address)
4967   "Make a \"wide\" reply to the message in the current buffer."
4968   (interactive)
4969   (message-reply to-address t))
4970
4971 ;;;###autoload
4972 (defun message-followup (&optional to-newsgroups)
4973   "Follow up to the message in the current buffer.
4974 If TO-NEWSGROUPS, use that as the new Newsgroups line."
4975   (interactive)
4976   (require 'gnus-sum)                   ; for gnus-list-identifiers
4977   (let ((cur (current-buffer))
4978         from subject date reply-to mrt mct mft
4979         references message-id follow-to
4980         (inhibit-point-motion-hooks t)
4981         (message-this-is-news t)
4982         followup-to distribution newsgroups gnus-warning posted-to)
4983     (save-restriction
4984       (message-narrow-to-head)
4985       (when (message-functionp message-followup-to-function)
4986         (setq follow-to
4987               (funcall message-followup-to-function)))
4988       (setq from (message-fetch-field "from")
4989             date (message-fetch-field "date")
4990             subject (or (message-fetch-field "subject") "none")
4991             references (message-fetch-field "references")
4992             message-id (message-fetch-field "message-id" t)
4993             followup-to (message-fetch-field "followup-to")
4994             newsgroups (message-fetch-field "newsgroups")
4995             posted-to (message-fetch-field "posted-to")
4996             reply-to (message-fetch-field "reply-to")
4997             mrt (when message-use-mail-reply-to
4998                   (message-fetch-field "mail-reply-to"))
4999             distribution (message-fetch-field "distribution")
5000             mct (when message-use-mail-copies-to
5001                   (message-fetch-field "mail-copies-to"))
5002             mft (when (or message-use-followup-to
5003                           message-use-mail-followup-to)
5004                   (message-fetch-field "mail-followup-to")))
5005       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
5006                  (string-match "<[^>]+>" gnus-warning))
5007         (setq message-id (match-string 0 gnus-warning)))
5008       ;; Remove bogus distribution.
5009       (when (and (stringp distribution)
5010                  (let ((case-fold-search t))
5011                    (string-match "world" distribution)))
5012         (setq distribution nil))
5013       (if gnus-list-identifiers
5014           (setq subject (message-strip-list-identifiers subject)))
5015       (setq subject (message-make-followup-subject subject))
5016       (widen))
5017
5018     ;; Handle special values of Mail-Copies-To.
5019     (when mct
5020       (cond
5021        ((and (or (equal (downcase mct) "never")
5022                  (equal (downcase mct) "nobody")))
5023         (setq mct nil))
5024        ((and (or (equal (downcase mct) "always")
5025                  (equal (downcase mct) "poster")))
5026         (if (or (not (eq message-use-mail-copies-to 'ask))
5027                 (message-y-or-n-p
5028                  (concat "Obey Mail-Copies-To: always? ") t "\
5029 You should normally obey the Mail-Copies-To: header.
5030
5031         `Mail-Copies-To: " mct "'
5032 sends a copy of your response to the author."))
5033             (setq mct (or mrt reply-to from))
5034           (setq mct nil)))
5035        ((and (eq message-use-mail-copies-to 'ask)
5036              (not
5037               (message-y-or-n-p
5038                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
5039 You should normally obey the Mail-Copies-To: header.
5040
5041         `Mail-Copies-To: " mct "'
5042 sends a copy of your response to " (if (string-match "," mct)
5043                                        "the specified addresses"
5044                                      "that address") ".")))
5045         (setq mct nil))))
5046
5047     (unless follow-to
5048       (cond
5049        (to-newsgroups (setq follow-to (list (cons 'Newsgroups to-newsgroups))))
5050        ;; Handle Followup-To.
5051        (followup-to
5052         (cond
5053          ((equal (downcase followup-to) "poster")
5054           (if (or (and followup-to (eq message-use-followup-to 'use))
5055                   (message-y-or-n-p "Obey Followup-To: poster? " t "\
5056 You should normally obey the Followup-To: header.
5057
5058         `Followup-To: poster'
5059 sends your response via e-mail instead of news.
5060
5061 A typical situation where `Followup-To: poster' is used is when the author
5062 does not read the newsgroup, so he wouldn't see any replies sent to it."))
5063               (setq message-this-is-news nil
5064                     distribution nil
5065                     follow-to (list (cons 'To (or mrt reply-to from ""))))
5066             (setq follow-to (list (cons 'Newsgroups newsgroups)))))
5067          (t
5068           (if (or (equal followup-to newsgroups)
5069                   (not (and followup-to (eq message-use-followup-to 'ask)))
5070                   (message-y-or-n-p
5071                    (concat "Obey Followup-To: " followup-to "? ") t "\
5072 You should normally obey the Followup-To: header.
5073
5074         `Followup-To: " followup-to "'
5075 directs your response to " (if (string-match "," followup-to)
5076                                "the specified newsgroups"
5077                              "that newsgroup only") ".
5078
5079 If a message is posted to several newsgroups, Followup-To is often
5080 used to direct the following discussion to one newsgroup only,
5081 because discussions that are spread over several newsgroup tend to
5082 be fragmented and very difficult to follow.
5083
5084 Also, some source/announcement newsgroups are not indented for discussion;
5085 responses here are directed to other newsgroups."))
5086               (setq follow-to (list (cons 'Newsgroups followup-to)))
5087             (setq follow-to (list (cons 'Newsgroups newsgroups)))))))
5088        ;; Handle Mail-Followup-To, followup via e-mail.
5089        ((and mft
5090              (or (not (eq (or message-use-followup-to
5091                               message-use-mail-followup-to) 'ask))
5092                  (message-y-or-n-p
5093                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
5094 You should normally obey the Mail-Followup-To: header.
5095
5096         `Mail-Followup-To: " mft "'
5097 directs your response to " (if (string-match "," mft)
5098                                "the specified addresses"
5099                              "that address only") " instead of news.
5100
5101 A typical situation where Mail-Followup-To is used is when the author thinks
5102 that further discussion should take place only in "
5103                              (if (string-match "," mft)
5104                                  "the specified mailing lists"
5105                                "that mailing list") ".")))
5106         (setq message-this-is-news nil
5107               distribution nil
5108               follow-to (list (cons 'To mft))))
5109        (posted-to (setq follow-to (list (cons 'Newsgroups posted-to))))
5110        (t
5111         (setq follow-to (list (cons 'Newsgroups newsgroups))))))
5112
5113     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
5114
5115     (message-setup
5116      `((Subject . ,subject)
5117        ,@follow-to
5118        ,@(and mct (list (cons 'Cc mct)))
5119        ,@(and distribution (list (cons 'Distribution distribution)))
5120        ,@(if (or references message-id)
5121              `((References . ,(concat (or references "") (and references " ")
5122                                       (or message-id ""))))))
5123      cur)
5124
5125     (setq message-reply-headers
5126           (make-full-mail-header-from-decoded-header
5127            0 subject from date message-id references 0 0 ""))))
5128
5129 ;;;###autoload
5130 (defun message-cancel-news (&optional arg)
5131   "Cancel an article you posted.
5132 If ARG, allow editing of the cancellation message."
5133   (interactive "P")
5134   (unless (message-news-p)
5135     (error "This is not a news article; canceling is impossible"))
5136   (let (from newsgroups message-id distribution buf sender)
5137     (save-excursion
5138       ;; Get header info from original article.
5139       (save-restriction
5140         (message-narrow-to-head-1)
5141         (setq from (message-fetch-field "from")
5142               sender (message-fetch-field "sender")
5143               newsgroups (message-fetch-field "newsgroups")
5144               message-id (message-fetch-field "message-id" t)
5145               distribution (message-fetch-field "distribution")))
5146       ;; Make sure that this article was written by the user.
5147       (unless (or (message-gnksa-enable-p 'cancel-messages)
5148                   (and sender
5149                        (string-equal
5150                         (downcase sender)
5151                         (downcase (message-make-sender))))
5152                   (string-equal
5153                    (downcase (cadr (std11-extract-address-components from)))
5154                    (downcase (cadr (std11-extract-address-components
5155                                     (message-make-from))))))
5156         (error "This article is not yours"))
5157       (when (yes-or-no-p "Do you really want to cancel this article? ")
5158         ;; Make control message.
5159         (if arg
5160             (message-news)
5161           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
5162         (erase-buffer)
5163         (insert "Newsgroups: " newsgroups "\n"
5164                 "From: " from "\n"
5165                 "Subject: cmsg cancel " message-id "\n"
5166                 "Control: cancel " message-id "\n"
5167                 (if distribution
5168                     (concat "Distribution: " distribution "\n")
5169                   "")
5170                 mail-header-separator "\n"
5171                 message-cancel-message)
5172         (run-hooks 'message-cancel-hook)
5173         (unless arg
5174           (message "Canceling your article...")
5175           (if (let ((message-syntax-checks
5176                      'dont-check-for-anything-just-trust-me)
5177                     (message-encoding-buffer (current-buffer))
5178                     (message-edit-buffer (current-buffer)))
5179                 (message-send-news))
5180               (message "Canceling your article...done"))
5181           (kill-buffer buf))))))
5182
5183 (defun message-supersede-setup-for-mime-edit ()
5184   (set (make-local-variable 'message-setup-hook) nil)
5185   (mime-edit-again))
5186
5187 ;;;###autoload
5188 (defun message-supersede ()
5189   "Start composing a message to supersede the current message.
5190 This is done simply by taking the old article and adding a Supersedes
5191 header line with the old Message-ID."
5192   (interactive)
5193   (let ((cur (current-buffer))
5194         (sender (message-fetch-field "sender"))
5195         (from (message-fetch-field "from")))
5196     ;; Check whether the user owns the article that is to be superseded.
5197     (unless (or (message-gnksa-enable-p 'cancel-messages)
5198                 (and sender
5199                      (string-equal
5200                       (downcase sender)
5201                       (downcase (message-make-sender))))
5202                 (string-equal
5203                  (downcase (cadr (std11-extract-address-components from)))
5204                  (downcase (cadr (std11-extract-address-components
5205                                   (message-make-from))))))
5206       (error "This article is not yours"))
5207     ;; Get a normal message buffer.
5208     (message-pop-to-buffer (message-buffer-name "supersede"))
5209     (insert-buffer-substring cur)
5210     (message-narrow-to-head-1)
5211     ;; Remove unwanted headers.
5212     (when message-ignored-supersedes-headers
5213       (message-remove-header message-ignored-supersedes-headers t))
5214     (goto-char (point-min))
5215     (if (not (re-search-forward "^Message-ID: " nil t))
5216         (error "No Message-ID in this article")
5217       (replace-match "Supersedes: " t t))
5218     (goto-char (point-max))
5219     (insert mail-header-separator)
5220     (widen)
5221     (when message-supersede-setup-function
5222       (funcall message-supersede-setup-function))
5223     (run-hooks 'message-supersede-setup-hook)
5224     (goto-char (point-min))
5225     (search-forward (concat "\n" mail-header-separator "\n") nil t)))
5226
5227 ;;;###autoload
5228 (defun message-recover ()
5229   "Reread contents of current buffer from its last auto-save file."
5230   (interactive)
5231   (let ((file-name (make-auto-save-file-name)))
5232     (cond ((save-window-excursion
5233              (if (not (eq system-type 'vax-vms))
5234                  (with-output-to-temp-buffer "*Directory*"
5235                    (with-current-buffer standard-output
5236                      (fundamental-mode)) ; for Emacs 20.4+
5237                    (buffer-disable-undo standard-output)
5238                    (let ((default-directory "/"))
5239                      (call-process
5240                       "ls" nil standard-output nil "-l" file-name))))
5241              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
5242            (let ((buffer-read-only nil))
5243              (erase-buffer)
5244              (insert-file-contents file-name nil)))
5245           (t (error "message-recover cancelled")))))
5246
5247 ;;; Washing Subject:
5248
5249 (defun message-wash-subject (subject)
5250   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
5251 Previous forwarders, replyers, etc. may add it."
5252   (with-temp-buffer
5253     (insert-string subject)
5254     (goto-char (point-min))
5255     ;; strip Re/Fwd stuff off the beginning
5256     (while (re-search-forward
5257             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
5258       (replace-match ""))
5259
5260     ;; and gnus-style forwards [foo@bar.com] subject
5261     (goto-char (point-min))
5262     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
5263       (replace-match ""))
5264
5265     ;; and off the end
5266     (goto-char (point-max))
5267     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
5268       (replace-match ""))
5269
5270     ;; and finally, any whitespace that was left-over
5271     (goto-char (point-min))
5272     (while (re-search-forward "^[ \t]+" nil t)
5273       (replace-match ""))
5274     (goto-char (point-max))
5275     (while (re-search-backward "[ \t]+$" nil t)
5276       (replace-match ""))
5277
5278     (buffer-string)))
5279
5280 ;;; Forwarding messages.
5281
5282 (defvar message-forward-decoded-p nil
5283   "Non-nil means the original message is decoded.")
5284
5285 (defun message-forward-subject-author-subject (subject)
5286   "Generate a SUBJECT for a forwarded message.
5287 The form is: [Source] Subject, where if the original message was mail,
5288 Source is the sender, and if the original message was news, Source is
5289 the list of newsgroups is was posted to."
5290   (concat "["
5291           (if (message-news-p)
5292               (or (message-fetch-field "newsgroups")
5293                   "(nowhere)")
5294             (let ((from (message-fetch-field "from")))
5295               (if from
5296                   (nnheader-decode-from from)
5297                 "(nobody)")))
5298           "] " subject))
5299
5300 (defun message-forward-subject-fwd (subject)
5301   "Generate a SUBJECT for a forwarded message.
5302 The form is: Fwd: Subject, where Subject is the original subject of
5303 the message."
5304   (concat "Fwd: " subject))
5305
5306 (defun message-make-forward-subject ()
5307   "Return a Subject header suitable for the message in the current buffer."
5308   (save-excursion
5309     (save-restriction
5310       (message-narrow-to-head-1)
5311       (let ((funcs message-make-forward-subject-function)
5312             (subject (message-fetch-field "Subject")))
5313         (setq subject
5314               (if subject
5315                   (if message-forward-decoded-p
5316                       subject
5317                     (nnheader-decode-subject subject))
5318                 ""))
5319         (if message-wash-forwarded-subjects
5320             (setq subject (message-wash-subject subject)))
5321         ;; Make sure funcs is a list.
5322         (and funcs
5323              (not (listp funcs))
5324              (setq funcs (list funcs)))
5325         ;; Apply funcs in order, passing subject generated by previous
5326         ;; func to the next one.
5327         (while funcs
5328           (when (message-functionp (car funcs))
5329             (setq subject (funcall (car funcs) subject)))
5330           (setq funcs (cdr funcs)))
5331         subject))))
5332
5333 ;;;###autoload
5334 (defun message-forward (&optional news)
5335   "Forward the current message via mail.
5336 Optional NEWS will use news to forward instead of mail."
5337   (interactive "P")
5338   (let ((cur (current-buffer))
5339         (subject (message-make-forward-subject))
5340         art-beg)
5341     (if news
5342         (message-news nil subject)
5343       (message-mail nil subject))
5344     ;; Put point where we want it before inserting the forwarded
5345     ;; message.
5346     (if message-forward-before-signature
5347         (message-goto-body)
5348       (goto-char (point-max)))
5349     ;; Make sure we're at the start of the line.
5350     (unless (bolp)
5351       (insert "\n"))
5352     ;; Narrow to the area we are to insert.
5353     (narrow-to-region (point) (point))
5354     ;; Insert the separators and the forwarded buffer.
5355     (insert message-forward-start-separator)
5356     (setq art-beg (point))
5357     (insert-buffer-substring cur)
5358     (goto-char (point-max))
5359     (insert message-forward-end-separator)
5360     (set-text-properties (point-min) (point-max) nil)
5361     ;; Remove all unwanted headers.
5362     (goto-char art-beg)
5363     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
5364                                   (1- (point))
5365                                 (point)))
5366     (goto-char (point-min))
5367     (message-remove-header message-included-forward-headers t nil t)
5368     (widen)
5369     (message-position-point)))
5370
5371 ;;;###autoload
5372 (defun message-resend (address)
5373   "Resend the current article to ADDRESS."
5374   (interactive
5375    (list (message-read-from-minibuffer "Resend message to: ")))
5376   (message "Resending message to %s..." address)
5377   (save-excursion
5378     (let ((cur (current-buffer))
5379           beg)
5380       ;; We first set up a normal mail buffer.
5381       (unless (message-mail-user-agent)
5382         (set-buffer (get-buffer-create " *message resend*"))
5383         (erase-buffer)
5384         (let ((message-this-is-mail t)
5385               ;; avoid to turn-on-mime-edit
5386               message-setup-hook)
5387           (message-setup `((To . ,address)))))
5388       ;; Insert our usual headers.
5389       (message-generate-headers '(From Date To))
5390       (message-narrow-to-headers)
5391       ;; Rename them all to "Resent-*".
5392       (while (re-search-forward "^[A-Za-z]" nil t)
5393         (forward-char -1)
5394         (insert "Resent-"))
5395       (widen)
5396       (forward-line)
5397       (delete-region (point) (point-max))
5398       (setq beg (point))
5399       ;; Insert the message to be resent.
5400       (insert-buffer-substring cur)
5401       (goto-char (point-min))
5402       (search-forward "\n\n")
5403       (forward-char -1)
5404       (save-restriction
5405         (narrow-to-region beg (point))
5406         (message-remove-header message-ignored-resent-headers t)
5407         (goto-char (point-max)))
5408       (insert mail-header-separator)
5409       ;; Rename all old ("Also-")Resent headers.
5410       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
5411         (beginning-of-line)
5412         (insert "Also-"))
5413       ;; Quote any "From " lines at the beginning.
5414       (goto-char beg)
5415       (when (looking-at "From ")
5416         (replace-match "X-From-Line: "))
5417       ;; Send it.
5418       (let ((message-encoding-buffer (current-buffer))
5419             (message-edit-buffer (current-buffer)))
5420         (let (message-required-mail-headers)
5421           (message-send-mail)))
5422       (kill-buffer (current-buffer)))
5423     (message "Resending message to %s...done" address)))
5424
5425 (defun message-bounce-setup-for-mime-edit ()
5426   (set (make-local-variable 'message-setup-hook) nil)
5427   (mime-edit-again))
5428
5429 ;;;###autoload
5430 (defun message-bounce ()
5431   "Re-mail the current message.
5432 This only makes sense if the current message is a bounce message that
5433 contains some mail you have written which has been bounced back to
5434 you."
5435   (interactive)
5436   (let ((cur (current-buffer))
5437         boundary)
5438     (message-pop-to-buffer (message-buffer-name "bounce"))
5439     (insert-buffer-substring cur)
5440     (undo-boundary)
5441     (message-narrow-to-head)
5442     (if (and (message-fetch-field "MIME-Version")
5443              (setq boundary (message-fetch-field "Content-Type")))
5444         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
5445             (setq boundary (concat (match-string 1 boundary) " *\n"
5446                                    "Content-Type: message/rfc822"))
5447           (setq boundary nil)))
5448     (widen)
5449     (goto-char (point-min))
5450     (search-forward "\n\n" nil t)
5451     (or (and boundary
5452              (re-search-forward boundary nil t)
5453              (forward-line 2))
5454         (and (re-search-forward message-unsent-separator nil t)
5455              (forward-line 1))
5456         (re-search-forward "^Return-Path:.*\n" nil t))
5457     ;; We remove everything before the bounced mail.
5458     (delete-region
5459      (point-min)
5460      (if (re-search-forward "^[^ \n\t]+:" nil t)
5461          (match-beginning 0)
5462        (point)))
5463     (save-restriction
5464       (message-narrow-to-head-1)
5465       (message-remove-header message-ignored-bounced-headers t)
5466       (goto-char (point-max))
5467       (insert mail-header-separator))
5468     (when message-bounce-setup-function
5469       (funcall message-bounce-setup-function))
5470     (run-hooks 'message-bounce-setup-hook)
5471     (message-position-point)))
5472
5473 ;;;
5474 ;;; Interactive entry points for new message buffers.
5475 ;;;
5476
5477 ;;;###autoload
5478 (defun message-mail-other-window (&optional to subject)
5479   "Like `message-mail' command, but display mail buffer in another window."
5480   (interactive)
5481   (unless (message-mail-user-agent)
5482     (let ((pop-up-windows t)
5483           (special-display-buffer-names nil)
5484           (special-display-regexps nil)
5485           (same-window-buffer-names nil)
5486           (same-window-regexps nil))
5487       (message-pop-to-buffer (message-buffer-name "mail" to))))
5488   (let ((message-this-is-mail t))
5489     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
5490                    nil nil 'switch-to-buffer-other-window)))
5491
5492 ;;;###autoload
5493 (defun message-mail-other-frame (&optional to subject)
5494   "Like `message-mail' command, but display mail buffer in another frame."
5495   (interactive)
5496   (unless (message-mail-user-agent)
5497     (let ((pop-up-frames t)
5498           (special-display-buffer-names nil)
5499           (special-display-regexps nil)
5500           (same-window-buffer-names nil)
5501           (same-window-regexps nil))
5502       (message-pop-to-buffer (message-buffer-name "mail" to))))
5503   (let ((message-this-is-mail t))
5504     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
5505                    nil nil 'switch-to-buffer-other-frame)))
5506
5507 ;;;###autoload
5508 (defun message-news-other-window (&optional newsgroups subject)
5509   "Start editing a news article to be sent."
5510   (interactive)
5511   (let ((pop-up-windows t)
5512         (special-display-buffer-names nil)
5513         (special-display-regexps nil)
5514         (same-window-buffer-names nil)
5515         (same-window-regexps nil))
5516     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
5517   (let ((message-this-is-news t))
5518     (message-setup `((Newsgroups . ,(or newsgroups ""))
5519                      (Subject . ,(or subject ""))))))
5520
5521 ;;;###autoload
5522 (defun message-news-other-frame (&optional newsgroups subject)
5523   "Start editing a news article to be sent."
5524   (interactive)
5525   (let ((pop-up-frames t)
5526         (special-display-buffer-names nil)
5527         (special-display-regexps nil)
5528         (same-window-buffer-names nil)
5529         (same-window-regexps nil))
5530     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
5531   (let ((message-this-is-news t))
5532     (message-setup `((Newsgroups . ,(or newsgroups ""))
5533                      (Subject . ,(or subject ""))))))
5534
5535 ;;; underline.el
5536
5537 ;; This code should be moved to underline.el (from which it is stolen).
5538
5539 ;;;###autoload
5540 (defun bold-region (start end)
5541   "Bold all nonblank characters in the region.
5542 Works by overstriking characters.
5543 Called from program, takes two arguments START and END
5544 which specify the range to operate on."
5545   (interactive "r")
5546   (save-excursion
5547     (let ((end1 (make-marker)))
5548       (move-marker end1 (max start end))
5549       (goto-char (min start end))
5550       (while (< (point) end1)
5551         (or (looking-at "[_\^@- ]")
5552             (insert (char-after) "\b"))
5553         (forward-char 1)))))
5554
5555 ;;;###autoload
5556 (defun unbold-region (start end)
5557   "Remove all boldness (overstruck characters) in the region.
5558 Called from program, takes two arguments START and END
5559 which specify the range to operate on."
5560   (interactive "r")
5561   (save-excursion
5562     (let ((end1 (make-marker)))
5563       (move-marker end1 (max start end))
5564       (goto-char (min start end))
5565       (while (re-search-forward "\b" end1 t)
5566         (if (eq (char-after) (char-after (- (point) 2)))
5567             (delete-char -2))))))
5568
5569 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
5570
5571 ;; Support for toolbar
5572 (eval-when-compile
5573   (defvar tool-bar-map)
5574   (defvar tool-bar-mode))
5575
5576 (defun message-tool-bar-map ()
5577   (or message-tool-bar-map
5578       (setq message-tool-bar-map
5579             (and (fboundp 'tool-bar-add-item-from-menu)
5580                  tool-bar-mode
5581                  (let ((tool-bar-map (copy-keymap tool-bar-map))
5582                        (load-path (mm-image-load-path)))
5583                    ;; Zap some items which aren't so relevant and take
5584                    ;; up space.
5585                    (dolist (key '(print-buffer kill-buffer save-buffer
5586                                                write-file dired open-file))
5587                      (define-key tool-bar-map (vector key) nil))
5588                    (tool-bar-add-item-from-menu
5589                     'message-send-and-exit "mail_send" message-mode-map)
5590                    (tool-bar-add-item-from-menu
5591                     'message-kill-buffer "close" message-mode-map)
5592                    (tool-bar-add-item-from-menu
5593                     'message-dont-send "cancel" message-mode-map)
5594                    (tool-bar-add-item-from-menu
5595                     'mml-attach-file "attach" message-mode-map)
5596                    (tool-bar-add-item-from-menu
5597                     'ispell-message "spell" message-mode-map)
5598                    tool-bar-map)))))
5599
5600 ;;; Group name completion.
5601
5602 (defvar message-newgroups-header-regexp
5603   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
5604   "Regexp that match headers that lists groups.")
5605
5606 (defun message-tab ()
5607   "Expand group names in Newsgroups and Followup-To headers.
5608 Do a `tab-to-tab-stop' if not in those headers."
5609   (interactive)
5610   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
5611         (mail-abbrev-in-expansion-header-p))
5612       (message-expand-group)
5613     (tab-to-tab-stop)))
5614
5615 (defun message-expand-group ()
5616   "Expand the group name under point."
5617   (let* ((b (save-excursion
5618               (save-restriction
5619                 (narrow-to-region
5620                  (save-excursion
5621                    (beginning-of-line)
5622                    (skip-chars-forward "^:")
5623                    (1+ (point)))
5624                  (point))
5625                 (skip-chars-backward "^, \t\n") (point))))
5626          (completion-ignore-case t)
5627          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
5628                                             (point))))
5629          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
5630          (completions (all-completions string hashtb))
5631          comp)
5632     (delete-region b (point))
5633     (cond
5634      ((= (length completions) 1)
5635       (if (string= (car completions) string)
5636           (progn
5637             (insert string)
5638             (message "Only matching group"))
5639         (insert (car completions))))
5640      ((and (setq comp (try-completion string hashtb))
5641            (not (string= comp string)))
5642       (insert comp))
5643      (t
5644       (insert string)
5645       (if (not comp)
5646           (message "No matching groups")
5647         (save-selected-window
5648           (pop-to-buffer "*Completions*")
5649           (buffer-disable-undo)
5650           (let ((buffer-read-only nil))
5651             (erase-buffer)
5652             (let ((standard-output (current-buffer)))
5653               (display-completion-list (sort completions 'string<)))
5654             (goto-char (point-min))
5655             (delete-region (point) (progn (forward-line 3) (point))))))))))
5656
5657 ;;; Help stuff.
5658
5659 (defun message-talkative-question (ask question show &rest text)
5660   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
5661 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
5662 The following arguments may contain lists of values."
5663   (if (and show
5664            (setq text (message-flatten-list text)))
5665       (save-window-excursion
5666         (save-excursion
5667           (with-output-to-temp-buffer " *MESSAGE information message*"
5668             (set-buffer " *MESSAGE information message*")
5669             (fundamental-mode)          ; for Emacs 20.4+
5670             (mapcar 'princ text)
5671             (goto-char (point-min))))
5672         (funcall ask question))
5673     (funcall ask question)))
5674
5675 (defun message-flatten-list (list)
5676   "Return a new, flat list that contains all elements of LIST.
5677
5678 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
5679 => (1 2 3 4 5 6 7)"
5680   (cond ((consp list)
5681          (apply 'append (mapcar 'message-flatten-list list)))
5682         (list
5683          (list list))))
5684
5685 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
5686   "Create and return a buffer with name based on NAME using `generate-new-buffer.'
5687 Then clone the local variables and values from the old buffer to the
5688 new one, cloning only the locals having a substring matching the
5689 regexp varstr."
5690   (let ((oldbuf (current-buffer)))
5691     (save-excursion
5692       (set-buffer (generate-new-buffer name))
5693       (message-clone-locals oldbuf varstr)
5694       (current-buffer))))
5695
5696 (defun message-clone-locals (buffer &optional varstr)
5697   "Clone the local variables from BUFFER to the current buffer."
5698   (let ((locals (save-excursion
5699                   (set-buffer buffer)
5700                   (buffer-local-variables)))
5701         (regexp
5702          "^\\(gnus\\|nn\\|message\\|user-\\(mail-address\\|full-name\\)\\)"))
5703     (mapcar
5704      (lambda (local)
5705        (when (and (consp local)
5706                   (car local)
5707                   (string-match regexp (symbol-name (car local)))
5708                   (or (null varstr)
5709                       (string-match varstr (symbol-name (car local)))))
5710          (ignore-errors
5711            (set (make-local-variable (car local))
5712                 (cdr local)))))
5713      locals)))
5714
5715
5716 ;;; @ for MIME Edit mode
5717 ;;;
5718
5719 (defun message-maybe-encode ()
5720   (when message-mime-mode
5721     ;; Inherit the buffer local variable `mime-edit-pgp-processing'.
5722     (let ((pgp-processing (with-current-buffer message-edit-buffer
5723                             mime-edit-pgp-processing)))
5724       (setq mime-edit-pgp-processing pgp-processing))
5725     (run-hooks 'mime-edit-translate-hook)
5726     (if (catch 'mime-edit-error
5727           (save-excursion
5728             (mime-edit-pgp-enclose-buffer)
5729             (mime-edit-translate-body)
5730             ))
5731         (error "Translation error!")
5732       )
5733     (end-of-invisible)
5734     (run-hooks 'mime-edit-exit-hook)
5735     ))
5736
5737 (defun message-mime-insert-article (&optional full-headers)
5738   (interactive "P")
5739   (let ((message-cite-function 'mime-edit-inserted-message-filter)
5740         (message-reply-buffer
5741          (message-get-parameter-with-eval 'original-buffer))
5742         (start (point)))
5743     (message-yank-original nil)
5744     (save-excursion
5745       (narrow-to-region (goto-char start)
5746                         (if (search-forward "\n\n" nil t)
5747                             (1- (point))
5748                           (point-max)))
5749       (goto-char (point-min))
5750       (let ((message-included-forward-headers
5751              (if full-headers "" message-included-forward-headers)))
5752         (message-remove-header message-included-forward-headers t nil t))
5753       (widen))))
5754
5755 (set-alist 'mime-edit-message-inserter-alist
5756            'message-mode (function message-mime-insert-article))
5757
5758 ;;; Miscellaneous functions
5759
5760 ;; stolen (and renamed) from nnheader.el
5761 (static-if (fboundp 'subst-char-in-string)
5762     (defsubst message-replace-chars-in-string (string from to)
5763       (subst-char-in-string from to string))
5764   (defun message-replace-chars-in-string (string from to)
5765     "Replace characters in STRING from FROM to TO."
5766     (let ((string (substring string 0)) ;Copy string.
5767           (len (length string))
5768           (idx 0))
5769       ;; Replace all occurrences of FROM with TO.
5770       (while (< idx len)
5771         (when (= (aref string idx) from)
5772           (aset string idx to))
5773         (setq idx (1+ idx)))
5774       string)))
5775
5776 ;;;
5777 ;;; MIME functions
5778 ;;;
5779
5780 (defvar message-inhibit-body-encoding t)
5781
5782 (defun message-encode-message-body ()
5783   (unless message-inhibit-body-encoding
5784     (let ((mail-parse-charset (or mail-parse-charset
5785                                   message-default-charset))
5786           (case-fold-search t)
5787           lines content-type-p)
5788       (message-goto-body)
5789       (save-restriction
5790         (narrow-to-region (point) (point-max))
5791         (let ((new (mml-generate-mime)))
5792           (when new
5793             (delete-region (point-min) (point-max))
5794             (insert new)
5795             (goto-char (point-min))
5796             (if (eq (aref new 0) ?\n)
5797                 (delete-char 1)
5798               (search-forward "\n\n")
5799               (setq lines (buffer-substring (point-min) (1- (point))))
5800               (delete-region (point-min) (point))))))
5801       (save-restriction
5802         (message-narrow-to-headers-or-head)
5803         (message-remove-header "Mime-Version")
5804         (goto-char (point-max))
5805         (insert "MIME-Version: 1.0\n")
5806         (when lines
5807           (insert lines))
5808         (setq content-type-p
5809               (or mml-boundary
5810                   (re-search-backward "^Content-Type:" nil t))))
5811       (save-restriction
5812         (message-narrow-to-headers-or-head)
5813         (message-remove-first-header "Content-Type")
5814         (message-remove-first-header "Content-Transfer-Encoding"))
5815       ;; We always make sure that the message has a Content-Type header.
5816       ;; This is because some broken MTAs and MUAs get awfully confused
5817       ;; when confronted with a message with a MIME-Version header and
5818       ;; without a Content-Type header.  For instance, Solaris'
5819       ;; /usr/bin/mail.
5820       (unless content-type-p
5821         (goto-char (point-min))
5822         (re-search-forward "^MIME-Version:")
5823         (forward-line 1)
5824         (insert "Content-Type: text/plain; charset=us-ascii\n")))))
5825
5826 (defun message-read-from-minibuffer (prompt)
5827   "Read from the minibuffer while providing abbrev expansion."
5828   (if (fboundp 'mail-abbrevs-setup)
5829       (let ((mail-abbrev-mode-regexp "")
5830             (minibuffer-setup-hook 'mail-abbrevs-setup)
5831             (minibuffer-local-map message-minibuffer-local-map))
5832         (read-from-minibuffer prompt))
5833     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
5834           (minibuffer-local-map message-minibuffer-local-map))
5835       (read-string prompt))))
5836
5837 (defun message-use-alternative-email-as-from ()
5838   (require 'mail-utils)
5839   (let* ((fields '("To" "Cc"))
5840          (emails
5841           (split-string
5842            (mail-strip-quoted-names
5843             (mapconcat 'message-fetch-reply-field fields ","))
5844            "[ \f\t\n\r\v,]+"))
5845          email)
5846     (while emails
5847       (if (string-match message-alternative-emails (car emails))
5848           (setq email (car emails)
5849                 emails nil))
5850       (pop emails))
5851     (unless (or (not email) (equal email user-mail-address))
5852       (goto-char (point-max))
5853       (insert "From: " email "\n"))))
5854
5855 (defun message-options-get (symbol)
5856   (cdr (assq symbol message-options)))
5857
5858 (defun message-options-set (symbol value)
5859   (let ((the-cons (assq symbol message-options)))
5860     (if the-cons
5861         (if value
5862             (setcdr the-cons value)
5863           (setq message-options (delq the-cons message-options)))
5864       (and value
5865            (push (cons symbol value) message-options))))
5866   value)
5867
5868 (defun message-options-set-recipient ()
5869   (save-restriction
5870     (message-narrow-to-headers-or-head)
5871     (message-options-set 'message-sender
5872                          (mail-strip-quoted-names
5873                           (message-fetch-field "from")))
5874     (message-options-set 'message-recipients
5875                          (mail-strip-quoted-names
5876                           (concat
5877                            (or (message-fetch-field "to") "") ", "
5878                            (or (message-fetch-field "cc") "") ", "
5879                            (or (message-fetch-field "bcc") ""))))))
5880
5881 (when (featurep 'xemacs)
5882   (require 'messagexmas)
5883   (message-xmas-redefine))
5884
5885 (defun message-save-drafts ()
5886   "Postponing the message."
5887   (interactive)
5888   (message "Saving %s..." buffer-file-name)
5889   (let ((reply-headers message-reply-headers)
5890         (msg (buffer-substring-no-properties (point-min) (point-max)))
5891         (message-invisibles (message-find-invisible-regions)))
5892     (with-temp-file buffer-file-name
5893       (insert msg)
5894       ;; Inherit the invisible property of texts to make MIME-Edit
5895       ;; find the MIME part boundaries.
5896       (dolist (region message-invisibles)
5897         (put-text-property (car region) (cdr region) 'invisible t))
5898       (setq message-reply-headers reply-headers)
5899       (message-generate-headers '((optional . In-Reply-To)))
5900       (mime-edit-translate-buffer))
5901     (set-buffer-modified-p nil))
5902   (message "Saving %s...done" buffer-file-name))
5903
5904 (provide 'message)
5905
5906 (run-hooks 'message-load-hook)
5907
5908 ;; Local Variables:
5909 ;; coding: iso-8859-1
5910 ;; End:
5911
5912 ;;; message.el ends here