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