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