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