Sync up with chao-6_9.
[elisp/gnus.git-] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2 ;; Copyright (C) 1996,97,98 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
6 ;;      Shuhei KOBAYASHI <shuhei-k@jaist.ac.jp>
7 ;;      Keiichi Suzuki <kei-suzu@mail.wbs.ne.jp>
8 ;;      Tatsuya Ichikawa <t-ichi@po.shiojiri.ne.jp>
9 ;;      Katsumi Yamaoka <yamaoka@jpl.org>
10 ;; Keywords: mail, news, MIME
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software; you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
26 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
27 ;; Boston, MA 02111-1307, USA.
28
29 ;;; Commentary:
30
31 ;; This mode provides mail-sending facilities from within Emacs.  It
32 ;; consists mainly of large chunks of code from the sendmail.el,
33 ;; gnus-msg.el and rnewspost.el files.
34
35 ;;; Code:
36
37 (eval-when-compile
38   (require 'cl)
39   (require 'smtp)
40   )
41
42 (require 'mailheader)
43 (require 'nnheader)
44 (require 'easymenu)
45 (require 'custom)
46 (if (string-match "XEmacs\\|Lucid" emacs-version)
47     (require 'mail-abbrevs)
48   (require 'mailabbrev))
49 (require 'mime-edit)
50
51 (defgroup message '((user-mail-address custom-variable)
52                     (user-full-name custom-variable))
53   "Mail and news message composing."
54   :link '(custom-manual "(message)Top")
55   :group 'mail
56   :group 'news)
57
58 (put 'user-mail-address 'custom-type 'string)
59 (put 'user-full-name 'custom-type 'string)
60
61 (defgroup message-various nil
62   "Various Message Variables"
63   :link '(custom-manual "(message)Various Message Variables")
64   :group 'message)
65
66 (defgroup message-buffers nil
67   "Message Buffers"
68   :link '(custom-manual "(message)Message Buffers")
69   :group 'message)
70
71 (defgroup message-sending nil
72   "Message Sending"
73   :link '(custom-manual "(message)Sending Variables")
74   :group 'message)
75
76 (defgroup message-interface nil
77   "Message Interface"
78   :link '(custom-manual "(message)Interface")
79   :group 'message)
80
81 (defgroup message-forwarding nil
82   "Message Forwarding"
83   :link '(custom-manual "(message)Forwarding")
84   :group 'message-interface)
85
86 (defgroup message-insertion nil
87   "Message Insertion"
88   :link '(custom-manual "(message)Insertion")
89   :group 'message)
90
91 (defgroup message-headers nil
92   "Message Headers"
93   :link '(custom-manual "(message)Message Headers")
94   :group 'message)
95
96 (defgroup message-news nil
97   "Composing News Messages"
98   :group 'message)
99
100 (defgroup message-mail nil
101   "Composing Mail Messages"
102   :group 'message)
103
104 (defgroup message-faces nil
105   "Faces used for message composing."
106   :group 'message
107   :group 'faces)
108
109 (defgroup message-frames nil
110   "Message frames"
111   :group 'message)
112
113 (defcustom message-directory "~/Mail/"
114   "*Directory from which all other mail file variables are derived."
115   :group 'message-various
116   :type 'directory)
117
118 (defcustom message-max-buffers 10
119   "*How many buffers to keep before starting to kill them off."
120   :group 'message-buffers
121   :type 'integer)
122
123 (defcustom message-send-rename-function nil
124   "Function called to rename the buffer after sending it."
125   :group 'message-buffers
126   :type 'function)
127
128 (defcustom message-fcc-handler-function 'message-output
129   "*A function called to save outgoing articles.
130 This function will be called with the name of the file to store the
131 article in.  The default function is `message-output' which saves in Unix
132 mailbox format."
133   :type '(radio (function-item message-output)
134                 (function :tag "Other"))
135   :group 'message-sending)
136
137 (defcustom message-encode-function 'message-maybe-encode
138   "*A function called to encode messages."
139   :group 'message-sending
140   :type 'function)
141
142 (defcustom message-courtesy-message
143   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
144   "*This is inserted at the start of a mailed copy of a posted message.
145 If the string contains the format spec \"%s\", the Newsgroups
146 the article has been posted to will be inserted there.
147 If this variable is nil, no such courtesy message will be added."
148   :group 'message-sending
149   :type 'string)
150
151 (defcustom message-ignored-bounced-headers "^\\(Received\\|Return-Path\\):"
152   "*Regexp that matches headers to be removed in resent bounced mail."
153   :group 'message-interface
154   :type 'regexp)
155
156 ;;;###autoload
157 (defcustom message-from-style 'default
158   "*Specifies how \"From\" headers look.
159
160 If `nil', they contain just the return address like:
161         king@grassland.com
162 If `parens', they look like:
163         king@grassland.com (Elvis Parsley)
164 If `angles', they look like:
165         Elvis Parsley <king@grassland.com>
166
167 Otherwise, most addresses look like `angles', but they look like
168 `parens' if `angles' would need quoting and `parens' would not."
169   :type '(choice (const :tag "simple" nil)
170                  (const parens)
171                  (const angles)
172                  (const default))
173   :group 'message-headers)
174
175 (defcustom message-syntax-checks nil
176   ; Guess this one shouldn't be easy to customize...
177   "*Controls what syntax checks should not be performed on outgoing posts.
178 To disable checking of long signatures, for instance, add
179  `(signature . disabled)' to this list.
180
181 Don't touch this variable unless you really know what you're doing.
182
183 Checks include subject-cmsg multiple-headers sendsys message-id from
184 long-lines control-chars size new-text redirected-followup signature
185 approved sender empty empty-headers message-id from subject
186 shorten-followup-to existing-newsgroups buffer-file-name unchanged."
187   :group 'message-news)
188
189 (defcustom message-required-news-headers
190   '(From Newsgroups Subject Date Message-ID
191          (optional . Organization) Lines
192          (optional . User-Agent))
193   "*Headers to be generated or prompted for when posting an article.
194 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
195 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
196 User-Agent are optional.  If don't you want message to insert some
197 header, remove it from this list."
198   :group 'message-news
199   :group 'message-headers
200   :type '(repeat sexp))
201
202 (defcustom message-required-mail-headers
203   '(From Subject Date (optional . In-Reply-To) Message-ID Lines
204          (optional . User-Agent))
205   "*Headers to be generated or prompted for when mailing a message.
206 RFC822 required that From, Date, To, Subject and Message-ID be
207 included.  Organization, Lines and User-Agent are optional."
208   :group 'message-mail
209   :group 'message-headers
210   :type '(repeat sexp))
211
212 (defcustom message-deletable-headers '(Message-ID Date Lines)
213   "Headers to be deleted if they already exist and were generated by message previously."
214   :group 'message-headers
215   :type 'sexp)
216
217 (defcustom message-ignored-news-headers
218   "^NNTP-Posting-Host:\\|^Xref:\\|^[BGF]cc:\\|^Resent-Fcc:"
219   "*Regexp of headers to be removed unconditionally before posting."
220   :group 'message-news
221   :group 'message-headers
222   :type 'regexp)
223
224 (defcustom message-ignored-mail-headers "^[GF]cc:\\|^Resent-Fcc:\\|^Xref:"
225   "*Regexp of headers to be removed unconditionally before mailing."
226   :group 'message-mail
227   :group 'message-headers
228   :type 'regexp)
229
230 (defcustom message-ignored-supersedes-headers "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|^X-Trace:\\|^X-Complaints-To:\\|Return-Path:\\|^Supersedes:"
231   "*Header lines matching this regexp will be deleted before posting.
232 It's best to delete old Path and Date headers before posting to avoid
233 any confusion."
234   :group 'message-interface
235   :type 'regexp)
236
237 (defcustom message-subject-re-regexp "^[ \t]*\\([Rr][Ee]:[ \t]*\\)*[ \t]*"
238   "*Regexp matching \"Re: \" in the subject line."
239   :group 'message-various
240   :type 'regexp)
241
242 ;;; Some sender agents encode the whole subject including leading "Re: ".
243 ;;; And if followup agent does not decode it for some reason (e.g. unknown
244 ;;; charset) and just add a new "Re: " in front of the encoded-word, the
245 ;;; result will contain multiple "Re: "'s.
246 (defcustom message-subject-encoded-re-regexp
247   (concat
248    "^[ \t]*"
249    (regexp-quote "=?")
250    "[-!#$%&'*+0-9A-Z^_`a-z{|}~]+" ; charset
251    (regexp-quote "?")
252    "\\("
253    "[Bb]" (regexp-quote "?") ; B encoding
254    "\\(\\(CQk\\|CSA\\|IAk\\|ICA\\)[Jg]\\)*" ; \([ \t][ \t][ \t]\)*
255    "\\("
256    "[Uc][km]U6" ; [Rr][Ee]:
257    "\\|"
258    "\\(C[VX]\\|I[FH]\\)J[Fl]O[g-v]" ; [ \t][Rr][Ee]:
259    "\\|"
260    "\\(CQl\\|CSB\\|IAl\\|ICB\\)[Sy][RZ]T[o-r]" ; [ \t][ \t][Rr][Ee]:
261    "\\)"
262    "\\|"
263    "[Qb]" (regexp-quote "?") ; Q encoding
264    "\\(_\\|=09\\|=20\\)*"
265    "\\([Rr]\\|=[57]2\\)\\([Ee]\\|=[46]5\\)\\(:\\|=3[Aa]\\)"
266    "\\)"
267    )
268   "*Regexp matching \"Re: \" in the subject line.
269 Unlike `message-subject-re-regexp', this regexp matches \"Re: \" within
270 an encoded-word."
271   :group 'message-various
272   :type 'regexp)
273
274 (defcustom message-use-subject-re t
275   "*If t, remove any (buggy) \"Re: \"'s from the subject of the precursor
276 and add a new \"Re: \".  If it is nil, use the subject \"as-is\".  If it
277 is the symbol `guess', try to detect \"Re: \" within an encoded-word."
278   :group 'message-various
279   :type '(choice (const :tag "off" nil)
280                  (const :tag "on" t)
281                  (const guess)))
282
283 ;;;###autoload
284 (defcustom message-signature-separator "^-- *$"
285   "Regexp matching the signature separator."
286   :type 'regexp
287   :group 'message-various)
288
289 (defcustom message-elide-elipsis "\n[...]\n\n"
290   "*The string which is inserted for elided text."
291   :type 'string
292   :group 'message-various)
293
294 (defcustom message-interactive nil
295   "Non-nil means when sending a message wait for and display errors.
296 nil means let mailer mail back a message to report errors."
297   :group 'message-sending
298   :group 'message-mail
299   :type 'boolean)
300
301 (defcustom message-generate-new-buffers t
302   "*Non-nil means that a new message buffer will be created whenever `message-setup' is called.
303 If this is a function, call that function with three parameters:  The type,
304 the to address and the group name.  (Any of these may be nil.)  The function
305 should return the new buffer name."
306   :group 'message-buffers
307   :type '(choice (const :tag "off" nil)
308                  (const :tag "on" t)
309                  (function fun)))
310
311 (defcustom message-kill-buffer-on-exit nil
312   "*Non-nil means that the message buffer will be killed after sending a message."
313   :group 'message-buffers
314   :type 'boolean)
315
316 (defcustom message-kill-buffer-query-function 'yes-or-no-p
317   "*A function called to query the user whether to kill buffer anyway or not.
318 If it is t, the buffer will be killed peremptorily."
319   :type '(radio (function-item yes-or-no-p)
320                 (function-item y-or-n-p)
321                 (function-item nnheader-Y-or-n-p)
322                 (function :tag "Other" t))
323   :group 'message-buffers)
324
325 (defvar gnus-local-organization)
326 (defcustom message-user-organization
327   (or (and (boundp 'gnus-local-organization)
328            (stringp gnus-local-organization)
329            gnus-local-organization)
330       (getenv "ORGANIZATION")
331       t)
332   "*String to be used as an Organization header.
333 If t, use `message-user-organization-file'."
334   :group 'message-headers
335   :type '(choice string
336                  (const :tag "consult file" t)))
337
338 ;;;###autoload
339 (defcustom message-user-organization-file "/usr/lib/news/organization"
340   "*Local news organization file."
341   :type 'file
342   :group 'message-headers)
343
344 (defcustom message-forward-start-separator
345   (concat (mime-make-tag "message" "rfc822") "\n")
346   "*Delimiter inserted before forwarded messages."
347   :group 'message-forwarding
348   :type 'string)
349
350 (defcustom message-forward-end-separator
351   (concat (mime-make-tag "text" "plain") "\n")
352   "*Delimiter inserted after forwarded messages."
353   :group 'message-forwarding
354   :type 'string)
355
356 (defcustom message-signature-before-forwarded-message t
357   "*If non-nil, put the signature before any included forwarded message."
358   :group 'message-forwarding
359   :type 'boolean)
360
361 (defcustom message-included-forward-headers
362   "^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:"
363   "*Regexp matching headers to be included in forwarded messages."
364   :group 'message-forwarding
365   :type 'regexp)
366
367 (defcustom message-make-forward-subject-function 
368   'message-forward-subject-author-subject
369  "*A list of functions that are called to generate a subject header for forwarded messages.
370 The subject generated by the previous function is passed into each
371 successive function.
372
373 The provided functions are:
374
375 * message-forward-subject-author-subject (Source of article (author or
376       newsgroup)), in brackets followed by the subject
377 * message-forward-subject-fwd (Subject of article with 'Fwd:' prepended
378       to it."
379  :group 'message-forwarding
380  :type '(radio (function-item message-forward-subject-author-subject)
381                (function-item message-forward-subject-fwd)))
382
383 (defcustom message-wash-forwarded-subjects nil
384   "*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."
385   :group 'message-forwarding
386   :type 'boolean)
387
388 (defcustom message-ignored-resent-headers "^Return-Receipt"
389   "*All headers that match this regexp will be deleted when resending a message."
390   :group 'message-interface
391   :type 'regexp)
392
393 (defcustom message-ignored-cited-headers "."
394   "*Delete these headers from the messages you yank."
395   :group 'message-insertion
396   :type 'regexp)
397
398 (defcustom message-cancel-message "I am canceling my own article."
399   "Message to be inserted in the cancel message."
400   :group 'message-interface
401   :type 'string)
402
403 ;; Useful to set in site-init.el
404 ;;;###autoload
405 (defcustom message-send-mail-function 'message-send-mail-with-sendmail
406   "Function to call to send the current buffer as mail.
407 The headers should be delimited by a line whose contents match the
408 variable `mail-header-separator'.
409
410 Legal values include `message-send-mail-with-sendmail' (the default),
411 `message-send-mail-with-mh', `message-send-mail-with-qmail' and
412 `message-send-mail-with-smtp'."
413   :type '(radio (function-item message-send-mail-with-sendmail)
414                 (function-item message-send-mail-with-mh)
415                 (function-item message-send-mail-with-qmail)
416                 (function-item message-send-mail-with-smtp)
417                 (function :tag "Other"))
418   :group 'message-sending
419   :group 'message-mail)
420
421 ;; 1997-09-29 by MORIOKA Tomohiko
422 (defcustom message-send-news-function 'message-send-news-with-gnus
423   "Function to call to send the current buffer as news.
424 The headers should be delimited by a line whose contents match the
425 variable `mail-header-separator'."
426   :group 'message-sending
427   :group 'message-news
428   :type 'function)
429
430 (defcustom message-reply-to-function nil
431   "Function that should return a list of headers.
432 This function should pick out addresses from the To, Cc, and From headers
433 and respond with new To and Cc headers."
434   :group 'message-interface
435   :type 'function)
436
437 (defcustom message-wide-reply-to-function nil
438   "Function that should return a list of headers.
439 This function should pick out addresses from the To, Cc, and From headers
440 and respond with new To and Cc headers."
441   :group 'message-interface
442   :type 'function)
443
444 (defcustom message-followup-to-function nil
445   "Function that should return a list of headers.
446 This function should pick out addresses from the To, Cc, and From headers
447 and respond with new To and Cc headers."
448   :group 'message-interface
449   :type 'function)
450
451 (defcustom message-use-followup-to 'ask
452   "*Specifies what to do with Followup-To header.
453 If nil, always ignore the header.  If it is t, use its value, but
454 query before using the \"poster\" value.  If it is the symbol `ask',
455 always query the user whether to use the value.  If it is the symbol
456 `use', always use the value."
457   :group 'message-interface
458   :type '(choice (const :tag "ignore" nil)
459                  (const :tag "maybe" t)
460                  (const :tag "always" use)
461                  (const :tag "ask" ask)))
462
463 (defcustom message-use-mail-copies-to 'ask
464   "*Specifies what to do with Mail-Copies-To header.
465 If nil, always ignore the header.  If it is t, use its value, but
466 query before using the value other than \"always\" or \"never\".
467 If it is the symbol `ask', always query the user whether to use
468 the value.  If it is the symbol `use', always use the value."
469   :group 'message-interface
470   :type '(choice (const :tag "ignore" nil)
471                  (const :tag "maybe" t)
472                  (const :tag "always" use)
473                  (const :tag "ask" ask)))
474
475 (defcustom message-use-mail-followup-to 'ask
476   "*Specifies what to do with Mail-Followup-To header.
477 If nil, always ignore the header.  If it is the symbol `ask', always
478 query the user whether to use the value.  If it is t or the symbol
479 `use', always use the value."
480   :group 'message-interface
481   :type '(choice (const :tag "ignore" nil)
482                  (const :tag "maybe" t)
483                  (const :tag "always" use)
484                  (const :tag "ask" ask)))
485
486 ;;; XXX: 'ask and 'use are not implemented yet.
487 (defcustom message-use-mail-reply-to 'ask
488   "*Specifies what to do with Mail-Reply-To/Reply-To header.
489 If nil, always ignore the header.  If it is t or the symbol `use', use
490 its value.  If it is the symbol `ask', always query the user whether to
491 use the value.  Note that if \"Reply-To\" is marked as \"broken\", its value
492 is never used."
493   :group 'message-interface
494   :type '(choice (const :tag "ignore" nil)
495                  (const :tag "maybe" t)
496                  (const :tag "always" use)
497                  (const :tag "ask" ask)))
498
499 ;; stuff relating to broken sendmail in MMDF
500 (defcustom message-sendmail-f-is-evil nil
501   "*Non-nil means that \"-f username\" should not be added to the sendmail
502 command line, because it is even more evil than leaving it out."
503   :group 'message-sending
504   :type 'boolean)
505
506 ;; qmail-related stuff
507 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
508   "Location of the qmail-inject program."
509   :group 'message-sending
510   :type 'file)
511
512 (defcustom message-qmail-inject-args nil
513   "Arguments passed to qmail-inject programs.
514 This should be a list of strings, one string for each argument.
515
516 For e.g., if you wish to set the envelope sender address so that bounces
517 go to the right place or to deal with listserv's usage of that address, you
518 might set this variable to '(\"-f\" \"you@some.where\")."
519   :group 'message-sending
520   :type '(repeat string))
521
522 (defvar gnus-post-method)
523 (defvar gnus-select-method)
524 (defcustom message-post-method
525   (cond ((and (boundp 'gnus-post-method)
526               (listp gnus-post-method)
527               gnus-post-method)
528          gnus-post-method)
529         ((boundp 'gnus-select-method)
530          gnus-select-method)
531         (t '(nnspool "")))
532   "*Method used to post news.
533 Note that when posting from inside Gnus, for instance, this
534 variable isn't used."
535   :group 'message-news
536   :group 'message-sending
537   ;; This should be the `gnus-select-method' widget, but that might
538   ;; create a dependence to `gnus.el'.
539   :type 'sexp)
540
541 (defcustom message-generate-headers-first nil
542   "*If non-nil, generate all possible headers before composing."
543   :group 'message-headers
544   :type 'boolean)
545
546 (defcustom message-setup-hook '(turn-on-mime-edit)
547   "Normal hook, run each time a new outgoing message is initialized.
548 The function `message-setup' runs this hook."
549   :group 'message-various
550   :type 'hook)
551
552 (defcustom message-signature-setup-hook nil
553   "Normal hook, run each time a new outgoing message is initialized.
554 It is run after the headers have been inserted and before
555 the signature is inserted."
556   :group 'message-various
557   :type 'hook)
558
559 (defcustom message-mode-hook nil
560   "Hook run in message mode buffers."
561   :group 'message-various
562   :type 'hook)
563
564 (defcustom message-header-hook '(eword-encode-header)
565   "Hook run in a message mode buffer narrowed to the headers."
566   :group 'message-various
567   :type 'hook)
568
569 (defcustom message-header-setup-hook nil
570   "Hook called narrowed to the headers when setting up a message buffer."
571   :group 'message-various
572   :type 'hook)
573
574 ;;;###autoload
575 (defcustom message-citation-line-function 'message-insert-citation-line
576   "*Function called to insert the \"Whomever writes:\" line."
577   :type 'function
578   :group 'message-insertion)
579
580 ;;;###autoload
581 (defcustom message-yank-prefix "> "
582   "*Prefix inserted on the lines of yanked messages.
583 nil means use indentation."
584   :type 'string
585   :group 'message-insertion)
586
587 (defcustom message-indentation-spaces 3
588   "*Number of spaces to insert at the beginning of each cited line.
589 Used by `message-yank-original' via `message-yank-cite'."
590   :group 'message-insertion
591   :type 'integer)
592
593 ;;;###autoload
594 (defcustom message-cite-function 'message-cite-original
595   "*Function for citing an original message.
596 Predefined functions include `message-cite-original' and
597 `message-cite-original-without-signature'.
598 Note that `message-cite-original' uses `mail-citation-hook' if that is non-nil."
599   :type '(radio (function-item message-cite-original)
600                 (function-item sc-cite-original)
601                 (function :tag "Other"))
602   :group 'message-insertion)
603
604 ;;;###autoload
605 (defcustom message-indent-citation-function 'message-indent-citation
606   "*Function for modifying a citation just inserted in the mail buffer.
607 This can also be a list of functions.  Each function can find the
608 citation between (point) and (mark t).  And each function should leave
609 point and mark around the citation text as modified."
610   :type 'function
611   :group 'message-insertion)
612
613 (defvar message-abbrevs-loaded nil)
614
615 ;;;###autoload
616 (defcustom message-signature t
617   "*String to be inserted at the end of the message buffer.
618 If t, the `message-signature-file' file will be inserted instead.
619 If a function, the result from the function will be used instead.
620 If a form, the result from the form will be used instead."
621   :type 'sexp
622   :group 'message-insertion)
623
624 ;;;###autoload
625 (defcustom message-signature-file "~/.signature"
626   "*File containing the text inserted at end of message buffer."
627   :type 'file
628   :group 'message-insertion)
629
630 (defcustom message-distribution-function nil
631   "*Function called to return a Distribution header."
632   :group 'message-news
633   :group 'message-headers
634   :type 'function)
635
636 (defcustom message-expires 14
637   "Number of days before your article expires."
638   :group 'message-news
639   :group 'message-headers
640   :link '(custom-manual "(message)News Headers")
641   :type 'integer)
642
643 (defcustom message-user-path nil
644   "If nil, use the NNTP server name in the Path header.
645 If stringp, use this; if non-nil, use no host name (user name only)."
646   :group 'message-news
647   :group 'message-headers
648   :link '(custom-manual "(message)News Headers")
649   :type '(choice (const :tag "nntp" nil)
650                  (string :tag "name")
651                  (sexp :tag "none" :format "%t" t)))
652
653 (defvar message-reply-buffer nil)
654 (defvar message-reply-headers nil)
655 (defvar message-sent-message-via nil)
656 (defvar message-checksum nil)
657 (defvar message-send-actions nil
658   "A list of actions to be performed upon successful sending of a message.")
659 (defvar message-exit-actions nil
660   "A list of actions to be performed upon exiting after sending a message.")
661 (defvar message-kill-actions nil
662   "A list of actions to be performed before killing a message buffer.")
663 (defvar message-postpone-actions nil
664   "A list of actions to be performed after postponing a message.")
665 (defvar message-original-frame nil)
666 (defvar message-parameter-alist nil)
667 (defvar message-startup-parameter-alist nil)
668
669 (define-widget 'message-header-lines 'text
670   "All header lines must be LFD terminated."
671   :format "%t:%n%v"
672   :valid-regexp "^\\'"
673   :error "All header lines must be newline terminated")
674
675 (defcustom message-default-headers ""
676   "*A string containing header lines to be inserted in outgoing messages.
677 It is inserted before you edit the message, so you can edit or delete
678 these lines."
679   :group 'message-headers
680   :type 'message-header-lines)
681
682 (defcustom message-default-mail-headers ""
683   "*A string of header lines to be inserted in outgoing mails."
684   :group 'message-headers
685   :group 'message-mail
686   :type 'message-header-lines)
687
688 (defcustom message-default-news-headers ""
689   "*A string of header lines to be inserted in outgoing news
690 articles."
691   :group 'message-headers
692   :group 'message-news
693   :type 'message-header-lines)
694
695 ;; Note: could use /usr/ucb/mail instead of sendmail;
696 ;; options -t, and -v if not interactive.
697 (defcustom message-mailer-swallows-blank-line
698   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)"
699                          system-configuration)
700            (file-readable-p "/etc/sendmail.cf")
701            (let ((buffer (get-buffer-create " *temp*")))
702              (unwind-protect
703                  (save-excursion
704                    (set-buffer buffer)
705                    (insert-file-contents "/etc/sendmail.cf")
706                    (goto-char (point-min))
707                    (let ((case-fold-search nil))
708                      (re-search-forward "^OR\\>" nil t)))
709                (kill-buffer buffer))))
710       ;; According to RFC822, "The field-name must be composed of printable
711       ;; ASCII characters (i. e., characters that have decimal values between
712       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
713       ;; space, or colon.
714       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
715   "*Set this non-nil if the system's mailer runs the header and body together.
716 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
717 The value should be an expression to test whether the problem will
718 actually occur."
719   :group 'message-sending
720   :type 'sexp)
721
722 ;;; XXX: This symbol is overloaded!  See below.
723 (defvar message-user-agent nil
724   "String of the form of PRODUCT/VERSION.  Used for User-Agent header field.")
725
726 ;; Ignore errors in case this is used in Emacs 19.
727 ;; Don't use ignore-errors because this is copied into loaddefs.el.
728 ;;;###autoload
729 (condition-case nil
730     (define-mail-user-agent 'message-user-agent
731       'message-mail 'message-send-and-exit
732       'message-kill-buffer 'message-send-hook)
733   (error nil))
734
735 (defvar message-mh-deletable-headers '(Message-ID Date Lines Sender)
736   "If non-nil, delete the deletable headers before feeding to mh.")
737
738 (defvar message-send-method-alist
739   '((news message-news-p message-send-via-news)
740     (mail message-mail-p message-send-via-mail))
741   "Alist of ways to send outgoing messages.
742 Each element has the form
743
744   \(TYPE PREDICATE FUNCTION)
745
746 where TYPE is a symbol that names the method; PREDICATE is a function
747 called without any parameters to determine whether the message is
748 a message of type TYPE; and FUNCTION is a function to be called if
749 PREDICATE returns non-nil.  FUNCTION is called with one parameter --
750 the prefix.")
751
752 (defvar message-mail-alias-type 'abbrev
753   "*What alias expansion type to use in Message buffers.
754 The default is `abbrev', which uses mailabbrev.  nil switches
755 mail aliases off.")
756
757 (defcustom message-auto-save-directory
758   (nnheader-concat message-directory "drafts/")
759   "*Directory where Message auto-saves buffers if Gnus isn't running.
760 If nil, Message won't auto-save."
761   :group 'message-buffers
762   :type 'directory)
763
764 ;;; Internal variables.
765 ;;; Well, not really internal.
766
767 (defvar message-mode-syntax-table
768   (let ((table (copy-syntax-table text-mode-syntax-table)))
769     (modify-syntax-entry ?% ". " table)
770     table)
771   "Syntax table used while in Message mode.")
772
773 (defvar message-mode-abbrev-table text-mode-abbrev-table
774   "Abbrev table used in Message mode buffers.
775 Defaults to `text-mode-abbrev-table'.")
776 (defgroup message-headers nil
777   "Message headers."
778   :link '(custom-manual "(message)Variables")
779   :group 'message)
780
781 (defface message-header-to-face
782   '((((class color)
783       (background dark))
784      (:foreground "green2" :bold t))
785     (((class color)
786       (background light))
787      (:foreground "MidnightBlue" :bold t))
788     (t
789      (:bold t :italic t)))
790   "Face used for displaying From headers."
791   :group 'message-faces)
792
793 (defface message-header-cc-face
794   '((((class color)
795       (background dark))
796      (:foreground "green4" :bold t))
797     (((class color)
798       (background light))
799      (:foreground "MidnightBlue"))
800     (t
801      (:bold t)))
802   "Face used for displaying Cc headers."
803   :group 'message-faces)
804
805 (defface message-header-subject-face
806   '((((class color)
807       (background dark))
808      (:foreground "green3"))
809     (((class color)
810       (background light))
811      (:foreground "navy blue" :bold t))
812     (t
813      (:bold t)))
814   "Face used for displaying subject headers."
815   :group 'message-faces)
816
817 (defface message-header-newsgroups-face
818   '((((class color)
819       (background dark))
820      (:foreground "yellow" :bold t :italic t))
821     (((class color)
822       (background light))
823      (:foreground "blue4" :bold t :italic t))
824     (t
825      (:bold t :italic t)))
826   "Face used for displaying newsgroups headers."
827   :group 'message-faces)
828
829 (defface message-header-other-face
830   '((((class color)
831       (background dark))
832      (:foreground "#b00000"))
833     (((class color)
834       (background light))
835      (:foreground "steel blue"))
836     (t
837      (:bold t :italic t)))
838   "Face used for displaying newsgroups headers."
839   :group 'message-faces)
840
841 (defface message-header-name-face
842   '((((class color)
843       (background dark))
844      (:foreground "DarkGreen"))
845     (((class color)
846       (background light))
847      (:foreground "cornflower blue"))
848     (t
849      (:bold t)))
850   "Face used for displaying header names."
851   :group 'message-faces)
852
853 (defface message-header-xheader-face
854   '((((class color)
855       (background dark))
856      (:foreground "blue"))
857     (((class color)
858       (background light))
859      (:foreground "blue"))
860     (t
861      (:bold t)))
862   "Face used for displaying X-Header headers."
863   :group 'message-faces)
864
865 (defface message-separator-face
866   '((((class color)
867       (background dark))
868      (:foreground "blue3"))
869     (((class color)
870       (background light))
871      (:foreground "brown"))
872     (t
873      (:bold t)))
874   "Face used for displaying the separator."
875   :group 'message-faces)
876
877 (defface message-cited-text-face
878   '((((class color)
879       (background dark))
880      (:foreground "red"))
881     (((class color)
882       (background light))
883      (:foreground "red"))
884     (t
885      (:bold t)))
886   "Face used for displaying cited text names."
887   :group 'message-faces)
888
889 (defvar message-font-lock-keywords
890   (let* ((cite-prefix "A-Za-z")
891          (cite-suffix (concat cite-prefix "0-9_.@-"))
892          (content "[ \t]*\\(.+\\(\n[ \t].*\\)*\\)"))
893     `((,(concat "^\\([Tt]o:\\)" content)
894        (1 'message-header-name-face)
895        (2 'message-header-to-face nil t))
896       (,(concat "^\\([GBF]?[Cc][Cc]:\\|[Rr]eply-[Tt]o:\\|"
897                 "[Mm]ail-[Cc]opies-[Tt]o:\\|"
898                 "[Mm]ail-[Rr]eply-[Tt]o:\\|"
899                 "[Mm]ail-[Ff]ollowup-[Tt]o:\\)" content)
900        (1 'message-header-name-face)
901        (2 'message-header-cc-face nil t))
902       (,(concat "^\\([Ss]ubject:\\)" content)
903        (1 'message-header-name-face)
904        (2 'message-header-subject-face nil t))
905       (,(concat "^\\([Nn]ewsgroups:\\|Followup-[Tt]o:\\)" content)
906        (1 'message-header-name-face)
907        (2 'message-header-newsgroups-face nil t))
908       (,(concat "^\\([A-Z][^: \n\t]+:\\)" content)
909        (1 'message-header-name-face)
910        (2 'message-header-other-face nil t))
911       (,(concat "^\\(X-[A-Za-z0-9-]+\\|In-Reply-To\\):" content)
912        (1 'message-header-name-face)
913        (2 'message-header-name-face))
914       ,@(if (and mail-header-separator
915                  (not (equal mail-header-separator "")))
916             `((,(concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
917                1 'message-separator-face))
918           nil)
919       (,(concat "^[ \t]*"
920                 "\\([" cite-prefix "]+[" cite-suffix "]*\\)?"
921                 "[:>|}].*")
922        (0 'message-cited-text-face))))
923   "Additional expressions to highlight in Message mode.")
924
925 ;; XEmacs does it like this.  For Emacs, we have to set the
926 ;; `font-lock-defaults' buffer-local variable.
927 (put 'message-mode 'font-lock-defaults '(message-font-lock-keywords t))
928
929 (defvar message-face-alist
930   '((bold . bold-region)
931     (underline . underline-region)
932     (default . (lambda (b e)
933                  (unbold-region b e)
934                  (ununderline-region b e))))
935   "Alist of mail and news faces for facemenu.
936 The cdr of ech entry is a function for applying the face to a region.")
937
938 (defcustom message-send-hook nil
939   "Hook run before sending messages."
940   :group 'message-various
941   :options '(ispell-message)
942   :type 'hook)
943
944 (defcustom message-send-mail-hook nil
945   "Hook run before sending mail messages."
946   :group 'message-various
947   :type 'hook)
948
949 (defcustom message-send-news-hook nil
950   "Hook run before sending news messages."
951   :group 'message-various
952   :type 'hook)
953
954 (defcustom message-sent-hook nil
955   "Hook run after sending messages."
956   :group 'message-various
957   :type 'hook)
958
959 (defcustom message-use-multi-frames nil
960   "Make new frame when sending messages."
961   :group 'message-frames
962   :type 'boolean)
963
964 (defcustom message-delete-frame-on-exit nil
965   "Delete frame after sending messages."
966   :group 'message-frames
967   :type '(choice (const :tag "off" nil)
968                  (const :tag "always" t)
969                  (const :tag "ask" ask)))
970
971 (defvar message-send-coding-system 'binary
972   "Coding system to encode outgoing mail.")
973
974 ;;; Internal variables.
975
976 (defvar message-default-charset nil)
977 (defvar message-buffer-list nil)
978 (defvar message-this-is-news nil)
979 (defvar message-this-is-mail nil)
980 (defvar message-draft-article nil)
981
982 ;; Byte-compiler warning
983 (defvar gnus-active-hashtb)
984 (defvar gnus-read-active-file)
985
986 ;;; Regexp matching the delimiter of messages in UNIX mail format
987 ;;; (UNIX From lines), minus the initial ^.  It should be a copy
988 ;;; of rmail.el's rmail-unix-mail-delimiter.
989 (defvar message-unix-mail-delimiter
990   (let ((time-zone-regexp
991          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
992                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
993                  "\\|"
994                  "\\) *")))
995     (concat
996      "From "
997
998      ;; Many things can happen to an RFC 822 mailbox before it is put into
999      ;; a `From' line.  The leading phrase can be stripped, e.g.
1000      ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
1001      ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
1002      ;; can be removed, e.g.
1003      ;;         From: joe@y.z (Joe      K
1004      ;;                 User)
1005      ;; can yield `From joe@y.z (Joe    K Fri Mar 22 08:11:15 1996', and
1006      ;;         From: Joe User
1007      ;;                 <joe@y.z>
1008      ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
1009      ;; The mailbox can be removed or be replaced by white space, e.g.
1010      ;;         From: "Joe User"{space}{tab}
1011      ;;                 <joe@y.z>
1012      ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
1013      ;; where {space} and {tab} represent the Ascii space and tab characters.
1014      ;; We want to match the results of any of these manglings.
1015      ;; The following regexp rejects names whose first characters are
1016      ;; obviously bogus, but after that anything goes.
1017      "\\([^\0-\b\n-\r\^?].*\\)? "
1018
1019      ;; The time the message was sent.
1020      "\\([^\0-\r \^?]+\\) +"                            ; day of the week
1021      "\\([^\0-\r \^?]+\\) +"                            ; month
1022      "\\([0-3]?[0-9]\\) +"                              ; day of month
1023      "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *"  ; time of day
1024
1025      ;; Perhaps a time zone, specified by an abbreviation, or by a
1026      ;; numeric offset.
1027      time-zone-regexp
1028
1029      ;; The year.
1030      " \\([0-9][0-9]+\\) *"
1031
1032      ;; On some systems the time zone can appear after the year, too.
1033      time-zone-regexp
1034
1035      ;; Old uucp cruft.
1036      "\\(remote from .*\\)?"
1037
1038      "\n"))
1039   "Regexp matching the delimiter of messages in UNIX mail format.")
1040
1041 (defvar message-unsent-separator
1042   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
1043           "^ *---+ +Returned message +---+ *$\\|"
1044           "^Start of returned message$\\|"
1045           "^ *---+ +Original message +---+ *$\\|"
1046           "^ *--+ +begin message +--+ *$\\|"
1047           "^ *---+ +Original message follows +---+ *$\\|"
1048           "^|? *---+ +Message text follows: +---+ *|?$")
1049   "A regexp that matches the separator before the text of a failed message.")
1050
1051 (defvar message-header-format-alist
1052   `((Newsgroups)
1053     (To . message-fill-address)
1054     (Cc . message-fill-address)
1055     (Subject)
1056     (In-Reply-To)
1057     (Fcc)
1058     (Bcc)
1059     (Date)
1060     (Organization)
1061     (Distribution)
1062     (Lines)
1063     (Expires)
1064     (Message-ID)
1065     (References . message-fill-header)
1066     (User-Agent))
1067   "Alist used for formatting headers.")
1068
1069 (eval-and-compile
1070   (autoload 'message-setup-toolbar "messagexmas")
1071   (autoload 'mh-new-draft-name "mh-comp")
1072   (autoload 'mh-send-letter "mh-comp")
1073   (autoload 'gnus-point-at-eol "gnus-util")
1074   (autoload 'gnus-point-at-bol "gnus-util")
1075   (autoload 'gnus-output-to-mail "gnus-util")
1076   (autoload 'mail-abbrev-in-expansion-header-p "mailabbrev")
1077   (autoload 'nndraft-request-associate-buffer "nndraft")
1078   (autoload 'nndraft-request-expire-articles "nndraft")
1079   (autoload 'gnus-open-server "gnus-int")
1080   (autoload 'gnus-request-post "gnus-int")
1081   (autoload 'gnus-copy-article-buffer "gnus-msg")
1082   (autoload 'gnus-alive-p "gnus-util")
1083   (autoload 'rmail-output "rmail"))
1084
1085 \f
1086
1087 ;;;
1088 ;;; Utility functions.
1089 ;;;
1090
1091 (defmacro message-y-or-n-p (question show &rest text)
1092   "Ask QUESTION, displaying the rest of the arguments in a temp. buffer if SHOW"
1093   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1094
1095 ;; Delete the current line (and the next N lines.);
1096 (defmacro message-delete-line (&optional n)
1097   `(delete-region (progn (beginning-of-line) (point))
1098                   (progn (forward-line ,(or n 1)) (point))))
1099
1100 (defun message-tokenize-header (header &optional separator)
1101   "Split HEADER into a list of header elements.
1102 \",\" is used as the separator."
1103   (if (not header)
1104       nil
1105     (let ((regexp (format "[%s]+" (or separator ",")))
1106           (beg 1)
1107           (first t)
1108           quoted elems paren)
1109       (save-excursion
1110         (message-set-work-buffer)
1111         (insert header)
1112         (goto-char (point-min))
1113         (while (not (eobp))
1114           (if first
1115               (setq first nil)
1116             (forward-char 1))
1117           (cond ((and (> (point) beg)
1118                       (or (eobp)
1119                           (and (looking-at regexp)
1120                                (not quoted)
1121                                (not paren))))
1122                  (push (buffer-substring beg (point)) elems)
1123                  (setq beg (match-end 0)))
1124                 ((= (following-char) ?\")
1125                  (setq quoted (not quoted)))
1126                 ((and (= (following-char) ?\()
1127                       (not quoted))
1128                  (setq paren t))
1129                 ((and (= (following-char) ?\))
1130                       (not quoted))
1131                  (setq paren nil))))
1132         (nreverse elems)))))
1133
1134 (defun message-mail-file-mbox-p (file)
1135   "Say whether FILE looks like a Unix mbox file."
1136   (when (and (file-exists-p file)
1137              (file-readable-p file)
1138              (file-regular-p file))
1139     (with-temp-buffer
1140       (nnheader-insert-file-contents file)
1141       (goto-char (point-min))
1142       (looking-at message-unix-mail-delimiter))))
1143
1144 (defun message-fetch-field (header &optional not-all)
1145   "The same as `mail-fetch-field', only remove all newlines."
1146   (let* ((inhibit-point-motion-hooks t)
1147          (value (mail-fetch-field header nil (not not-all))))
1148     (when value
1149       (while (string-match "\n[\t ]+" value)
1150         (setq value (replace-match " " t t value)))
1151       value)))
1152
1153 (defun message-narrow-to-field ()
1154   "Narrow the buffer to the header on the current line."
1155   (beginning-of-line)
1156   (narrow-to-region
1157    (point)
1158    (progn
1159      (forward-line 1)
1160      (if (re-search-forward "^[^ \n\t]" nil t)
1161          (progn
1162            (beginning-of-line)
1163            (point))
1164        (point-max))))
1165   (goto-char (point-min)))
1166
1167 (defun message-add-header (&rest headers)
1168   "Add the HEADERS to the message header, skipping those already present."
1169   (while headers
1170     (let (hclean)
1171       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1172         (error "Invalid header `%s'" (car headers)))
1173       (setq hclean (match-string 1 (car headers)))
1174     (save-restriction
1175       (message-narrow-to-headers)
1176       (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1177         (insert (car headers) ?\n))))
1178     (setq headers (cdr headers))))
1179
1180 (defun message-fetch-reply-field (header)
1181   "Fetch FIELD from the message we're replying to."
1182   (let ((buffer (message-get-reply-buffer)))
1183     (when (and buffer
1184                (buffer-name buffer))
1185       (save-excursion
1186         (set-buffer buffer)
1187         (message-fetch-field header)))))
1188
1189 (defun message-set-work-buffer ()
1190   (if (get-buffer " *message work*")
1191       (progn
1192         (set-buffer " *message work*")
1193         (erase-buffer))
1194     (set-buffer (get-buffer-create " *message work*"))
1195     (kill-all-local-variables)))
1196
1197 (defun message-functionp (form)
1198   "Return non-nil if FORM is funcallable."
1199   (or (and (symbolp form) (fboundp form))
1200       (and (listp form) (eq (car form) 'lambda))
1201       (byte-code-function-p form)))
1202
1203 (defun message-strip-subject-re (subject)
1204   "Remove \"Re:\" from subject lines."
1205   (if (string-match message-subject-re-regexp subject)
1206       (substring subject (match-end 0))
1207     subject))
1208
1209 (defun message-remove-header (header &optional is-regexp first reverse)
1210   "Remove HEADER in the narrowed buffer.
1211 If REGEXP, HEADER is a regular expression.
1212 If FIRST, only remove the first instance of the header.
1213 Return the number of headers removed."
1214   (goto-char (point-min))
1215   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1216         (number 0)
1217         (case-fold-search t)
1218         last)
1219     (while (and (not (eobp))
1220                 (not last))
1221       (if (if reverse
1222               (not (looking-at regexp))
1223             (looking-at regexp))
1224           (progn
1225             (incf number)
1226             (when first
1227               (setq last t))
1228             (delete-region
1229              (point)
1230              ;; There might be a continuation header, so we have to search
1231              ;; until we find a new non-continuation line.
1232              (progn
1233                (forward-line 1)
1234                (if (re-search-forward "^[^ \t]" nil t)
1235                    (goto-char (match-beginning 0))
1236                  (point-max)))))
1237         (forward-line 1)
1238         (if (re-search-forward "^[^ \t]" nil t)
1239             (goto-char (match-beginning 0))
1240           (point-max))))
1241     number))
1242
1243 (defun message-narrow-to-headers ()
1244   "Narrow the buffer to the head of the message."
1245   (widen)
1246   (narrow-to-region
1247    (goto-char (point-min))
1248    (if (re-search-forward
1249         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1250        (match-beginning 0)
1251      (point-max)))
1252   (goto-char (point-min)))
1253
1254 (defun message-narrow-to-head ()
1255   "Narrow the buffer to the head of the message.
1256 Point is left at the beginning of the narrowed-to region."
1257   (widen)
1258   (narrow-to-region
1259    (goto-char (point-min))
1260    (if (search-forward "\n\n" nil 1)
1261        (1- (point))
1262      (point-max)))
1263   (goto-char (point-min)))
1264
1265 (defun message-narrow-to-headers-or-head ()
1266   "Narrow the buffer to the head of the message."
1267   (widen)
1268   (narrow-to-region
1269    (goto-char (point-min))
1270    (cond
1271     ((re-search-forward
1272       (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1273      (match-beginning 0))
1274     ((search-forward "\n\n" nil t)
1275      (1- (point)))
1276     (t
1277      (point-max))))
1278   (goto-char (point-min)))
1279
1280 (defun message-news-p ()
1281   "Say whether the current buffer contains a news message."
1282   (and (not message-this-is-mail)
1283        (or message-this-is-news
1284            (save-excursion
1285              (save-restriction
1286                (message-narrow-to-headers)
1287                (and (message-fetch-field "newsgroups")
1288                     (not (message-fetch-field "posted-to"))))))))
1289
1290 (defun message-mail-p ()
1291   "Say whether the current buffer contains a mail message."
1292   (and (not message-this-is-news)
1293        (or message-this-is-mail
1294            (save-excursion
1295              (save-restriction
1296                (message-narrow-to-headers)
1297                (or (message-fetch-field "to")
1298                    (message-fetch-field "cc")
1299                    (message-fetch-field "bcc")))))))
1300
1301 (defun message-next-header ()
1302   "Go to the beginning of the next header."
1303   (beginning-of-line)
1304   (or (eobp) (forward-char 1))
1305   (not (if (re-search-forward "^[^ \t]" nil t)
1306            (beginning-of-line)
1307          (goto-char (point-max)))))
1308
1309 (defun message-sort-headers-1 ()
1310   "Sort the buffer as headers using `message-rank' text props."
1311   (goto-char (point-min))
1312   (sort-subr
1313    nil 'message-next-header
1314    (lambda ()
1315      (message-next-header)
1316      (unless (bobp)
1317        (forward-char -1)))
1318    (lambda ()
1319      (or (get-text-property (point) 'message-rank)
1320          10000))))
1321
1322 (defun message-sort-headers ()
1323   "Sort the headers of the current message according to `message-header-format-alist'."
1324   (interactive)
1325   (save-excursion
1326     (save-restriction
1327       (let ((max (1+ (length message-header-format-alist)))
1328             rank)
1329         (message-narrow-to-headers)
1330         (while (re-search-forward "^[^ \n]+:" nil t)
1331           (put-text-property
1332            (match-beginning 0) (1+ (match-beginning 0))
1333            'message-rank
1334            (if (setq rank (length (memq (assq (intern (buffer-substring
1335                                                        (match-beginning 0)
1336                                                        (1- (match-end 0))))
1337                                               message-header-format-alist)
1338                                         message-header-format-alist)))
1339                (- max rank)
1340              (1+ max)))))
1341       (message-sort-headers-1))))
1342
1343 (defun message-eval-parameter (parameter)
1344   (condition-case ()
1345       (if (symbolp parameter)
1346           (if (functionp parameter)
1347               (funcall parameter)
1348             (eval parameter))
1349         parameter)
1350     (error nil)))
1351
1352 (defun message-get-reply-buffer ()
1353   (message-eval-parameter message-reply-buffer))
1354
1355 (defun message-get-original-reply-buffer ()
1356   (message-eval-parameter
1357    (cdr (assq 'original-buffer message-parameter-alist))))
1358
1359 \f
1360
1361 ;;;
1362 ;;; Message mode
1363 ;;;
1364
1365 ;;; Set up keymap.
1366
1367 (defvar message-mode-map nil)
1368
1369 (unless message-mode-map
1370   (setq message-mode-map (make-keymap))
1371   (set-keymap-parent message-mode-map text-mode-map)
1372   (define-key message-mode-map "\C-c?" 'describe-mode)
1373
1374   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1375   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1376   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1377   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1378   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1379   ;; (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1380   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-mail-reply-to)
1381   (define-key message-mode-map "\C-c\C-f\C-m" 'message-goto-mail-followup-to)
1382   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1383   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1384   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1385   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1386   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1387   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1388   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1389
1390   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1391   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1392
1393   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1394   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1395   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1396   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1397   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1398   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1399
1400   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1401   (define-key message-mode-map "\C-c\C-s" 'message-send)
1402   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1403   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1404
1405   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1406   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1407   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1408   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1409
1410   (define-key message-mode-map "\t" 'message-tab)
1411
1412   (define-key message-mode-map "\C-x\C-s" 'message-save-drafts)
1413   (define-key message-mode-map "\C-xk" 'message-kill-buffer))
1414
1415 (easy-menu-define
1416  message-mode-menu message-mode-map "Message Menu."
1417  '("Message"
1418    ["Sort Headers" message-sort-headers t]
1419    ["Yank Original" message-yank-original t]
1420    ["Fill Yanked Message" message-fill-yanked-message t]
1421    ["Insert Signature" message-insert-signature t]
1422    ["Caesar (rot13) Message" message-caesar-buffer-body t]
1423    ["Caesar (rot13) Region" message-caesar-region (mark t)]
1424    ["Elide Region" message-elide-region (mark t)]
1425    ["Delete Outside Region" message-delete-not-region (mark t)]
1426    ["Kill To Signature" message-kill-to-signature t]
1427    ["Newline and Reformat" message-newline-and-reformat t]
1428    ["Rename buffer" message-rename-buffer t]
1429    ["Spellcheck" ispell-message t]
1430    "----"
1431    ["Send Message" message-send-and-exit t]
1432    ["Abort Message" message-dont-send t]
1433    ["Kill Message" message-kill-buffer t]))
1434
1435 (easy-menu-define
1436  message-mode-field-menu message-mode-map ""
1437  '("Field"
1438    ["Fetch To" message-insert-to t]
1439    ["Fetch Newsgroups" message-insert-newsgroups t]
1440    "----"
1441    ["To" message-goto-to t]
1442    ["Subject" message-goto-subject t]
1443    ["Cc" message-goto-cc t]
1444    ["Reply-To" message-goto-reply-to t]
1445    ["Mail-Reply-To" message-goto-mail-reply-to t]
1446    ["Mail-Followup-To" message-goto-mail-followup-to t]
1447    ["Mail-Copies-To" message-goto-mail-copies-to t]
1448    ["Summary" message-goto-summary t]
1449    ["Keywords" message-goto-keywords t]
1450    ["Newsgroups" message-goto-newsgroups t]
1451    ["Followup-To" message-goto-followup-to t]
1452    ["Distribution" message-goto-distribution t]
1453    ["Body" message-goto-body t]
1454    ["Signature" message-goto-signature t]))
1455
1456 (defvar facemenu-add-face-function)
1457 (defvar facemenu-remove-face-function)
1458
1459 ;;;###autoload
1460 (defun message-mode ()
1461   "Major mode for editing mail and news to be sent.
1462 Like Text Mode but with these additional commands:
1463 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
1464 C-c C-f  move to a header field (and create it if there isn't):
1465          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1466          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1467          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1468          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1469          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1470          C-c C-f C-m  move to Mail-Followup-To
1471          C-c C-f C-f  move to Followup-To
1472 C-c C-t  message-insert-to (add a To header to a news followup)
1473 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
1474 C-c C-b  message-goto-body (move to beginning of message text).
1475 C-c C-i  message-goto-signature (move to the beginning of the signature).
1476 C-c C-w  message-insert-signature (insert `message-signature-file' file).
1477 C-c C-y  message-yank-original (insert current message, if any).
1478 C-c C-q  message-fill-yanked-message (fill what was yanked).
1479 C-c C-e  message-elide-region (elide the text between point and mark).
1480 C-c C-v  message-delete-not-region (remove the text outside the region).
1481 C-c C-z  message-kill-to-signature (kill the text up to the signature).
1482 C-c C-r  message-caesar-buffer-body (rot13 the message body)."
1483   (interactive)
1484   (kill-all-local-variables)
1485   (make-local-variable 'message-reply-buffer)
1486   (setq message-reply-buffer nil)
1487   (make-local-variable 'message-send-actions) 
1488   (make-local-variable 'message-exit-actions) 
1489   (make-local-variable 'message-kill-actions)
1490   (make-local-variable 'message-postpone-actions)
1491   (make-local-variable 'message-draft-article)
1492   (make-local-hook 'kill-buffer-hook)
1493   (set-syntax-table message-mode-syntax-table)
1494   (use-local-map message-mode-map)
1495   (setq local-abbrev-table message-mode-abbrev-table)
1496   (setq major-mode 'message-mode)
1497   (setq mode-name "Message")
1498   (setq buffer-offer-save t)
1499   (make-local-variable 'facemenu-add-face-function)
1500   (make-local-variable 'facemenu-remove-face-function)
1501   (setq facemenu-add-face-function
1502         (lambda (face end)
1503           (let ((face-fun (cdr (assq face message-face-alist))))
1504             (if face-fun
1505                 (funcall face-fun (point) end)
1506               (error "Face %s not configured for %s mode" face mode-name)))
1507           "")
1508         facemenu-remove-face-function t)
1509   (make-local-variable 'paragraph-separate)
1510   (make-local-variable 'paragraph-start)
1511   ;; `-- ' precedes the signature.  `-----' appears at the start of the
1512   ;; lines that delimit forwarded messages.
1513   ;; Lines containing just >= 3 dashes, perhaps after whitespace,
1514   ;; are also sometimes used and should be separators.
1515   (setq paragraph-start
1516         (concat (regexp-quote mail-header-separator)
1517                 "$\\|[ \t]*[a-z0-9A-Z]*>+[ \t]*$\\|[ \t]*$\\|"
1518                 "-- $\\|---+$\\|"
1519                 page-delimiter
1520                 ;;!!! Uhm... shurely this can't be right?
1521                 "[> " (regexp-quote message-yank-prefix) "]+$"))
1522   (setq paragraph-separate paragraph-start)
1523   (make-local-variable 'message-reply-headers)
1524   (setq message-reply-headers nil)
1525   (make-local-variable 'message-user-agent)
1526   (make-local-variable 'message-post-method)
1527   (make-local-variable 'message-sent-message-via)
1528   (setq message-sent-message-via nil)
1529   (make-local-variable 'message-checksum)
1530   (setq message-checksum nil)
1531   (make-local-variable 'message-parameter-alist)
1532   (setq message-parameter-alist
1533         (copy-sequence message-startup-parameter-alist))
1534   ;;(when (fboundp 'mail-hist-define-keys)
1535   ;;  (mail-hist-define-keys))
1536   (when (string-match "XEmacs\\|Lucid" emacs-version)
1537     (message-setup-toolbar))
1538   (easy-menu-add message-mode-menu message-mode-map)
1539   (easy-menu-add message-mode-field-menu message-mode-map)
1540   ;; Allow mail alias things.
1541   (when (eq message-mail-alias-type 'abbrev)
1542     (if (fboundp 'mail-abbrevs-setup)
1543         (mail-abbrevs-setup)
1544       (mail-aliases-setup)))
1545   (message-set-auto-save-file-name)
1546   (unless (string-match "XEmacs" emacs-version)
1547     (set (make-local-variable 'font-lock-defaults)
1548          '(message-font-lock-keywords t)))
1549   (make-local-variable 'adaptive-fill-regexp)
1550   (setq adaptive-fill-regexp
1551         (concat "[ \t]*[-a-z0-9A-Z]*>+[ \t]*\\|" adaptive-fill-regexp))
1552   (unless (boundp 'adaptive-fill-first-line-regexp)
1553     (setq adaptive-fill-first-line-regexp nil))
1554   (make-local-variable 'adaptive-fill-first-line-regexp)
1555   (setq adaptive-fill-first-line-regexp
1556         (concat "[ \t]*[-a-z0-9A-Z]*>+[ \t]*\\|"
1557                 adaptive-fill-first-line-regexp))
1558   (run-hooks 'text-mode-hook 'message-mode-hook))
1559
1560 \f
1561
1562 ;;;
1563 ;;; Message mode commands
1564 ;;;
1565
1566 ;;; Movement commands
1567
1568 (defun message-goto-to ()
1569   "Move point to the To header."
1570   (interactive)
1571   (message-position-on-field "To"))
1572
1573 (defun message-goto-subject ()
1574   "Move point to the Subject header."
1575   (interactive)
1576   (message-position-on-field "Subject"))
1577
1578 (defun message-goto-cc ()
1579   "Move point to the Cc header."
1580   (interactive)
1581   (message-position-on-field "Cc" "To"))
1582
1583 (defun message-goto-bcc ()
1584   "Move point to the Bcc  header."
1585   (interactive)
1586   (message-position-on-field "Bcc" "Cc" "To"))
1587
1588 (defun message-goto-fcc ()
1589   "Move point to the Fcc header."
1590   (interactive)
1591   (message-position-on-field "Fcc" "To" "Newsgroups"))
1592
1593 (defun message-goto-reply-to ()
1594   "Move point to the Reply-To header."
1595   (interactive)
1596   (message-position-on-field "Reply-To" "Subject"))
1597
1598 (defun message-goto-mail-reply-to ()
1599   "Move point to the Mail-Reply-To header."
1600   (interactive)
1601   (message-position-on-field "Mail-Reply-To" "Subject"))
1602
1603 (defun message-goto-mail-followup-to ()
1604   "Move point to the Mail-Followup-To header."
1605   (interactive)
1606   (message-position-on-field "Mail-Followup-To" "Subject"))
1607
1608 (defun message-goto-mail-copies-to ()
1609   "Move point to the Mail-Copies-To header."
1610   (interactive)
1611   (message-position-on-field "Mail-Copies-To" "Subject"))
1612
1613 (defun message-goto-newsgroups ()
1614   "Move point to the Newsgroups header."
1615   (interactive)
1616   (message-position-on-field "Newsgroups"))
1617
1618 (defun message-goto-distribution ()
1619   "Move point to the Distribution header."
1620   (interactive)
1621   (message-position-on-field "Distribution"))
1622
1623 (defun message-goto-followup-to ()
1624   "Move point to the Followup-To header."
1625   (interactive)
1626   (message-position-on-field "Followup-To" "Newsgroups"))
1627
1628 (defun message-goto-keywords ()
1629   "Move point to the Keywords header."
1630   (interactive)
1631   (message-position-on-field "Keywords" "Subject"))
1632
1633 (defun message-goto-summary ()
1634   "Move point to the Summary header."
1635   (interactive)
1636   (message-position-on-field "Summary" "Subject"))
1637
1638 (defun message-goto-body ()
1639   "Move point to the beginning of the message body."
1640   (interactive)
1641   (if (looking-at "[ \t]*\n") (expand-abbrev))
1642   (goto-char (point-min))
1643   (search-forward (concat "\n" mail-header-separator "\n") nil t))
1644
1645 (defun message-goto-eoh ()
1646   "Move point to the end of the headers."
1647   (interactive)
1648   (message-goto-body)
1649   (forward-line -2))
1650
1651 (defun message-goto-signature ()
1652   "Move point to the beginning of the message signature.
1653 If there is no signature in the article, go to the end and
1654 return nil."
1655   (interactive)
1656   (goto-char (point-min))
1657   (if (re-search-forward message-signature-separator nil t)
1658       (forward-line 1)
1659     (goto-char (point-max))
1660     nil))
1661
1662 \f
1663
1664 (defun message-insert-to (&optional force)
1665   "Insert a To header that points to the author of the article being replied to.
1666 If the original author requested not to be sent mail, the function signals
1667 an error.
1668 With the prefix argument FORCE, insert the header anyway."
1669   (interactive "P")
1670   (let ((co (message-fetch-reply-field "mail-copies-to")))
1671     (when (and (null force)
1672                co
1673                (or (equal (downcase co) "never")
1674                    (equal (downcase co) "nobody")))
1675       (error "The user has requested not to have copies sent via mail")))
1676   (when (and (message-position-on-field "To")
1677              (mail-fetch-field "to")
1678              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1679     (insert ", "))
1680   (insert (or (message-fetch-reply-field "reply-to")
1681               (message-fetch-reply-field "from") "")))
1682
1683 (defun message-insert-newsgroups ()
1684   "Insert the Newsgroups header from the article being replied to."
1685   (interactive)
1686   (when (and (message-position-on-field "Newsgroups")
1687              (mail-fetch-field "newsgroups")
1688              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1689     (insert ","))
1690   (insert (or (message-fetch-reply-field "newsgroups") "")))
1691
1692 \f
1693
1694 ;;; Various commands
1695
1696 (defun message-delete-not-region (beg end)
1697   "Delete everything in the body of the current message that is outside of the region."
1698   (interactive "r")
1699   (save-excursion
1700     (goto-char end)
1701     (delete-region (point) (if (not (message-goto-signature))
1702                                (point)
1703                              (forward-line -2)
1704                              (point)))
1705     (insert "\n")
1706     (goto-char beg)
1707     (delete-region beg (progn (message-goto-body)
1708                               (forward-line 2)
1709                               (point))))
1710   (when (message-goto-signature)
1711     (forward-line -2)))
1712
1713 (defun message-kill-to-signature ()
1714   "Deletes all text up to the signature."
1715   (interactive)
1716   (let ((point (point)))
1717     (message-goto-signature)
1718     (unless (eobp)
1719       (forward-line -2))
1720     (kill-region point (point))
1721     (unless (bolp)
1722       (insert "\n"))))
1723
1724 (defun message-newline-and-reformat ()
1725   "Insert four newlines, and then reformat if inside quoted text."
1726   (interactive)
1727   (let ((point (point))
1728         quoted)
1729     (save-excursion
1730       (beginning-of-line)
1731       (setq quoted (looking-at (regexp-quote message-yank-prefix))))
1732     (insert "\n\n\n\n")
1733     (when quoted
1734       (insert message-yank-prefix))
1735     (fill-paragraph nil)
1736     (goto-char point)
1737     (forward-line 2)))
1738
1739 (defun message-insert-signature (&optional force)
1740   "Insert a signature.  See documentation for the `message-signature' variable."
1741   (interactive (list 0))
1742   (let* ((signature
1743           (cond
1744            ((and (null message-signature)
1745                  (eq force 0))
1746             (save-excursion
1747               (goto-char (point-max))
1748               (not (re-search-backward
1749                     message-signature-separator nil t))))
1750            ((and (null message-signature)
1751                  force)
1752             t)
1753            ((message-functionp message-signature)
1754             (funcall message-signature))
1755            ((listp message-signature)
1756             (eval message-signature))
1757            (t message-signature)))
1758          (signature
1759           (cond ((stringp signature)
1760                  signature)
1761                 ((and (eq t signature)
1762                       message-signature-file
1763                       (file-exists-p message-signature-file))
1764                  signature))))
1765     (when signature
1766       (goto-char (point-max))
1767       ;; Insert the signature.
1768       (unless (bolp)
1769         (insert "\n"))
1770       (insert "\n-- \n")
1771       (if (eq signature t)
1772           (insert-file-contents message-signature-file)
1773         (insert signature))
1774       (goto-char (point-max))
1775       (or (bolp) (insert "\n")))))
1776
1777 (defun message-elide-region (b e)
1778   "Elide the text between point and mark.
1779 An ellipsis (from `message-elide-elipsis') will be inserted where the
1780 text was killed."
1781   (interactive "r")
1782   (kill-region b e)
1783   (unless (bolp)
1784     (insert "\n"))
1785   (insert message-elide-elipsis))
1786
1787 (defvar message-caesar-translation-table nil)
1788
1789 (defun message-caesar-region (b e &optional n)
1790   "Caesar rotation of region by N, default 13, for decrypting netnews."
1791   (interactive
1792    (list
1793     (min (point) (or (mark t) (point)))
1794     (max (point) (or (mark t) (point)))
1795     (when current-prefix-arg
1796       (prefix-numeric-value current-prefix-arg))))
1797
1798   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1799   (unless (or (zerop n)                 ; no action needed for a rot of 0
1800               (= b e))                  ; no region to rotate
1801     ;; We build the table, if necessary.
1802     (when (or (not message-caesar-translation-table)
1803               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1804         (setq message-caesar-translation-table
1805               (message-make-caesar-translation-table n)))
1806     ;; Then we translate the region.  Do it this way to retain
1807     ;; text properties.
1808     (while (< b e)
1809       (when (< (char-after b) 255)
1810         (subst-char-in-region
1811          b (1+ b) (char-after b)
1812          (aref message-caesar-translation-table (char-after b))))
1813       (incf b))))
1814
1815 (defun message-make-caesar-translation-table (n)
1816   "Create a rot table with offset N."
1817   (let ((i -1)
1818         (table (make-string 256 0)))
1819     (while (< (incf i) 256)
1820       (aset table i i))
1821     (concat
1822      (substring table 0 ?A)
1823      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1824      (substring table ?A (+ ?A n))
1825      (substring table (+ ?A 26) ?a)
1826      (substring table (+ ?a n) (+ ?a n (- 26 n)))
1827      (substring table ?a (+ ?a n))
1828      (substring table (+ ?a 26) 255))))
1829
1830 (defun message-caesar-buffer-body (&optional rotnum)
1831   "Caesar rotates all letters in the current buffer by 13 places.
1832 Used to encode/decode possiblyun offensive messages (commonly in net.jokes).
1833 With prefix arg, specifies the number of places to rotate each letter forward.
1834 Mail and USENET news headers are not rotated."
1835   (interactive (if current-prefix-arg
1836                    (list (prefix-numeric-value current-prefix-arg))
1837                  (list nil)))
1838   (save-excursion
1839     (save-restriction
1840       (when (message-goto-body)
1841         (narrow-to-region (point) (point-max)))
1842       (message-caesar-region (point-min) (point-max) rotnum))))
1843
1844 (defun message-pipe-buffer-body (program)
1845   "Pipe the message body in the current buffer through PROGRAM."
1846   (save-excursion
1847     (save-restriction
1848       (when (message-goto-body)
1849         (narrow-to-region (point) (point-max)))
1850       (let ((body (buffer-substring (point-min) (point-max))))
1851         (unless (equal 0 (call-process-region
1852                            (point-min) (point-max) program t t))
1853             (insert body)
1854             (message "%s failed." program))))))
1855
1856 (defun message-rename-buffer (&optional enter-string)
1857   "Rename the *message* buffer to \"*message* RECIPIENT\".
1858 If the function is run with a prefix, it will ask for a new buffer
1859 name, rather than giving an automatic name."
1860   (interactive "Pbuffer name: ")
1861   (save-excursion
1862     (save-restriction
1863       (goto-char (point-min))
1864       (narrow-to-region (point)
1865                         (search-forward mail-header-separator nil 'end))
1866       (let* ((mail-to (or
1867                        (if (message-news-p) (message-fetch-field "Newsgroups")
1868                          (message-fetch-field "To"))
1869                        ""))
1870              (mail-trimmed-to
1871               (if (string-match "," mail-to)
1872                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1873                 mail-to))
1874              (name-default (concat "*message* " mail-trimmed-to))
1875              (name (if enter-string
1876                        (read-string "New buffer name: " name-default)
1877                      name-default)))
1878         (rename-buffer name t)))))
1879
1880 (defun message-fill-yanked-message (&optional justifyp)
1881   "Fill the paragraphs of a message yanked into this one.
1882 Numeric argument means justify as well."
1883   (interactive "P")
1884   (save-excursion
1885     (goto-char (point-min))
1886     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1887     (let ((fill-prefix message-yank-prefix))
1888       (fill-individual-paragraphs (point) (point-max) justifyp t))))
1889
1890 (defun message-indent-citation ()
1891   "Modify text just inserted from a message to be cited.
1892 The inserted text should be the region.
1893 When this function returns, the region is again around the modified text.
1894
1895 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1896 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1897   (let ((start (point)))
1898     ;; Remove unwanted headers.
1899     (when message-ignored-cited-headers
1900       (let (all-removed)
1901         (save-restriction
1902           (narrow-to-region
1903            (goto-char start)
1904            (if (search-forward "\n\n" nil t)
1905                (1- (point))
1906              (point)))
1907           (message-remove-header message-ignored-cited-headers t)
1908           (when (= (point-min) (point-max))
1909             (setq all-removed t))
1910           (goto-char (point-max)))
1911         (if all-removed
1912             (goto-char start)
1913           (forward-line 1))))
1914     ;; Delete blank lines at the start of the buffer.
1915     (while (and (point-min)
1916                 (eolp)
1917                 (not (eobp)))
1918       (message-delete-line))
1919     ;; Delete blank lines at the end of the buffer.
1920     (goto-char (point-max))
1921     (unless (eolp)
1922       (insert "\n"))
1923     (while (and (zerop (forward-line -1))
1924                 (looking-at "$"))
1925       (message-delete-line))
1926     ;; Do the indentation.
1927     (if (null message-yank-prefix)
1928         (indent-rigidly start (mark t) message-indentation-spaces)
1929       (save-excursion
1930         (goto-char start)
1931         (while (< (point) (mark t))
1932           (insert message-yank-prefix)
1933           (forward-line 1))))
1934     (goto-char start)))
1935
1936 (defvar gnus-article-copy)
1937 (defun message-yank-original (&optional arg)
1938   "Insert the message being replied to, if any.
1939 Puts point before the text and mark after.
1940 Normally indents each nonblank line ARG spaces (default 3).  However,
1941 if `message-yank-prefix' is non-nil, insert that prefix on each line.
1942
1943 This function uses `message-cite-function' to do the actual citing.
1944
1945 Just \\[universal-argument] as argument means don't indent, insert no
1946 prefix, and don't delete any headers."
1947   (interactive "P")
1948   (let ((modified (buffer-modified-p))
1949         (buffer (message-get-reply-buffer)))
1950     (when (and buffer
1951                message-cite-function)
1952       (delete-windows-on buffer t)
1953       (insert-buffer buffer)
1954       (funcall message-cite-function)
1955       (message-exchange-point-and-mark)
1956       (unless (bolp)
1957         (insert ?\n))
1958       (unless modified
1959         (setq message-checksum (message-checksum))))))
1960
1961 (defun message-cite-original-without-signature ()
1962   "Cite function in the standard Message manner."
1963   (let ((start (point))
1964         (end (mark t))
1965         (functions
1966          (when message-indent-citation-function
1967            (if (listp message-indent-citation-function)
1968                message-indent-citation-function
1969              (list message-indent-citation-function)))))
1970     (goto-char end)
1971     (when (re-search-backward "^-- $" start t)
1972       ;; Also peel off any blank lines before the signature.
1973       (forward-line -1)
1974       (while (looking-at "^[ \t]*$")
1975         (forward-line -1))
1976       (forward-line 1)
1977       (delete-region (point) end))
1978     (goto-char start)
1979     (while functions
1980       (funcall (pop functions)))
1981     (when message-citation-line-function
1982       (unless (bolp)
1983         (insert "\n"))
1984       (funcall message-citation-line-function))))
1985
1986 (defvar mail-citation-hook) ;Compiler directive
1987 (defun message-cite-original ()
1988   "Cite function in the standard Message manner."
1989   (if (and (boundp 'mail-citation-hook)
1990            mail-citation-hook)
1991       (run-hooks 'mail-citation-hook)
1992     (let ((start (point))
1993           (functions
1994            (when message-indent-citation-function
1995              (if (listp message-indent-citation-function)
1996                  message-indent-citation-function
1997                (list message-indent-citation-function)))))
1998       (goto-char start)
1999       (while functions
2000         (funcall (pop functions)))
2001       (when message-citation-line-function
2002         (unless (bolp)
2003           (insert "\n"))
2004         (funcall message-citation-line-function)))))
2005
2006 (defun message-insert-citation-line ()
2007   "Function that inserts a simple citation line."
2008   (when message-reply-headers
2009     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
2010
2011 (defun message-position-on-field (header &rest afters)
2012   (let ((case-fold-search t))
2013     (save-restriction
2014       (narrow-to-region
2015        (goto-char (point-min))
2016        (progn
2017          (re-search-forward
2018           (concat "^" (regexp-quote mail-header-separator) "$"))
2019          (match-beginning 0)))
2020       (goto-char (point-min))
2021       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
2022           (progn
2023             (re-search-forward "^[^ \t]" nil 'move)
2024             (beginning-of-line)
2025             (skip-chars-backward "\n")
2026             t)
2027         (while (and afters
2028                     (not (re-search-forward
2029                           (concat "^" (regexp-quote (car afters)) ":")
2030                           nil t)))
2031           (pop afters))
2032         (when afters
2033           (re-search-forward "^[^ \t]" nil 'move)
2034           (beginning-of-line))
2035         (insert header ": \n")
2036         (forward-char -1)
2037         nil))))
2038
2039 (defun message-remove-signature ()
2040   "Remove the signature from the text between point and mark.
2041 The text will also be indented the normal way."
2042   (save-excursion
2043     (let ((start (point))
2044           mark)
2045       (if (not (re-search-forward message-signature-separator (mark t) t))
2046           ;; No signature here, so we just indent the cited text.
2047           (message-indent-citation)
2048         ;; Find the last non-empty line.
2049         (forward-line -1)
2050         (while (looking-at "[ \t]*$")
2051           (forward-line -1))
2052         (forward-line 1)
2053         (setq mark (set-marker (make-marker) (point)))
2054         (goto-char start)
2055         (message-indent-citation)
2056         ;; Enable undoing the deletion.
2057         (undo-boundary)
2058         (delete-region mark (mark t))
2059         (set-marker mark nil)))))
2060
2061 \f
2062
2063 ;;;
2064 ;;; Sending messages
2065 ;;;
2066
2067 ;; Avoid byte-compile warning.
2068 (defvar message-encoding-buffer nil)
2069 (defvar message-edit-buffer nil)
2070 (defvar message-mime-mode nil)
2071
2072 (defun message-send-and-exit (&optional arg)
2073   "Send message like `message-send', then, if no errors, exit from mail buffer."
2074   (interactive "P")
2075   (let ((buf (current-buffer))
2076         (actions message-exit-actions)
2077         (frame (selected-frame))
2078         (org-frame message-original-frame))
2079     (when (and (message-send arg)
2080                (buffer-name buf))
2081       (if message-kill-buffer-on-exit
2082           (kill-buffer buf)
2083         (bury-buffer buf)
2084         (when (eq buf (current-buffer))
2085           (message-bury buf)))
2086       (message-do-actions actions)
2087       (message-delete-frame frame org-frame)
2088       t)))
2089
2090 (defun message-dont-send ()
2091   "Don't send the message you have been editing."
2092   (interactive)
2093   (set-buffer-modified-p t)
2094   (save-buffer)
2095   (let ((actions message-postpone-actions))
2096     (message-bury (current-buffer))
2097     (message-do-actions actions)))
2098
2099 (defun message-kill-buffer ()
2100   "Kill the current buffer."
2101   (interactive)
2102   (when (or (not (buffer-modified-p))
2103             (eq t message-kill-buffer-query-function)
2104             (funcall message-kill-buffer-query-function
2105                      "The buffer modified; kill anyway? "))
2106     (let ((actions message-kill-actions)
2107           (frame (selected-frame))
2108           (org-frame message-original-frame))
2109       (setq buffer-file-name nil)
2110       (kill-buffer (current-buffer))
2111       (message-do-actions actions)
2112       (message-delete-frame frame org-frame)))
2113   (message ""))
2114
2115 (defun message-delete-frame (frame org-frame)
2116   "Delete frame for editing message."
2117   (when (and (or (and (featurep 'xemacs)
2118                       (not (eq 'tty (device-type))))
2119                  window-system
2120                  (>= emacs-major-version 20))
2121              (or (and (eq message-delete-frame-on-exit t)
2122                       (select-frame frame)
2123                       (or (eq frame org-frame)
2124                           (prog1
2125                               (y-or-n-p "Delete this frame?")
2126                             (message ""))))
2127                  (and (eq message-delete-frame-on-exit 'ask)
2128                       (select-frame frame)
2129                       (prog1
2130                           (y-or-n-p "Delete this frame?")
2131                         (message "")))))
2132     (delete-frame frame)))
2133
2134 (defun message-bury (buffer)
2135   "Bury this mail buffer."
2136   (let ((newbuf (other-buffer buffer)))
2137     (bury-buffer buffer)
2138     (if (and (fboundp 'frame-parameters)
2139              (cdr (assq 'dedicated (frame-parameters)))
2140              (not (null (delq (selected-frame) (visible-frame-list)))))
2141         (delete-frame (selected-frame))
2142       (switch-to-buffer newbuf))))
2143
2144 (defun message-send (&optional arg)
2145   "Send the message in the current buffer.
2146 If `message-interactive' is non-nil, wait for success indication
2147 or error messages, and inform user.
2148 Otherwise any failure is reported in a message back to
2149 the user from the mailer."
2150   (interactive "P")
2151   ;; Disabled test.
2152   (when (or (buffer-modified-p)
2153             (message-check-element 'unchanged)
2154             (y-or-n-p "No changes in the buffer; really send? "))
2155     ;; Make it possible to undo the coming changes.
2156     (undo-boundary)
2157     (let ((inhibit-read-only t))
2158       (put-text-property (point-min) (point-max) 'read-only nil))
2159     (run-hooks 'message-send-hook)
2160     (message "Sending...")
2161     (let ((message-encoding-buffer
2162            (message-generate-new-buffer-clone-locals " message encoding"))
2163           (message-edit-buffer (current-buffer))
2164           (message-mime-mode mime-edit-mode-flag)
2165           (alist message-send-method-alist)
2166           (success t)
2167           elem sent)
2168       (save-excursion
2169         (set-buffer message-encoding-buffer)
2170         (erase-buffer)
2171         (insert-buffer message-edit-buffer)
2172         (funcall message-encode-function)
2173         (message-fix-before-sending)
2174         (while (and success
2175                     (setq elem (pop alist)))
2176           (when (and (or (not (funcall (cadr elem)))
2177                          (and (or (not (memq (car elem)
2178                                              message-sent-message-via))
2179                                   (y-or-n-p
2180                                    (format
2181                                     "Already sent message via %s; resend? "
2182                                     (car elem))))
2183                               (setq success (funcall (caddr elem) arg)))))
2184             (setq sent t))))
2185       (when (and success sent)
2186         (message-do-fcc)
2187         ;;(when (fboundp 'mail-hist-put-headers-into-history)
2188         ;; (mail-hist-put-headers-into-history))
2189         (run-hooks 'message-sent-hook)
2190         (message "Sending...done")
2191         ;; Mark the buffer as unmodified and delete autosave.
2192         (set-buffer-modified-p nil)
2193         (delete-auto-save-file-if-necessary t)
2194         (message-disassociate-draft)
2195         ;; Delete other mail buffers and stuff.
2196         (message-do-send-housekeeping)
2197         (message-do-actions message-send-actions)
2198         ;; Return success.
2199         t))))
2200
2201 (defun message-send-via-mail (arg)
2202   "Send the current message via mail."
2203   (message-send-mail arg))
2204
2205 (defun message-send-via-news (arg)
2206   "Send the current message via news."
2207   (message-send-news arg))
2208
2209 (defmacro message-check (type &rest forms)
2210   "Eval FORMS if TYPE is to be checked."
2211   `(or (message-check-element ,type)
2212        (save-excursion
2213          ,@forms)))
2214
2215 (put 'message-check 'lisp-indent-function 1)
2216 (put 'message-check 'edebug-form-spec '(form body))
2217
2218 (defun message-fix-before-sending ()
2219   "Do various things to make the message nice before sending it."
2220   ;; Make sure there's a newline at the end of the message.
2221   (goto-char (point-max))
2222   (unless (bolp)
2223     (insert "\n"))
2224   ;; Delete all invisible text.
2225   (message-check 'invisible-text
2226     (when (text-property-any (point-min) (point-max) 'invisible t)
2227       (put-text-property (point-min) (point-max) 'invisible nil)
2228       (unless (yes-or-no-p "Invisible text found and made visible; continue posting? ")
2229         (error "Invisible text found and made visible")))))
2230
2231 (defun message-add-action (action &rest types)
2232   "Add ACTION to be performed when doing an exit of type TYPES."
2233   (let (var)
2234     (while types
2235       (set (setq var (intern (format "message-%s-actions" (pop types))))
2236            (nconc (symbol-value var) (list action))))))
2237
2238 (defun message-do-actions (actions)
2239   "Perform all actions in ACTIONS."
2240   ;; Now perform actions on successful sending.
2241   (while actions
2242     (ignore-errors
2243       (cond
2244        ;; A simple function.
2245        ((message-functionp (car actions))
2246         (funcall (car actions)))
2247        ;; Something to be evaled.
2248        (t
2249         (eval (car actions)))))
2250     (pop actions)))
2251
2252 (defun message-send-mail (&optional arg)
2253   (require 'mail-utils)
2254   (let ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2255         (case-fold-search nil)
2256         (news (message-news-p)))
2257     (save-restriction
2258       (message-narrow-to-headers)
2259       ;; Insert some headers.
2260       (let ((message-deletable-headers
2261              (if news nil message-deletable-headers)))
2262         (message-generate-headers message-required-mail-headers))
2263       ;; Let the user do all of the above.
2264       (run-hooks 'message-header-hook))
2265     (unwind-protect
2266         (save-excursion
2267           (set-buffer tembuf)
2268           (erase-buffer)
2269           (insert-buffer message-encoding-buffer)
2270           ;; Remove some headers.
2271           (save-restriction
2272             (message-narrow-to-headers)
2273             ;; Remove some headers.
2274             (message-remove-header message-ignored-mail-headers t))
2275           (goto-char (point-max))
2276           ;; require one newline at the end.
2277           (or (= (preceding-char) ?\n)
2278               (insert ?\n))
2279           (when (and news
2280                      (or (message-fetch-field "cc")
2281                          (message-fetch-field "to")))
2282             (message-insert-courtesy-copy))
2283 ;;        (mime-edit-maybe-split-and-send
2284 ;;         (function
2285 ;;          (lambda ()
2286 ;;            (interactive)
2287 ;;            (funcall message-send-mail-function)
2288 ;;            )))
2289           (mime-edit-maybe-split-and-send
2290            (function
2291             (lambda ()
2292               (interactive)
2293               (save-restriction
2294                 (std11-narrow-to-header mail-header-separator)
2295                 (goto-char (point-min))
2296                 (when (re-search-forward "^Message-Id:" nil t)
2297                   (delete-region (match-end 0)(std11-field-end))
2298                   (insert (concat " " (message-make-message-id)))
2299                   ))
2300               (funcall message-send-mail-function))))
2301           (funcall message-send-mail-function))
2302       (kill-buffer tembuf))
2303     (set-buffer message-edit-buffer)
2304     (push 'mail message-sent-message-via)))
2305
2306 (defun message-send-mail-with-sendmail ()
2307   "Send off the prepared buffer with sendmail."
2308   (let ((errbuf (if message-interactive
2309                     (generate-new-buffer " sendmail errors")
2310                   0))
2311         resend-to-addresses delimline)
2312     (let ((case-fold-search t))
2313       (save-restriction
2314         (message-narrow-to-headers)
2315         (setq resend-to-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-to-addresses
2356                          (list resend-to-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 (and (> (current-column) 78)
3366                        last)
3367                   (save-excursion
3368                     (goto-char last)
3369                     (looking-at "[ \t]*")
3370                     (replace-match "\n " t t)))
3371               (setq last (1+ (point))))
3372           (setq quoted (not quoted)))
3373         (unless (eobp)
3374           (forward-char 1))))
3375     (goto-char (point-max))
3376     (widen)
3377     (forward-line 1)))
3378
3379 (defun message-fill-references (header value)
3380   (insert (capitalize (symbol-name header))
3381           ": "
3382           (std11-fill-msg-id-list-string
3383           (if (consp value) (car value) value))
3384           "\n"))
3385
3386 (defun message-fill-header (header value)
3387   (let ((begin (point))
3388         (fill-column 78)
3389         (fill-prefix " "))
3390     (insert (capitalize (symbol-name header))
3391             ": "
3392             (if (consp value) (car value) value)
3393             "\n")
3394     (save-restriction
3395       (narrow-to-region begin (point))
3396       (fill-region-as-paragraph begin (point))
3397       ;; Tapdance around looong Message-IDs.
3398       (forward-line -1)
3399       (when (looking-at "[ \t]*$")
3400         (message-delete-line))
3401       (goto-char begin)
3402       (re-search-forward ":" nil t)
3403       (when (looking-at "\n[ \t]+")
3404         (replace-match " " t t))
3405       (goto-char (point-max)))))
3406
3407 (defun message-shorten-references (header references)
3408   "Limit REFERENCES to be shorter than 988 characters."
3409   (let ((max 988)
3410         (cut 4)
3411         refs)
3412     (with-temp-buffer
3413       (insert references)
3414       (goto-char (point-min))
3415       (while (re-search-forward "<[^>]+>" nil t)
3416         (push (match-string 0) refs))
3417       (setq refs (nreverse refs))
3418       (while (> (length (mapconcat 'identity refs " ")) max)
3419         (when (< (length refs) (1+ cut))
3420           (decf cut))
3421         (setcdr (nthcdr cut refs) (cddr (nthcdr cut refs)))))
3422     (insert (capitalize (symbol-name header)) ": "
3423             (mapconcat 'identity refs " ") "\n")))
3424
3425 (defun message-position-point ()
3426   "Move point to where the user probably wants to find it."
3427   (message-narrow-to-headers)
3428   (cond
3429    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3430     (search-backward ":" )
3431     (widen)
3432     (forward-char 1)
3433     (if (= (following-char) ? )
3434         (forward-char 1)
3435       (insert " ")))
3436    (t
3437     (goto-char (point-max))
3438     (widen)
3439     (forward-line 1)
3440     (unless (looking-at "$")
3441       (forward-line 2)))
3442    (sit-for 0)))
3443
3444 (defun message-buffer-name (type &optional to group)
3445   "Return a new (unique) buffer name based on TYPE and TO."
3446   (cond
3447    ;; Check whether `message-generate-new-buffers' is a function,
3448    ;; and if so, call it.
3449    ((message-functionp message-generate-new-buffers)
3450     (funcall message-generate-new-buffers type to group))
3451    ;; Generate a new buffer name The Message Way.
3452    (message-generate-new-buffers
3453     (generate-new-buffer-name
3454      (concat "*" type
3455              (if to
3456                  (concat " to "
3457                          (or (car (std11-extract-address-components to))
3458                              to) "")
3459                "")
3460              (if (and group (not (string= group ""))) (concat " on " group) "")
3461              "*")))
3462    ;; Use standard name.
3463    (t
3464     (format "*%s message*" type))))
3465
3466 (defun message-pop-to-buffer (name)
3467   "Pop to buffer NAME, and warn if it already exists and is modified."
3468   (let ((pop-up-frames pop-up-frames)
3469         (special-display-buffer-names special-display-buffer-names)
3470         (special-display-regexps special-display-regexps)
3471         (same-window-buffer-names same-window-buffer-names)
3472         (same-window-regexps same-window-regexps)
3473         (buffer (get-buffer name))
3474         (cur (current-buffer)))
3475     (if (or (and (featurep 'xemacs)
3476                  (not (eq 'tty (device-type))))
3477             window-system
3478             (>= emacs-major-version 20))
3479         (when message-use-multi-frames
3480           (setq pop-up-frames t
3481                 special-display-buffer-names nil
3482                 special-display-regexps nil
3483                 same-window-buffer-names nil
3484                 same-window-regexps nil))
3485       (setq pop-up-frames nil))
3486     (if (and buffer
3487              (buffer-name buffer))
3488         (progn
3489           (set-buffer (pop-to-buffer buffer))
3490           (when (and (buffer-modified-p)
3491                      (not (y-or-n-p
3492                            "Message already being composed; erase? ")))
3493             (error "Message being composed")))
3494       (set-buffer (pop-to-buffer name)))
3495     (erase-buffer)
3496     (message-mode)
3497     (when pop-up-frames
3498       (make-local-variable 'message-original-frame)
3499       (setq message-original-frame (selected-frame)))))
3500
3501 (defun message-do-send-housekeeping ()
3502   "Kill old message buffers."
3503   ;; We might have sent this buffer already.  Delete it from the
3504   ;; list of buffers.
3505   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3506   (while (and message-max-buffers
3507               message-buffer-list
3508               (>= (length message-buffer-list) message-max-buffers))
3509     ;; Kill the oldest buffer -- unless it has been changed.
3510     (let ((buffer (pop message-buffer-list)))
3511       (when (and (buffer-name buffer)
3512                  (not (buffer-modified-p buffer)))
3513         (kill-buffer buffer))))
3514   ;; Rename the buffer.
3515   (if message-send-rename-function
3516       (funcall message-send-rename-function)
3517     (when (string-match "\\`\\*" (buffer-name))
3518       (rename-buffer
3519        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3520   ;; Push the current buffer onto the list.
3521   (when message-max-buffers
3522     (setq message-buffer-list
3523           (nconc message-buffer-list (list (current-buffer))))))
3524
3525 (defvar mc-modes-alist)
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         from subject date to cc
3640         references message-id follow-to
3641         (inhibit-point-motion-hooks t)
3642         mct never-mct mft mrt 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           (make-full-mail-header-from-decoded-header
3780            0 subject from date message-id references 0 0 ""))
3781
3782     (message-setup
3783      `((Subject . ,subject)
3784        ,@follow-to
3785        ,@(if (or references message-id)
3786              `((References . ,(concat (or references "") (and references " ")
3787                                       (or message-id ""))))))
3788      cur)))
3789
3790 ;;;###autoload
3791 (defun message-wide-reply (&optional to-address)
3792   "Make a \"wide\" reply to the message in the current buffer."
3793   (interactive)
3794   (message-reply to-address t))
3795
3796 ;;;###autoload
3797 (defun message-followup (&optional to-newsgroups)
3798   "Follow up to the message in the current buffer.
3799 If TO-NEWSGROUPS, use that as the new Newsgroups line."
3800   (interactive)
3801   (let ((cur (current-buffer))
3802         from subject date mct
3803         references message-id follow-to
3804         (inhibit-point-motion-hooks t)
3805         (message-this-is-news t)
3806         followup-to distribution newsgroups gnus-warning posted-to mft mrt)
3807     (save-restriction
3808       (message-narrow-to-head)
3809       (when (message-functionp message-followup-to-function)
3810         (setq follow-to
3811               (funcall message-followup-to-function)))
3812       (setq from (message-fetch-field "from")
3813             date (message-fetch-field "date" t)
3814             subject (or (message-fetch-field "subject") "none")
3815             references (message-fetch-field "references")
3816             message-id (message-fetch-field "message-id" t)
3817             followup-to (when message-use-followup-to
3818                           (message-fetch-field "followup-to"))
3819             distribution (message-fetch-field "distribution")
3820             newsgroups (message-fetch-field "newsgroups")
3821             posted-to (message-fetch-field "posted-to")
3822             mct (when message-use-mail-copies-to
3823                   (message-fetch-field "mail-copies-to"))
3824             mft (when message-use-mail-followup-to
3825                   (message-fetch-field "mail-followup-to"))
3826             mrt (when message-use-mail-reply-to
3827                   (or (message-fetch-field "mail-reply-to")
3828                       (message-fetch-field "reply-to")))
3829             gnus-warning (message-fetch-field "gnus-warning"))
3830       (when (and gnus-warning (string-match "<[^>]+>" gnus-warning))
3831         (setq message-id (match-string 0 gnus-warning)))
3832       ;; Remove bogus distribution.
3833       (when (and (stringp distribution)
3834                  (let ((case-fold-search t))
3835                    (string-match "world" distribution)))
3836         (setq distribution nil))
3837       ;; Remove any (buggy) Re:'s that are present and make a
3838       ;; proper one.
3839       (setq subject (message-make-followup-subject subject))
3840       (widen))
3841
3842     ;; Handle special values of Mail-Copies-To.
3843     (when mct
3844       (cond
3845        ((and (or (equal (downcase mct) "never")
3846                  (equal (downcase mct) "nobody"))
3847              (or (not (eq message-use-mail-copies-to 'ask))
3848                  (message-y-or-n-p
3849                   (concat "Obey Mail-Copies-To: never? ") t "\
3850 You should normally obey the Mail-Copies-To: header.
3851
3852         `Mail-Copies-To: never'
3853 directs you not to send your response to the author.")))
3854         (setq mct nil))
3855        ((and (or (equal (downcase mct) "always")
3856                  (equal (downcase mct) "poster"))
3857              (or (not (eq message-use-mail-copies-to 'ask))
3858                  (message-y-or-n-p
3859                   (concat "Obey Mail-Copies-To: always? ") t "\
3860 You should normally obey the Mail-Copies-To: header.
3861
3862         `Mail-Copies-To: always'
3863 sends a copy of your response to the author.")))
3864         (setq mct (or mrt from)))
3865        ((and (eq message-use-mail-copies-to 'ask)
3866              (not 
3867               (message-y-or-n-p
3868                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
3869 You should normally obey the Mail-Copies-To: header.
3870
3871         `Mail-Copies-To: " mct "'
3872 sends a copy of your response to " (if (string-match "," mct)
3873                                        "the specified addresses"
3874                                      "that address") ".")))
3875         (setq mct nil))
3876        ))
3877
3878     (unless follow-to
3879       (cond
3880        (to-newsgroups (setq follow-to (list (cons 'Newsgroups to-newsgroups))))
3881        ;; Handle Followup-To.
3882        (followup-to
3883         (cond
3884          ((equal (downcase followup-to) "poster")
3885           (if (or (eq message-use-followup-to 'use)
3886                   (message-y-or-n-p "Obey Followup-To: poster? " t "\
3887 You should normally obey the Followup-To: header.
3888
3889         `Followup-To: poster'
3890 sends your response via e-mail instead of news.
3891
3892 A typical situation where `Followup-To: poster' is used is when the author
3893 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3894               (setq message-this-is-news nil
3895                     distribution nil
3896                     follow-to (list (cons 'To (or mrt from ""))))
3897             (setq follow-to (list (cons 'Newsgroups newsgroups)))))
3898          (t
3899           (if (or (equal followup-to newsgroups)
3900                   (not (eq message-use-followup-to 'ask))
3901                   (message-y-or-n-p
3902                    (concat "Obey Followup-To: " followup-to "? ") t "\
3903 You should normally obey the Followup-To: header.
3904
3905         `Followup-To: " followup-to "'
3906 directs your response to " (if (string-match "," followup-to)
3907                                "the specified newsgroups"
3908                              "that newsgroup only") ".
3909
3910 If a message is posted to several newsgroups, Followup-To is often
3911 used to direct the following discussion to one newsgroup only,
3912 because discussions that are spread over several newsgroup tend to
3913 be fragmented and very difficult to follow.
3914
3915 Also, some source/announcement newsgroups are not indented for discussion;
3916 responses here are directed to other newsgroups."))
3917               (setq follow-to (list (cons 'Newsgroups followup-to)))
3918             (setq follow-to (list (cons 'Newsgroups newsgroups)))))))
3919        ;; Handle Mail-Followup-To, followup via e-mail.
3920        ((and mft
3921              (or (not (eq message-use-mail-followup-to 'ask))
3922                  (message-y-or-n-p
3923                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
3924 You should normally obey the Mail-Followup-To: header.
3925
3926         `Mail-Followup-To: " mft "'
3927 directs your response to " (if (string-match "," mft)
3928                                "the specified addresses"
3929                              "that address only") " instead of news.
3930
3931 A typical situation where Mail-Followup-To is used is when the author thinks
3932 that further discussion should take place only in "
3933                              (if (string-match "," mft)
3934                                  "the specified mailing lists"
3935                                "that mailing list") ".")))
3936         (setq message-this-is-news nil
3937               distribution nil
3938               follow-to (list (cons 'To mft))))
3939        (posted-to (setq follow-to (list (cons 'Newsgroups posted-to))))
3940        (t
3941         (setq follow-to (list (cons 'Newsgroups newsgroups))))))
3942
3943     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3944
3945     (setq message-reply-headers
3946           (make-full-mail-header-from-decoded-header
3947            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