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