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