1998-10-03 Katsumi Yamaoka <yamaoka@jpl.org>
[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   (substitute-key-definition 'kill-buffer 'message-kill-buffer
1390                              message-mode-map))
1391
1392 (easy-menu-define
1393  message-mode-menu message-mode-map "Message Menu."
1394  '("Message"
1395    ["Sort Headers" message-sort-headers t]
1396    ["Yank Original" message-yank-original t]
1397    ["Fill Yanked Message" message-fill-yanked-message t]
1398    ["Insert Signature" message-insert-signature t]
1399    ["Caesar (rot13) Message" message-caesar-buffer-body t]
1400    ["Caesar (rot13) Region" message-caesar-region (mark t)]
1401    ["Elide Region" message-elide-region (mark t)]
1402    ["Delete Outside Region" message-delete-not-region (mark t)]
1403    ["Kill To Signature" message-kill-to-signature t]
1404    ["Newline and Reformat" message-newline-and-reformat t]
1405    ["Rename buffer" message-rename-buffer t]
1406    ["Spellcheck" ispell-message t]
1407    "----"
1408    ["Send Message" message-send-and-exit t]
1409    ["Abort Message" message-dont-send t]
1410    ["Kill Message" message-kill-buffer t]))
1411
1412 (easy-menu-define
1413  message-mode-field-menu message-mode-map ""
1414  '("Field"
1415    ["Fetch To" message-insert-to t]
1416    ["Fetch Newsgroups" message-insert-newsgroups t]
1417    "----"
1418    ["To" message-goto-to t]
1419    ["Subject" message-goto-subject t]
1420    ["Cc" message-goto-cc t]
1421    ["Reply-To" message-goto-reply-to t]
1422    ["Mail-Reply-To" message-goto-mail-reply-to t]
1423    ["Mail-Followup-To" message-goto-mail-followup-to t]
1424    ["Mail-Copies-To" message-goto-mail-copies-to t]
1425    ["Summary" message-goto-summary t]
1426    ["Keywords" message-goto-keywords t]
1427    ["Newsgroups" message-goto-newsgroups t]
1428    ["Followup-To" message-goto-followup-to t]
1429    ["Distribution" message-goto-distribution t]
1430    ["Body" message-goto-body t]
1431    ["Signature" message-goto-signature t]))
1432
1433 (defvar facemenu-add-face-function)
1434 (defvar facemenu-remove-face-function)
1435
1436 ;;;###autoload
1437 (defun message-mode ()
1438   "Major mode for editing mail and news to be sent.
1439 Like Text Mode but with these additional commands:
1440 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
1441 C-c C-f  move to a header field (and create it if there isn't):
1442          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1443          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1444          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1445          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1446          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1447          C-c C-f C-m  move to Mail-Followup-To
1448          C-c C-f C-f  move to Followup-To
1449 C-c C-t  message-insert-to (add a To header to a news followup)
1450 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
1451 C-c C-b  message-goto-body (move to beginning of message text).
1452 C-c C-i  message-goto-signature (move to the beginning of the signature).
1453 C-c C-w  message-insert-signature (insert `message-signature-file' file).
1454 C-c C-y  message-yank-original (insert current message, if any).
1455 C-c C-q  message-fill-yanked-message (fill what was yanked).
1456 C-c C-e  message-elide-region (elide the text between point and mark).
1457 C-c C-z  message-kill-to-signature (kill the text up to the signature).
1458 C-c C-r  message-caesar-buffer-body (rot13 the message body)."
1459   (interactive)
1460   (kill-all-local-variables)
1461   (make-local-variable 'message-reply-buffer)
1462   (setq message-reply-buffer nil)
1463   (make-local-variable 'message-send-actions) 
1464   (make-local-variable 'message-exit-actions) 
1465   (make-local-variable 'message-kill-actions)
1466   (make-local-variable 'message-postpone-actions)
1467   (make-local-variable 'message-draft-article)
1468   (make-local-hook 'kill-buffer-hook)
1469   (set-syntax-table message-mode-syntax-table)
1470   (use-local-map message-mode-map)
1471   (setq local-abbrev-table message-mode-abbrev-table)
1472   (setq major-mode 'message-mode)
1473   (setq mode-name "Message")
1474   (setq buffer-offer-save t)
1475   (make-local-variable 'facemenu-add-face-function)
1476   (make-local-variable 'facemenu-remove-face-function)
1477   (setq facemenu-add-face-function
1478         (lambda (face end)
1479           (let ((face-fun (cdr (assq face message-face-alist))))
1480             (if face-fun
1481                 (funcall face-fun (point) end)
1482               (error "Face %s not configured for %s mode" face mode-name)))
1483           "")
1484         facemenu-remove-face-function t)
1485   (make-local-variable 'paragraph-separate)
1486   (make-local-variable 'paragraph-start)
1487   ;; `-- ' precedes the signature.  `-----' appears at the start of the
1488   ;; lines that delimit forwarded messages.
1489   ;; Lines containing just >= 3 dashes, perhaps after whitespace,
1490   ;; are also sometimes used and should be separators.
1491   (setq paragraph-start
1492         (concat (regexp-quote mail-header-separator)
1493                 "$\\|[ \t]*[a-z0-9A-Z]*>+[ \t]*$\\|[ \t]*$\\|"
1494                 "-- $\\|---+$\\|"
1495                 page-delimiter
1496                 ;;!!! Uhm... shurely this can't be right?
1497                 "[> " (regexp-quote message-yank-prefix) "]+$"))
1498   (setq paragraph-separate paragraph-start)
1499   (make-local-variable 'message-reply-headers)
1500   (setq message-reply-headers nil)
1501   (make-local-variable 'message-user-agent)
1502   (make-local-variable 'message-post-method)
1503   (make-local-variable 'message-sent-message-via)
1504   (setq message-sent-message-via nil)
1505   (make-local-variable 'message-checksum)
1506   (setq message-checksum nil)
1507   ;;(when (fboundp 'mail-hist-define-keys)
1508   ;;  (mail-hist-define-keys))
1509   (when (string-match "XEmacs\\|Lucid" emacs-version)
1510     (message-setup-toolbar))
1511   (easy-menu-add message-mode-menu message-mode-map)
1512   (easy-menu-add message-mode-field-menu message-mode-map)
1513   ;; Allow mail alias things.
1514   (when (eq message-mail-alias-type 'abbrev)
1515     (if (fboundp 'mail-abbrevs-setup)
1516         (mail-abbrevs-setup)
1517       (mail-aliases-setup)))
1518   (message-set-auto-save-file-name)
1519   (unless (string-match "XEmacs" emacs-version)
1520     (set (make-local-variable 'font-lock-defaults)
1521          '(message-font-lock-keywords t)))
1522   (make-local-variable 'adaptive-fill-regexp)
1523   (setq adaptive-fill-regexp
1524         (concat "[ \t]*[-a-z0-9A-Z]*>+[ \t]*\\|" adaptive-fill-regexp))
1525   (unless (boundp 'adaptive-fill-first-line-regexp)
1526     (setq adaptive-fill-first-line-regexp nil))
1527   (make-local-variable 'adaptive-fill-first-line-regexp)
1528   (setq adaptive-fill-first-line-regexp
1529         (concat "[ \t]*[-a-z0-9A-Z]*>+[ \t]*\\|"
1530                 adaptive-fill-first-line-regexp))
1531   (run-hooks 'text-mode-hook 'message-mode-hook))
1532
1533 \f
1534
1535 ;;;
1536 ;;; Message mode commands
1537 ;;;
1538
1539 ;;; Movement commands
1540
1541 (defun message-goto-to ()
1542   "Move point to the To header."
1543   (interactive)
1544   (message-position-on-field "To"))
1545
1546 (defun message-goto-subject ()
1547   "Move point to the Subject header."
1548   (interactive)
1549   (message-position-on-field "Subject"))
1550
1551 (defun message-goto-cc ()
1552   "Move point to the Cc header."
1553   (interactive)
1554   (message-position-on-field "Cc" "To"))
1555
1556 (defun message-goto-bcc ()
1557   "Move point to the Bcc  header."
1558   (interactive)
1559   (message-position-on-field "Bcc" "Cc" "To"))
1560
1561 (defun message-goto-fcc ()
1562   "Move point to the Fcc header."
1563   (interactive)
1564   (message-position-on-field "Fcc" "To" "Newsgroups"))
1565
1566 (defun message-goto-reply-to ()
1567   "Move point to the Reply-To header."
1568   (interactive)
1569   (message-position-on-field "Reply-To" "Subject"))
1570
1571 (defun message-goto-mail-reply-to ()
1572   "Move point to the Mail-Reply-To header."
1573   (interactive)
1574   (message-position-on-field "Mail-Reply-To" "Subject"))
1575
1576 (defun message-goto-mail-followup-to ()
1577   "Move point to the Mail-Followup-To header."
1578   (interactive)
1579   (message-position-on-field "Mail-Followup-To" "Subject"))
1580
1581 (defun message-goto-mail-copies-to ()
1582   "Move point to the Mail-Copies-To header."
1583   (interactive)
1584   (message-position-on-field "Mail-Copies-To" "Subject"))
1585
1586 (defun message-goto-newsgroups ()
1587   "Move point to the Newsgroups header."
1588   (interactive)
1589   (message-position-on-field "Newsgroups"))
1590
1591 (defun message-goto-distribution ()
1592   "Move point to the Distribution header."
1593   (interactive)
1594   (message-position-on-field "Distribution"))
1595
1596 (defun message-goto-followup-to ()
1597   "Move point to the Followup-To header."
1598   (interactive)
1599   (message-position-on-field "Followup-To" "Newsgroups"))
1600
1601 (defun message-goto-keywords ()
1602   "Move point to the Keywords header."
1603   (interactive)
1604   (message-position-on-field "Keywords" "Subject"))
1605
1606 (defun message-goto-summary ()
1607   "Move point to the Summary header."
1608   (interactive)
1609   (message-position-on-field "Summary" "Subject"))
1610
1611 (defun message-goto-body ()
1612   "Move point to the beginning of the message body."
1613   (interactive)
1614   (if (looking-at "[ \t]*\n") (expand-abbrev))
1615   (goto-char (point-min))
1616   (search-forward (concat "\n" mail-header-separator "\n") nil t))
1617
1618 (defun message-goto-eoh ()
1619   "Move point to the end of the headers."
1620   (interactive)
1621   (message-goto-body)
1622   (forward-line -2))
1623
1624 (defun message-goto-signature ()
1625   "Move point to the beginning of the message signature.
1626 If there is no signature in the article, go to the end and
1627 return nil."
1628   (interactive)
1629   (goto-char (point-min))
1630   (if (re-search-forward message-signature-separator nil t)
1631       (forward-line 1)
1632     (goto-char (point-max))
1633     nil))
1634
1635 \f
1636
1637 (defun message-insert-to (&optional force)
1638   "Insert a To header that points to the author of the article being replied to.
1639 If the original author requested not to be sent mail, the function signals
1640 an error.
1641 With the prefix argument FORCE, insert the header anyway."
1642   (interactive "P")
1643   (let ((co (message-fetch-reply-field "mail-copies-to")))
1644     (when (and (null force)
1645                co
1646                (equal (downcase co) "never"))
1647       (error "The user has requested not to have copies sent via mail")))
1648   (when (and (message-position-on-field "To")
1649              (mail-fetch-field "to")
1650              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1651     (insert ", "))
1652   (insert (or (message-fetch-reply-field "reply-to")
1653               (message-fetch-reply-field "from") "")))
1654
1655 (defun message-insert-newsgroups ()
1656   "Insert the Newsgroups header from the article being replied to."
1657   (interactive)
1658   (when (and (message-position-on-field "Newsgroups")
1659              (mail-fetch-field "newsgroups")
1660              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1661     (insert ","))
1662   (insert (or (message-fetch-reply-field "newsgroups") "")))
1663
1664 \f
1665
1666 ;;; Various commands
1667
1668 (defun message-delete-not-region (beg end)
1669   "Delete everything in the body of the current message that is outside of the region."
1670   (interactive "r")
1671   (save-excursion
1672     (goto-char end)
1673     (delete-region (point) (if (not (message-goto-signature))
1674                                (point)
1675                              (forward-line -2)
1676                              (point)))
1677     (insert "\n")
1678     (goto-char beg)
1679     (delete-region beg (progn (message-goto-body)
1680                               (forward-line 2)
1681                               (point))))
1682   (when (message-goto-signature)
1683     (forward-line -2)))
1684
1685 (defun message-kill-to-signature ()
1686   "Deletes all text up to the signature."
1687   (interactive)
1688   (let ((point (point)))
1689     (message-goto-signature)
1690     (unless (eobp)
1691       (forward-line -2))
1692     (kill-region point (point))
1693     (unless (bolp)
1694       (insert "\n"))))
1695
1696 (defun message-newline-and-reformat ()
1697   "Insert four newlines, and then reformat if inside quoted text."
1698   (interactive)
1699   (let ((point (point))
1700         quoted)
1701     (save-excursion
1702       (beginning-of-line)
1703       (setq quoted (looking-at (regexp-quote message-yank-prefix))))
1704     (insert "\n\n\n\n")
1705     (when quoted
1706       (insert message-yank-prefix))
1707     (fill-paragraph nil)
1708     (goto-char point)
1709     (forward-line 2)))
1710
1711 (defun message-insert-signature (&optional force)
1712   "Insert a signature.  See documentation for the `message-signature' variable."
1713   (interactive (list 0))
1714   (let* ((signature
1715           (cond
1716            ((and (null message-signature)
1717                  (eq force 0))
1718             (save-excursion
1719               (goto-char (point-max))
1720               (not (re-search-backward
1721                     message-signature-separator nil t))))
1722            ((and (null message-signature)
1723                  force)
1724             t)
1725            ((message-functionp message-signature)
1726             (funcall message-signature))
1727            ((listp message-signature)
1728             (eval message-signature))
1729            (t message-signature)))
1730          (signature
1731           (cond ((stringp signature)
1732                  signature)
1733                 ((and (eq t signature)
1734                       message-signature-file
1735                       (file-exists-p message-signature-file))
1736                  signature))))
1737     (when signature
1738       (goto-char (point-max))
1739       ;; Insert the signature.
1740       (unless (bolp)
1741         (insert "\n"))
1742       (insert "\n-- \n")
1743       (if (eq signature t)
1744           (insert-file-contents message-signature-file)
1745         (insert signature))
1746       (goto-char (point-max))
1747       (or (bolp) (insert "\n")))))
1748
1749 (defun message-elide-region (b e)
1750   "Elide the text between point and mark.
1751 An ellipsis (from `message-elide-elipsis') will be inserted where the
1752 text was killed."
1753   (interactive "r")
1754   (kill-region b e)
1755   (unless (bolp)
1756     (insert "\n"))
1757   (insert message-elide-elipsis))
1758
1759 (defvar message-caesar-translation-table nil)
1760
1761 (defun message-caesar-region (b e &optional n)
1762   "Caesar rotation of region by N, default 13, for decrypting netnews."
1763   (interactive
1764    (list
1765     (min (point) (or (mark t) (point)))
1766     (max (point) (or (mark t) (point)))
1767     (when current-prefix-arg
1768       (prefix-numeric-value current-prefix-arg))))
1769
1770   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1771   (unless (or (zerop n)                 ; no action needed for a rot of 0
1772               (= b e))                  ; no region to rotate
1773     ;; We build the table, if necessary.
1774     (when (or (not message-caesar-translation-table)
1775               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1776         (setq message-caesar-translation-table
1777               (message-make-caesar-translation-table n)))
1778     ;; Then we translate the region.  Do it this way to retain
1779     ;; text properties.
1780     (while (< b e)
1781       (when (< (char-after b) 255)
1782         (subst-char-in-region
1783          b (1+ b) (char-after b)
1784          (aref message-caesar-translation-table (char-after b))))
1785       (incf b))))
1786
1787 (defun message-make-caesar-translation-table (n)
1788   "Create a rot table with offset N."
1789   (let ((i -1)
1790         (table (make-string 256 0)))
1791     (while (< (incf i) 256)
1792       (aset table i i))
1793     (concat
1794      (substring table 0 ?A)
1795      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1796      (substring table ?A (+ ?A n))
1797      (substring table (+ ?A 26) ?a)
1798      (substring table (+ ?a n) (+ ?a n (- 26 n)))
1799      (substring table ?a (+ ?a n))
1800      (substring table (+ ?a 26) 255))))
1801
1802 (defun message-caesar-buffer-body (&optional rotnum)
1803   "Caesar rotates all letters in the current buffer by 13 places.
1804 Used to encode/decode possiblyun offensive messages (commonly in net.jokes).
1805 With prefix arg, specifies the number of places to rotate each letter forward.
1806 Mail and USENET news headers are not rotated."
1807   (interactive (if current-prefix-arg
1808                    (list (prefix-numeric-value current-prefix-arg))
1809                  (list nil)))
1810   (save-excursion
1811     (save-restriction
1812       (when (message-goto-body)
1813         (narrow-to-region (point) (point-max)))
1814       (message-caesar-region (point-min) (point-max) rotnum))))
1815
1816 (defun message-pipe-buffer-body (program)
1817   "Pipe the message body in the current buffer through PROGRAM."
1818   (save-excursion
1819     (save-restriction
1820       (when (message-goto-body)
1821         (narrow-to-region (point) (point-max)))
1822       (let ((body (buffer-substring (point-min) (point-max))))
1823         (unless (equal 0 (call-process-region
1824                            (point-min) (point-max) program t t))
1825             (insert body)
1826             (message "%s failed." program))))))
1827
1828 (defun message-rename-buffer (&optional enter-string)
1829   "Rename the *message* buffer to \"*message* RECIPIENT\".
1830 If the function is run with a prefix, it will ask for a new buffer
1831 name, rather than giving an automatic name."
1832   (interactive "Pbuffer name: ")
1833   (save-excursion
1834     (save-restriction
1835       (goto-char (point-min))
1836       (narrow-to-region (point)
1837                         (search-forward mail-header-separator nil 'end))
1838       (let* ((mail-to (or
1839                        (if (message-news-p) (message-fetch-field "Newsgroups")
1840                          (message-fetch-field "To"))
1841                        ""))
1842              (mail-trimmed-to
1843               (if (string-match "," mail-to)
1844                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1845                 mail-to))
1846              (name-default (concat "*message* " mail-trimmed-to))
1847              (name (if enter-string
1848                        (read-string "New buffer name: " name-default)
1849                      name-default)))
1850         (rename-buffer name t)))))
1851
1852 (defun message-fill-yanked-message (&optional justifyp)
1853   "Fill the paragraphs of a message yanked into this one.
1854 Numeric argument means justify as well."
1855   (interactive "P")
1856   (save-excursion
1857     (goto-char (point-min))
1858     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1859     (let ((fill-prefix message-yank-prefix))
1860       (fill-individual-paragraphs (point) (point-max) justifyp t))))
1861
1862 (defun message-indent-citation ()
1863   "Modify text just inserted from a message to be cited.
1864 The inserted text should be the region.
1865 When this function returns, the region is again around the modified text.
1866
1867 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1868 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1869   (let ((start (point)))
1870     ;; Remove unwanted headers.
1871     (when message-ignored-cited-headers
1872       (let (all-removed)
1873         (save-restriction
1874           (narrow-to-region
1875            (goto-char start)
1876            (if (search-forward "\n\n" nil t)
1877                (1- (point))
1878              (point)))
1879           (message-remove-header message-ignored-cited-headers t)
1880           (when (= (point-min) (point-max))
1881             (setq all-removed t))
1882           (goto-char (point-max)))
1883         (if all-removed
1884             (goto-char start)
1885           (forward-line 1))))
1886     ;; Delete blank lines at the start of the buffer.
1887     (while (and (point-min)
1888                 (eolp)
1889                 (not (eobp)))
1890       (message-delete-line))
1891     ;; Delete blank lines at the end of the buffer.
1892     (goto-char (point-max))
1893     (unless (eolp)
1894       (insert "\n"))
1895     (while (and (zerop (forward-line -1))
1896                 (looking-at "$"))
1897       (message-delete-line))
1898     ;; Do the indentation.
1899     (if (null message-yank-prefix)
1900         (indent-rigidly start (mark t) message-indentation-spaces)
1901       (save-excursion
1902         (goto-char start)
1903         (while (< (point) (mark t))
1904           (insert message-yank-prefix)
1905           (forward-line 1))))
1906     (goto-char start)))
1907
1908 (defvar gnus-article-copy)
1909 (defun message-yank-original (&optional arg)
1910   "Insert the message being replied to, if any.
1911 Puts point before the text and mark after.
1912 Normally indents each nonblank line ARG spaces (default 3).  However,
1913 if `message-yank-prefix' is non-nil, insert that prefix on each line.
1914
1915 This function uses `message-cite-function' to do the actual citing.
1916
1917 Just \\[universal-argument] as argument means don't indent, insert no
1918 prefix, and don't delete any headers."
1919   (interactive "P")
1920   (let ((modified (buffer-modified-p)))
1921     (when (and message-reply-buffer
1922                message-cite-function)
1923       (gnus-copy-article-buffer)
1924       (setq message-reply-buffer gnus-article-copy)
1925       (delete-windows-on message-reply-buffer t)
1926       (insert-buffer message-reply-buffer)
1927       (funcall message-cite-function)
1928       (message-exchange-point-and-mark)
1929       (unless (bolp)
1930         (insert ?\n))
1931       (unless modified
1932         (setq message-checksum (message-checksum))))))
1933
1934 (defun message-cite-original-without-signature ()
1935   "Cite function in the standard Message manner."
1936   (let ((start (point))
1937         (end (mark t))
1938         (functions
1939          (when message-indent-citation-function
1940            (if (listp message-indent-citation-function)
1941                message-indent-citation-function
1942              (list message-indent-citation-function)))))
1943     (goto-char end)
1944     (when (re-search-backward "^-- $" start t)
1945       ;; Also peel off any blank lines before the signature.
1946       (forward-line -1)
1947       (while (looking-at "^[ \t]*$")
1948         (forward-line -1))
1949       (forward-line 1)
1950       (delete-region (point) end))
1951     (goto-char start)
1952     (while functions
1953       (funcall (pop functions)))
1954     (when message-citation-line-function
1955       (unless (bolp)
1956         (insert "\n"))
1957       (funcall message-citation-line-function))))
1958
1959 (defvar mail-citation-hook) ;Compiler directive
1960 (defun message-cite-original ()
1961   "Cite function in the standard Message manner."
1962   (if (and (boundp 'mail-citation-hook)
1963            mail-citation-hook)
1964       (run-hooks 'mail-citation-hook)
1965     (let ((start (point))
1966           (functions
1967            (when message-indent-citation-function
1968              (if (listp message-indent-citation-function)
1969                  message-indent-citation-function
1970                (list message-indent-citation-function)))))
1971       (goto-char start)
1972       (while functions
1973         (funcall (pop functions)))
1974       (when message-citation-line-function
1975         (unless (bolp)
1976           (insert "\n"))
1977         (funcall message-citation-line-function)))))
1978
1979 (defun message-insert-citation-line ()
1980   "Function that inserts a simple citation line."
1981   (when message-reply-headers
1982     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
1983
1984 (defun message-position-on-field (header &rest afters)
1985   (let ((case-fold-search t))
1986     (save-restriction
1987       (narrow-to-region
1988        (goto-char (point-min))
1989        (progn
1990          (re-search-forward
1991           (concat "^" (regexp-quote mail-header-separator) "$"))
1992          (match-beginning 0)))
1993       (goto-char (point-min))
1994       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
1995           (progn
1996             (re-search-forward "^[^ \t]" nil 'move)
1997             (beginning-of-line)
1998             (skip-chars-backward "\n")
1999             t)
2000         (while (and afters
2001                     (not (re-search-forward
2002                           (concat "^" (regexp-quote (car afters)) ":")
2003                           nil t)))
2004           (pop afters))
2005         (when afters
2006           (re-search-forward "^[^ \t]" nil 'move)
2007           (beginning-of-line))
2008         (insert header ": \n")
2009         (forward-char -1)
2010         nil))))
2011
2012 (defun message-remove-signature ()
2013   "Remove the signature from the text between point and mark.
2014 The text will also be indented the normal way."
2015   (save-excursion
2016     (let ((start (point))
2017           mark)
2018       (if (not (re-search-forward message-signature-separator (mark t) t))
2019           ;; No signature here, so we just indent the cited text.
2020           (message-indent-citation)
2021         ;; Find the last non-empty line.
2022         (forward-line -1)
2023         (while (looking-at "[ \t]*$")
2024           (forward-line -1))
2025         (forward-line 1)
2026         (setq mark (set-marker (make-marker) (point)))
2027         (goto-char start)
2028         (message-indent-citation)
2029         ;; Enable undoing the deletion.
2030         (undo-boundary)
2031         (delete-region mark (mark t))
2032         (set-marker mark nil)))))
2033
2034 \f
2035
2036 ;;;
2037 ;;; Sending messages
2038 ;;;
2039
2040 ;; Avoid byte-compile warning.
2041 (defvar message-encoding-buffer nil)
2042 (defvar message-edit-buffer nil)
2043 (defvar message-mime-mode nil)
2044
2045 (defun message-send-and-exit (&optional arg)
2046   "Send message like `message-send', then, if no errors, exit from mail buffer."
2047   (interactive "P")
2048   (let ((buf (current-buffer))
2049         (actions message-exit-actions)
2050         (frame (selected-frame))
2051         (org-frame message-original-frame))
2052     (when (and (message-send arg)
2053                (buffer-name buf))
2054       (if message-kill-buffer-on-exit
2055           (kill-buffer buf)
2056         (bury-buffer buf)
2057         (when (eq buf (current-buffer))
2058           (message-bury buf)))
2059       (message-do-actions actions)
2060       (message-delete-frame frame org-frame)
2061       t)))
2062
2063 (defun message-dont-send ()
2064   "Don't send the message you have been editing."
2065   (interactive)
2066   (set-buffer-modified-p t)
2067   (save-buffer)
2068   (let ((actions message-postpone-actions))
2069     (message-bury (current-buffer))
2070     (message-do-actions actions)))
2071
2072 (defun message-kill-buffer ()
2073   "Kill the current buffer."
2074   (interactive)
2075   (when (or (not (buffer-modified-p))
2076             (eq t message-kill-buffer-query-function)
2077             (funcall message-kill-buffer-query-function
2078                      "The buffer modified; kill anyway? "))
2079     (let ((actions message-kill-actions)
2080           (frame (selected-frame))
2081           (org-frame message-original-frame))
2082       (setq buffer-file-name nil)
2083       (kill-buffer (current-buffer))
2084       (message-do-actions actions)
2085       (message-delete-frame frame org-frame)))
2086   (message ""))
2087
2088 (defun message-delete-frame (frame org-frame)
2089   "Delete frame for editing message."
2090   (when (and (or (and (featurep 'xemacs)
2091                       (not (eq 'tty (device-type))))
2092                  window-system
2093                  (>= emacs-major-version 20))
2094              (or (and (eq message-delete-frame-on-exit t)
2095                       (select-frame frame)
2096                       (or (eq frame org-frame)
2097                           (prog1
2098                               (y-or-n-p "Delete this frame?")
2099                             (message ""))))
2100                  (and (eq message-delete-frame-on-exit 'ask)
2101                       (select-frame frame)
2102                       (prog1
2103                           (y-or-n-p "Delete this frame?")
2104                         (message "")))))
2105     (delete-frame frame)))
2106
2107 (defun message-bury (buffer)
2108   "Bury this mail buffer."
2109   (let ((newbuf (other-buffer buffer)))
2110     (bury-buffer buffer)
2111     (if (and (fboundp 'frame-parameters)
2112              (cdr (assq 'dedicated (frame-parameters)))
2113              (not (null (delq (selected-frame) (visible-frame-list)))))
2114         (delete-frame (selected-frame))
2115       (switch-to-buffer newbuf))))
2116
2117 (defun message-send (&optional arg)
2118   "Send the message in the current buffer.
2119 If `message-interactive' is non-nil, wait for success indication
2120 or error messages, and inform user.
2121 Otherwise any failure is reported in a message back to
2122 the user from the mailer."
2123   (interactive "P")
2124   ;; Disabled test.
2125   (when (or (buffer-modified-p)
2126             (message-check-element 'unchanged)
2127             (y-or-n-p "No changes in the buffer; really send? "))
2128     ;; Make it possible to undo the coming changes.
2129     (undo-boundary)
2130     (let ((inhibit-read-only t))
2131       (put-text-property (point-min) (point-max) 'read-only nil))
2132     (run-hooks 'message-send-hook)
2133     (message "Sending...")
2134     (let ((message-encoding-buffer
2135            (message-generate-new-buffer-clone-locals " message encoding"))
2136           (message-edit-buffer (current-buffer))
2137           (message-mime-mode mime-edit-mode-flag)
2138           (alist message-send-method-alist)
2139           (success t)
2140           elem sent)
2141       (save-excursion
2142         (set-buffer message-encoding-buffer)
2143         (erase-buffer)
2144         (insert-buffer message-edit-buffer)
2145         (funcall message-encode-function)
2146         (message-fix-before-sending)
2147         (while (and success
2148                     (setq elem (pop alist)))
2149           (when (and (or (not (funcall (cadr elem)))
2150                          (and (or (not (memq (car elem)
2151                                              message-sent-message-via))
2152                                   (y-or-n-p
2153                                    (format
2154                                     "Already sent message via %s; resend? "
2155                                     (car elem))))
2156                               (setq success (funcall (caddr elem) arg)))))
2157             (setq sent t))))
2158       (when (and success sent)
2159         (message-do-fcc)
2160         ;;(when (fboundp 'mail-hist-put-headers-into-history)
2161         ;; (mail-hist-put-headers-into-history))
2162         (run-hooks 'message-sent-hook)
2163         (message "Sending...done")
2164         ;; Mark the buffer as unmodified and delete autosave.
2165         (set-buffer-modified-p nil)
2166         (delete-auto-save-file-if-necessary t)
2167         (message-disassociate-draft)
2168         ;; Delete other mail buffers and stuff.
2169         (message-do-send-housekeeping)
2170         (message-do-actions message-send-actions)
2171         ;; Return success.
2172         t))))
2173
2174 (defun message-send-via-mail (arg)
2175   "Send the current message via mail."
2176   (message-send-mail arg))
2177
2178 (defun message-send-via-news (arg)
2179   "Send the current message via news."
2180   (message-send-news arg))
2181
2182 (defun message-fix-before-sending ()
2183   "Do various things to make the message nice before sending it."
2184   ;; Make sure there's a newline at the end of the message.
2185   (goto-char (point-max))
2186   (unless (bolp)
2187     (insert "\n"))
2188   ;; Delete all invisible text.
2189   (message-check 'invisible-text
2190     (when (text-property-any (point-min) (point-max) 'invisible t)
2191       (put-text-property (point-min) (point-max) 'invisible nil)
2192       (unless (yes-or-no-p "Invisible text found and made visible; continue posting?")
2193         (error "Invisible text found and made visible")))))
2194
2195 (defun message-add-action (action &rest types)
2196   "Add ACTION to be performed when doing an exit of type TYPES."
2197   (let (var)
2198     (while types
2199       (set (setq var (intern (format "message-%s-actions" (pop types))))
2200            (nconc (symbol-value var) (list action))))))
2201
2202 (defun message-do-actions (actions)
2203   "Perform all actions in ACTIONS."
2204   ;; Now perform actions on successful sending.
2205   (while actions
2206     (ignore-errors
2207       (cond
2208        ;; A simple function.
2209        ((message-functionp (car actions))
2210         (funcall (car actions)))
2211        ;; Something to be evaled.
2212        (t
2213         (eval (car actions)))))
2214     (pop actions)))
2215
2216 (defun message-send-mail (&optional arg)
2217   (require 'mail-utils)
2218   (let ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2219         (case-fold-search nil)
2220         (news (message-news-p)))
2221     (save-restriction
2222       (message-narrow-to-headers)
2223       ;; Insert some headers.
2224       (let ((message-deletable-headers
2225              (if news nil message-deletable-headers)))
2226         (message-generate-headers message-required-mail-headers))
2227       ;; Let the user do all of the above.
2228       (run-hooks 'message-header-hook))
2229     (unwind-protect
2230         (save-excursion
2231           (set-buffer tembuf)
2232           (erase-buffer)
2233           (insert-buffer message-encoding-buffer)
2234           ;; Remove some headers.
2235           (save-restriction
2236             (message-narrow-to-headers)
2237             ;; Remove some headers.
2238             (message-remove-header message-ignored-mail-headers t))
2239           (goto-char (point-max))
2240           ;; require one newline at the end.
2241           (or (= (preceding-char) ?\n)
2242               (insert ?\n))
2243           (when (and news
2244                      (or (message-fetch-field "cc")
2245                          (message-fetch-field "to")))
2246             (message-insert-courtesy-copy))
2247 ;;        (mime-edit-maybe-split-and-send
2248 ;;         (function
2249 ;;          (lambda ()
2250 ;;            (interactive)
2251 ;;            (funcall message-send-mail-function)
2252 ;;            )))
2253           (mime-edit-maybe-split-and-send
2254            (function
2255             (lambda ()
2256               (interactive)
2257               (save-restriction
2258                 (std11-narrow-to-header mail-header-separator)
2259                 (goto-char (point-min))
2260                 (when (re-search-forward "^Message-Id:" nil t)
2261                   (delete-region (match-end 0)(std11-field-end))
2262                   (insert (concat " " (message-make-message-id)))
2263                   ))
2264               (interactive)
2265               (funcall message-send-mail-function))))
2266           (funcall message-send-mail-function))
2267       (kill-buffer tembuf))
2268     (set-buffer message-edit-buffer)
2269     (push 'mail message-sent-message-via)))
2270
2271 (defun message-send-mail-with-sendmail ()
2272   "Send off the prepared buffer with sendmail."
2273   (let ((errbuf (if message-interactive
2274                     (generate-new-buffer " sendmail errors")
2275                   0))
2276         resend-addresses delimline)
2277     (let ((case-fold-search t))
2278       (save-restriction
2279         (message-narrow-to-headers)
2280         ;; XXX: We need to handle Resent-CC/Resent-BCC, too.
2281         (setq resend-addresses (message-fetch-field "resent-to")))
2282       ;; Change header-delimiter to be what sendmail expects.
2283       (goto-char (point-min))
2284       (re-search-forward
2285        (concat "^" (regexp-quote mail-header-separator) "\n"))
2286       (replace-match "\n")
2287       (backward-char 1)
2288       (setq delimline (point-marker))
2289       (run-hooks 'message-send-mail-hook)
2290       ;; Insert an extra newline if we need it to work around
2291       ;; Sun's bug that swallows newlines.
2292       (goto-char (1+ delimline))
2293       (when (eval message-mailer-swallows-blank-line)
2294         (newline))
2295       (when message-interactive
2296         (save-excursion
2297           (set-buffer errbuf)
2298           (erase-buffer))))
2299     (let ((default-directory "/")
2300           (coding-system-for-write message-send-coding-system))
2301       (apply 'call-process-region
2302              (append (list (point-min) (point-max)
2303                            (if (boundp 'sendmail-program)
2304                                sendmail-program
2305                              "/usr/lib/sendmail")
2306                            nil errbuf nil "-oi")
2307                      ;; Always specify who from,
2308                      ;; since some systems have broken sendmails.
2309                      ;; But some systems are more broken with -f, so
2310                      ;; we'll let users override this.
2311                      (if (null message-sendmail-f-is-evil)
2312                          (list "-f" (user-login-name)))
2313                      ;; These mean "report errors by mail"
2314                      ;; and "deliver in background".
2315                      (if (null message-interactive) '("-oem" "-odb"))
2316                      ;; Get the addresses from the message
2317                      ;; unless this is a resend.
2318                      ;; We must not do that for a resend
2319                      ;; because we would find the original addresses.
2320                      ;; For a resend, include the specific addresses.
2321                      (if resend-addresses
2322                          (list resend-addresses)
2323                        '("-t")))))
2324     (when message-interactive
2325       (save-excursion
2326         (set-buffer errbuf)
2327         (goto-char (point-min))
2328         (while (re-search-forward "\n\n* *" nil t)
2329           (replace-match "; "))
2330         (if (not (zerop (buffer-size)))
2331             (error "Sending...failed to %s"
2332                    (buffer-substring (point-min) (point-max)))))
2333       (when (bufferp errbuf)
2334         (kill-buffer errbuf)))))
2335
2336 (defun message-send-mail-with-qmail ()
2337   "Pass the prepared message buffer to qmail-inject.
2338 Refer to the documentation for the variable `message-send-mail-function'
2339 to find out how to use this."
2340   ;; replace the header delimiter with a blank line.
2341   (goto-char (point-min))
2342   (re-search-forward
2343    (concat "^" (regexp-quote mail-header-separator) "\n"))
2344   (replace-match "\n")
2345   (backward-char 1)
2346   (run-hooks 'message-send-mail-hook)
2347   ;; send the message
2348   (case
2349       (let ((coding-system-for-write message-send-coding-system))
2350         (apply
2351          'call-process-region 1 (point-max) message-qmail-inject-program
2352          nil nil nil
2353          ;; qmail-inject's default behaviour is to look for addresses on the
2354          ;; command line; if there're none, it scans the headers.
2355          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2356          ;;
2357          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2358          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2359          ;; message from stdin.
2360          ;;
2361          ;; qmail also has the advantage of not having been raped by
2362          ;; various vendors, so we don't have to allow for that, either --
2363          ;; compare this with message-send-mail-with-sendmail and weep
2364          ;; for sendmail's lost innocence.
2365          ;;
2366          ;; all this is way cool coz it lets us keep the arguments entirely
2367          ;; free for -inject-arguments -- a big win for the user and for us
2368          ;; since we don't have to play that double-guessing game and the user
2369          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2370          message-qmail-inject-args))
2371     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2372     ;; we have to look at the retval instead
2373     (0 nil)
2374     (1   (error "qmail-inject reported permanent failure"))
2375     (111 (error "qmail-inject reported transient failure"))
2376     ;; should never happen
2377     (t   (error "qmail-inject reported unknown failure"))))
2378
2379 (defun message-send-mail-with-mh ()
2380   "Send the prepared message buffer with mh."
2381   (let ((mh-previous-window-config nil)
2382         (name (mh-new-draft-name)))
2383     (setq buffer-file-name name)
2384     ;; MH wants to generate these headers itself.
2385     (when message-mh-deletable-headers
2386       (let ((headers message-mh-deletable-headers))
2387         (while headers
2388           (goto-char (point-min))
2389           (and (re-search-forward
2390                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2391                (message-delete-line))
2392           (pop headers))))
2393     (run-hooks 'message-send-mail-hook)
2394     ;; Pass it on to mh.
2395     (mh-send-letter)))
2396
2397 (defun message-send-mail-with-smtp ()
2398   "Send off the prepared buffer with SMTP."
2399   (require 'smtp) ; XXX
2400   (let ((case-fold-search t)
2401         recipients)
2402     (save-restriction
2403       (message-narrow-to-headers)
2404       (setq recipients
2405             ;; XXX: Should be replaced by better one.
2406             (smtp-deduce-address-list (current-buffer)
2407                                       (point-min) (point-max)))
2408       ;; Remove BCC lines.
2409       (message-remove-header "bcc"))
2410     ;; replace the header delimiter with a blank line.
2411     (goto-char (point-min))
2412     (re-search-forward
2413      (concat "^" (regexp-quote mail-header-separator) "\n"))
2414     (replace-match "\n")
2415     (backward-char 1)
2416     (run-hooks 'message-send-mail-hook)
2417     (if recipients
2418         (let ((result (smtp-via-smtp user-mail-address
2419                                      recipients
2420                                      (current-buffer))))
2421           (unless (eq result t)
2422             (error "Sending failed; " result)))
2423       (error "Sending failed; no recipients"))))
2424
2425 (defun message-send-news (&optional arg)
2426   (let ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2427         (case-fold-search nil)
2428         (method (if (message-functionp message-post-method)
2429                     (funcall message-post-method arg)
2430                   message-post-method))
2431         (message-syntax-checks
2432          (if arg
2433              (cons '(existing-newsgroups . disabled)
2434                    message-syntax-checks)
2435            message-syntax-checks))
2436         result)
2437     (save-restriction
2438       (message-narrow-to-headers)
2439       ;; Insert some headers.
2440       (message-generate-headers message-required-news-headers)
2441       ;; Let the user do all of the above.
2442       (run-hooks 'message-header-hook))
2443     (message-cleanup-headers)
2444     (if (not (message-check-news-syntax))
2445         nil
2446       (unwind-protect
2447           (save-excursion
2448             (set-buffer tembuf)
2449             (buffer-disable-undo)
2450             (erase-buffer)
2451             (insert-buffer message-encoding-buffer)
2452             ;; Remove some headers.
2453             (save-restriction
2454               (message-narrow-to-headers)
2455               ;; Remove some headers.
2456               (message-remove-header message-ignored-news-headers t))
2457             (goto-char (point-max))
2458             ;; require one newline at the end.
2459             (or (= (preceding-char) ?\n)
2460                 (insert ?\n))
2461             (mime-edit-maybe-split-and-send
2462              (function
2463               (lambda ()
2464                 (interactive)
2465                 (save-restriction
2466                   (std11-narrow-to-header mail-header-separator)
2467                   (goto-char (point-min))
2468                   (when (re-search-forward "^Message-Id:" nil t)
2469                     (delete-region (match-end 0)(std11-field-end))
2470                     (insert (concat " " (message-make-message-id)))
2471                     ))
2472                 (funcall message-send-news-function method)
2473                 )))
2474             (setq result (funcall message-send-news-function method)))
2475         (kill-buffer tembuf))
2476       (set-buffer message-edit-buffer)
2477       (if result
2478           (push 'news message-sent-message-via)
2479         (message "Couldn't send message via news: %s"
2480                  (nnheader-get-report (car method)))
2481         nil))))
2482
2483 ;; 1997-09-29 by MORIOKA Tomohiko
2484 (defun message-send-news-with-gnus (method)
2485   (let ((case-fold-search t))
2486     ;; Remove the delimiter.
2487     (goto-char (point-min))
2488     (re-search-forward
2489      (concat "^" (regexp-quote mail-header-separator) "\n"))
2490     (replace-match "\n")
2491     (backward-char 1)
2492     (run-hooks 'message-send-news-hook)
2493     ;;(require (car method))
2494     ;;(funcall (intern (format "%s-open-server" (car method)))
2495     ;;(cadr method) (cddr method))
2496     ;;(setq result
2497     ;;    (funcall (intern (format "%s-request-post" (car method)))
2498     ;;             (cadr method)))
2499     (gnus-open-server method)
2500     (gnus-request-post method)
2501     ))
2502
2503 ;;;
2504 ;;; Header generation & syntax checking.
2505 ;;;
2506
2507 (defmacro message-check (type &rest forms)
2508   "Eval FORMS if TYPE is to be checked."
2509   `(or (message-check-element ,type)
2510        (save-excursion
2511          ,@forms)))
2512
2513 (put 'message-check 'lisp-indent-function 1)
2514 (put 'message-check 'edebug-form-spec '(form body))
2515
2516 (defun message-check-element (type)
2517   "Returns non-nil if this type is not to be checked."
2518   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2519       t
2520     (let ((able (assq type message-syntax-checks)))
2521       (and (consp able)
2522            (eq (cdr able) 'disabled)))))
2523
2524 (defun message-check-news-syntax ()
2525   "Check the syntax of the message."
2526   (save-excursion
2527     (save-restriction
2528       (widen)
2529       (and
2530        ;; We narrow to the headers and check them first.
2531        (save-excursion
2532          (save-restriction
2533            (message-narrow-to-headers)
2534            (message-check-news-header-syntax)))
2535        ;; Check the body.
2536        (save-excursion
2537          (set-buffer message-edit-buffer)
2538          (message-check-news-body-syntax))))))
2539
2540 (defun message-check-news-header-syntax ()
2541   (and
2542    ;; Check the Subject header.
2543    (message-check 'subject
2544      (let* ((case-fold-search t)
2545             (subject (message-fetch-field "subject")))
2546        (or
2547         (and subject
2548              (not (string-match "\\`[ \t]*\\'" subject)))
2549         (ignore
2550          (message
2551           "The subject field is empty or missing.  Posting is denied.")))))
2552    ;; Check for commands in Subject.
2553    (message-check 'subject-cmsg
2554      (if (string-match "^cmsg " (message-fetch-field "subject"))
2555          (y-or-n-p
2556           "The control code \"cmsg\" is in the subject.  Really post? ")
2557        t))
2558    ;; Check for multiple identical headers.
2559    (message-check 'multiple-headers
2560      (let (found)
2561        (while (and (not found)
2562                    (re-search-forward "^[^ \t:]+: " nil t))
2563          (save-excursion
2564            (or (re-search-forward
2565                 (concat "^"
2566                         (regexp-quote
2567                          (setq found
2568                                (buffer-substring
2569                                 (match-beginning 0) (- (match-end 0) 2))))
2570                         ":")
2571                 nil t)
2572                (setq found nil))))
2573        (if found
2574            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2575          t)))
2576    ;; Check for Version and Sendsys.
2577    (message-check 'sendsys
2578      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2579          (y-or-n-p
2580           (format "The article contains a %s command.  Really post? "
2581                   (buffer-substring (match-beginning 0)
2582                                     (1- (match-end 0)))))
2583        t))
2584    ;; See whether we can shorten Followup-To.
2585    (message-check 'shorten-followup-to
2586      (let ((newsgroups (message-fetch-field "newsgroups"))
2587            (followup-to (message-fetch-field "followup-to"))
2588            to)
2589        (when (and newsgroups
2590                   (string-match "," newsgroups)
2591                   (not followup-to)
2592                   (not
2593                    (zerop
2594                     (length
2595                      (setq to (completing-read
2596                                "Followups to: (default all groups) "
2597                                (mapcar (lambda (g) (list g))
2598                                        (cons "poster"
2599                                              (message-tokenize-header
2600                                               newsgroups)))))))))
2601          (goto-char (point-min))
2602          (insert "Followup-To: " to "\n"))
2603        t))
2604    ;; Check "Shoot me".
2605    (message-check 'shoot
2606      (if (re-search-forward
2607           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2608          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2609        t))
2610    ;; Check for Approved.
2611    (message-check 'approved
2612      (if (re-search-forward "^Approved:" nil t)
2613          (y-or-n-p "The article contains an Approved header.  Really post? ")
2614        t))
2615    ;; Check the Message-ID header.
2616    (message-check 'message-id
2617      (let* ((case-fold-search t)
2618             (message-id (message-fetch-field "message-id" t)))
2619        (or (not message-id)
2620            ;; Is there an @ in the ID?
2621            (and (string-match "@" message-id)
2622                 ;; Is there a dot in the ID?
2623                 (string-match "@[^.]*\\." message-id)
2624                 ;; Does the ID end with a dot?
2625                 (not (string-match "\\.>" message-id)))
2626            (y-or-n-p
2627             (format "The Message-ID looks strange: \"%s\".  Really post? "
2628                     message-id)))))
2629    ;; Check the Newsgroups & Followup-To headers.
2630    (message-check 'existing-newsgroups
2631      (let* ((case-fold-search t)
2632             (newsgroups (message-fetch-field "newsgroups"))
2633             (followup-to (message-fetch-field "followup-to"))
2634             (groups (message-tokenize-header
2635                      (if followup-to
2636                          (concat newsgroups "," followup-to)
2637                        newsgroups)))
2638             (hashtb (and (boundp 'gnus-active-hashtb)
2639                          gnus-active-hashtb))
2640             errors)
2641        (if (or (not hashtb)
2642                (not (boundp 'gnus-read-active-file))
2643                (not gnus-read-active-file)
2644                (eq gnus-read-active-file 'some))
2645            t
2646          (while groups
2647            (when (and (not (boundp (intern (car groups) hashtb)))
2648                       (not (equal (car groups) "poster")))
2649              (push (car groups) errors))
2650            (pop groups))
2651          (if (not errors)
2652              t
2653            (y-or-n-p
2654             (format
2655              "Really post to %s unknown group%s: %s "
2656              (if (= (length errors) 1) "this" "these")
2657              (if (= (length errors) 1) "" "s")
2658              (mapconcat 'identity errors ", ")))))))
2659    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2660    (message-check 'valid-newsgroups
2661      (let ((case-fold-search t)
2662            (headers '("Newsgroups" "Followup-To"))
2663            header error)
2664        (while (and headers (not error))
2665          (when (setq header (mail-fetch-field (car headers)))
2666            (if (or
2667                 (not
2668                  (string-match
2669                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2670                   header))
2671                 (memq
2672                  nil (mapcar
2673                       (lambda (g)
2674                         (not (string-match "\\.\\'\\|\\.\\." g)))
2675                       (message-tokenize-header header ","))))
2676                (setq error t)))
2677          (unless error
2678            (pop headers)))
2679        (if (not error)
2680            t
2681          (y-or-n-p
2682           (format "The %s header looks odd: \"%s\".  Really post? "
2683                   (car headers) header)))))
2684    (message-check 'repeated-newsgroups
2685      (let ((case-fold-search t)
2686            (headers '("Newsgroups" "Followup-To"))
2687            header error groups group)
2688        (while (and headers
2689                    (not error))
2690          (when (setq header (mail-fetch-field (pop headers)))
2691            (setq groups (message-tokenize-header header ","))
2692            (while (setq group (pop groups))
2693              (when (member group groups)
2694                (setq error group
2695                      groups nil)))))
2696        (if (not error)
2697            t
2698          (y-or-n-p
2699           (format "Group %s is repeated in headers.  Really post? " error)))))
2700    ;; Check the From header.
2701    (message-check 'from
2702      (let* ((case-fold-search t)
2703             (from (message-fetch-field "from"))
2704             (ad (nth 1 (std11-extract-address-components from))))
2705        (cond
2706         ((not from)
2707          (message "There is no From line.  Posting is denied.")
2708          nil)
2709         ((or (not (string-match "@[^\\.]*\\." ad)) ;larsi@ifi
2710              (string-match "\\.\\." ad) ;larsi@ifi..uio
2711              (string-match "@\\." ad)   ;larsi@.ifi.uio
2712              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2713              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2714              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2715          (message
2716           "Denied posting -- the From looks strange: \"%s\"." from)
2717          nil)
2718         (t t))))))
2719
2720 (defun message-check-news-body-syntax ()
2721   (and
2722    ;; Check for long lines.
2723    (message-check 'long-lines
2724      (goto-char (point-min))
2725      (re-search-forward
2726       (concat "^" (regexp-quote mail-header-separator) "$"))
2727      (while (and
2728              (progn
2729                (end-of-line)
2730                (< (current-column) 80))
2731              (zerop (forward-line 1))))
2732      (or (bolp)
2733          (eobp)
2734          (y-or-n-p
2735           "You have lines longer than 79 characters.  Really post? ")))
2736    ;; Check whether the article is empty.
2737    (message-check 'empty
2738      (goto-char (point-min))
2739      (re-search-forward
2740       (concat "^" (regexp-quote mail-header-separator) "$"))
2741      (forward-line 1)
2742      (let ((b (point)))
2743        (goto-char (point-max))
2744        (re-search-backward message-signature-separator nil t)
2745        (beginning-of-line)
2746        (or (re-search-backward "[^ \n\t]" b t)
2747            (y-or-n-p "Empty article.  Really post? "))))
2748    ;; Check for control characters.
2749    (message-check 'control-chars
2750      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
2751          (y-or-n-p
2752           "The article contains control characters.  Really post? ")
2753        t))
2754    ;; Check excessive size.
2755    (message-check 'size
2756      (if (> (buffer-size) 60000)
2757          (y-or-n-p
2758           (format "The article is %d octets long.  Really post? "
2759                   (buffer-size)))
2760        t))
2761    ;; Check whether any new text has been added.
2762    (message-check 'new-text
2763      (or
2764       (not message-checksum)
2765       (not (eq (message-checksum) message-checksum))
2766       (y-or-n-p
2767        "It looks like no new text has been added.  Really post? ")))
2768    ;; Check the length of the signature.
2769    (message-check 'signature
2770      (goto-char (point-max))
2771      (if (or (not (re-search-backward message-signature-separator nil t))
2772              (search-forward message-forward-end-separator nil t))
2773          t
2774        (if (> (count-lines (point) (point-max)) 5)
2775            (y-or-n-p
2776             (format
2777              "Your .sig is %d lines; it should be max 4.  Really post? "
2778              (1- (count-lines (point) (point-max)))))
2779          t)))))
2780
2781 (defun message-checksum ()
2782   "Return a \"checksum\" for the current buffer."
2783   (let ((sum 0))
2784     (save-excursion
2785       (goto-char (point-min))
2786       (re-search-forward
2787        (concat "^" (regexp-quote mail-header-separator) "$"))
2788       (while (not (eobp))
2789         (when (not (looking-at "[ \t\n]"))
2790           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
2791                             (following-char))))
2792         (forward-char 1)))
2793     sum))
2794
2795 (defun message-do-fcc ()
2796   "Process Fcc headers in the current buffer."
2797   (let ((case-fold-search t)
2798         (coding-system-for-write 'raw-text)
2799         list file)
2800     (save-excursion
2801       (set-buffer (get-buffer-create " *message temp*"))
2802       (erase-buffer)
2803       (insert-buffer-substring message-encoding-buffer)
2804       (save-restriction
2805         (message-narrow-to-headers)
2806         (while (setq file (message-fetch-field "fcc"))
2807           (push file list)
2808           (message-remove-header "fcc" nil t)))
2809       (run-hooks 'message-header-hook 'message-before-do-fcc-hook)
2810       (goto-char (point-min))
2811       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
2812       (replace-match "" t t)
2813       ;; Process FCC operations.
2814       (while list
2815         (setq file (pop list))
2816         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
2817             ;; Pipe the article to the program in question.
2818             (call-process-region (point-min) (point-max) shell-file-name
2819                                  nil nil nil shell-command-switch
2820                                  (match-string 1 file))
2821           ;; Save the article.
2822           (setq file (expand-file-name file))
2823           (unless (file-exists-p (file-name-directory file))
2824             (make-directory (file-name-directory file) t))
2825           (if (and message-fcc-handler-function
2826                    (not (eq message-fcc-handler-function 'rmail-output)))
2827               (funcall message-fcc-handler-function file)
2828             (if (and (file-readable-p file) (mail-file-babyl-p file))
2829                 (rmail-output file 1 nil t)
2830               (let ((mail-use-rfc822 t))
2831                 (rmail-output file 1 t t))))))
2832
2833       (kill-buffer (current-buffer)))))
2834
2835 (defun message-output (filename)
2836   "Append this article to Unix/babyl mail file.."
2837   (if (and (file-readable-p filename)
2838            (mail-file-babyl-p filename))
2839       (rmail-output-to-rmail-file filename t)
2840     (gnus-output-to-mail filename t)))
2841
2842 (defun message-cleanup-headers ()
2843   "Do various automatic cleanups of the headers."
2844   ;; Remove empty lines in the header.
2845   (save-restriction
2846     (message-narrow-to-headers)
2847     ;; Remove blank lines.
2848     (while (re-search-forward "^[ \t]*\n" nil t)
2849       (replace-match "" t t))
2850
2851     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
2852     ;; spaces to comma and eliminate spaces around commas.  Eliminate
2853     ;; embedded line breaks.
2854     (goto-char (point-min))
2855     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2856       (save-restriction
2857         (narrow-to-region
2858          (point)
2859          (if (re-search-forward "^[^ \t]" nil t)
2860              (match-beginning 0)
2861            (forward-line 1)
2862            (point)))
2863         (goto-char (point-min))
2864         (while (re-search-forward "\n[ \t]+" nil t)
2865           (replace-match " " t t))      ;No line breaks (too confusing)
2866         (goto-char (point-min))
2867         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
2868           (replace-match "," t t))
2869         (goto-char (point-min))
2870         ;; Remove trailing commas.
2871         (when (re-search-forward ",+$" nil t)
2872           (replace-match "" t t))))))
2873
2874 (defun message-make-date (&optional now)
2875   "Make a valid data header.
2876 If NOW, use that time instead."
2877   (let* ((now (or now (current-time)))
2878          (zone (nth 8 (decode-time now)))
2879          (sign "+"))
2880     (when (< zone 0)
2881       (setq sign ""))
2882     ;; We do all of this because XEmacs doesn't have the %z spec.
2883     (concat (format-time-string
2884              "%d %b %Y %H:%M:%S " (or now (current-time)))
2885             (format "%s%02d%02d"
2886                     sign (/ zone 3600)
2887                     (% zone 3600)))))
2888
2889 (defun message-make-followup-subject (subject)
2890   "Make a followup Subject."
2891   (cond
2892    ((and (eq message-use-subject-re 'guess)
2893          (string-match message-subject-encoded-re-regexp subject))
2894     subject)
2895    (message-use-subject-re
2896     (concat "Re: " (message-strip-subject-re subject)))
2897    (t subject)))
2898
2899 (defun message-make-message-id ()
2900   "Make a unique Message-ID."
2901   (concat "<" (message-unique-id)
2902           (let ((psubject (save-excursion (message-fetch-field "subject")))
2903                 (psupersedes
2904                  (save-excursion (message-fetch-field "supersedes"))))
2905             (if (or
2906                  (and message-reply-headers
2907                       (mail-header-references message-reply-headers)
2908                       (mail-header-subject message-reply-headers)
2909                       psubject
2910                       (mail-header-subject message-reply-headers)
2911                       (not (string=
2912                             (message-strip-subject-re
2913                              (mail-header-subject message-reply-headers))
2914                             (message-strip-subject-re psubject))))
2915                  (and psupersedes
2916                       (string-match "_-_@" psupersedes)))
2917                 "_-_" ""))
2918           "@" (message-make-fqdn) ">"))
2919
2920 (defvar message-unique-id-char nil)
2921
2922 ;; If you ever change this function, make sure the new version
2923 ;; cannot generate IDs that the old version could.
2924 ;; You might for example insert a "." somewhere (not next to another dot
2925 ;; or string boundary), or modify the "fsf" string.
2926 (defun message-unique-id ()
2927   ;; Don't use microseconds from (current-time), they may be unsupported.
2928   ;; Instead we use this randomly inited counter.
2929   (setq message-unique-id-char
2930         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2931            ;; (current-time) returns 16-bit ints,
2932            ;; and 2^16*25 just fits into 4 digits i base 36.
2933            (* 25 25)))
2934   (let ((tm (current-time)))
2935     (concat
2936      (if (memq system-type '(ms-dos emx vax-vms))
2937          (let ((user (downcase (user-login-name))))
2938            (while (string-match "[^a-z0-9_]" user)
2939              (aset user (match-beginning 0) ?_))
2940            user)
2941        (message-number-base36 (user-uid) -1))
2942      (message-number-base36 (+ (car   tm)
2943                                (lsh (% message-unique-id-char 25) 16)) 4)
2944      (message-number-base36 (+ (nth 1 tm)
2945                                (lsh (/ message-unique-id-char 25) 16)) 4)
2946      ;; Append the newsreader name, because while the generated
2947      ;; ID is unique to this newsreader, other newsreaders might
2948      ;; otherwise generate the same ID via another algorithm.
2949      ".fsf")))
2950
2951 (defun message-number-base36 (num len)
2952   (if (if (< len 0)
2953           (<= num 0)
2954         (= len 0))
2955       ""
2956     (concat (message-number-base36 (/ num 36) (1- len))
2957             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
2958                                   (% num 36))))))
2959
2960 (defun message-make-organization ()
2961   "Make an Organization header."
2962   (let* ((organization
2963           (when message-user-organization
2964                 (if (message-functionp message-user-organization)
2965                     (funcall message-user-organization)
2966                   message-user-organization))))
2967     (save-excursion
2968       (message-set-work-buffer)
2969       (cond ((stringp organization)
2970              (insert organization))
2971             ((and (eq t organization)
2972                   message-user-organization-file
2973                   (file-exists-p message-user-organization-file))
2974              (insert-file-contents message-user-organization-file)))
2975       (goto-char (point-min))
2976       (while (re-search-forward "[\t\n]+" nil t)
2977         (replace-match "" t t))
2978       (unless (zerop (buffer-size))
2979         (buffer-string)))))
2980
2981 (defun message-make-lines ()
2982   "Count the number of lines and return numeric string."
2983   (save-excursion
2984     (save-restriction
2985       (widen)
2986       (goto-char (point-min))
2987       (re-search-forward
2988        (concat "^" (regexp-quote mail-header-separator) "$"))
2989       (forward-line 1)
2990       (int-to-string (count-lines (point) (point-max))))))
2991
2992 (defun message-make-in-reply-to ()
2993   "Return the In-Reply-To header for this message."
2994   (when message-reply-headers
2995     (let ((mid (mail-header-message-id message-reply-headers))
2996           (from (mail-header-from message-reply-headers))
2997           (date (mail-header-date message-reply-headers)))
2998       (when mid
2999         (concat mid
3000                 (when from
3001                   (let ((pair (std11-extract-address-components from)))
3002                     (concat "\n ("
3003                             (or (car pair) (cadr pair))
3004                             "'s message of " 
3005                             (if (or (not date) (string= date ""))
3006                                 "(unknown date)" date)
3007                             ")"))))))))
3008
3009 (defun message-make-distribution ()
3010   "Make a Distribution header."
3011   (let ((orig-distribution (message-fetch-reply-field "distribution")))
3012     (cond ((message-functionp message-distribution-function)
3013            (funcall message-distribution-function))
3014           (t orig-distribution))))
3015
3016 (defun message-make-expires ()
3017   "Return an Expires header based on `message-expires'."
3018   (let ((current (current-time))
3019         (future (* 1.0 message-expires 60 60 24)))
3020     ;; Add the future to current.
3021     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
3022     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
3023     (message-make-date current)))
3024
3025 (defun message-make-path ()
3026   "Return uucp path."
3027   (let ((login-name (user-login-name)))
3028     (cond ((null message-user-path)
3029            (concat (system-name) "!" login-name))
3030           ((stringp message-user-path)
3031            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
3032            (concat message-user-path "!" login-name))
3033           (t login-name))))
3034
3035 (defun message-make-from ()
3036   "Make a From header."
3037   (let* ((style message-from-style)
3038          (login (message-make-address))
3039          (fullname
3040           (or (and (boundp 'user-full-name)
3041                    user-full-name)
3042               (user-full-name))))
3043     (when (string= fullname "&")
3044       (setq fullname (user-login-name)))
3045     (save-excursion
3046       (message-set-work-buffer)
3047       (cond
3048        ((or (null style)
3049             (equal fullname ""))
3050         (insert login))
3051        ((or (eq style 'angles)
3052             (and (not (eq style 'parens))
3053                  ;; Use angles if no quoting is needed, or if parens would
3054                  ;; need quoting too.
3055                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
3056                      (let ((tmp (concat fullname nil)))
3057                        (while (string-match "([^()]*)" tmp)
3058                          (aset tmp (match-beginning 0) ?-)
3059                          (aset tmp (1- (match-end 0)) ?-))
3060                        (string-match "[\\()]" tmp)))))
3061         (insert fullname)
3062         (goto-char (point-min))
3063         ;; Look for a character that cannot appear unquoted
3064         ;; according to RFC 822.
3065         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
3066           ;; Quote fullname, escaping specials.
3067           (goto-char (point-min))
3068           (insert "\"")
3069           (while (re-search-forward "[\"\\]" nil 1)
3070             (replace-match "\\\\\\&" t))
3071           (insert "\""))
3072         (insert " <" login ">"))
3073        (t                               ; 'parens or default
3074         (insert login " (")
3075         (let ((fullname-start (point)))
3076           (insert fullname)
3077           (goto-char fullname-start)
3078           ;; RFC 822 says \ and nonmatching parentheses
3079           ;; must be escaped in comments.
3080           ;; Escape every instance of ()\ ...
3081           (while (re-search-forward "[()\\]" nil 1)
3082             (replace-match "\\\\\\&" t))
3083           ;; ... then undo escaping of matching parentheses,
3084           ;; including matching nested parentheses.
3085           (goto-char fullname-start)
3086           (while (re-search-forward
3087                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3088                   nil 1)
3089             (replace-match "\\1(\\3)" t)
3090             (goto-char fullname-start)))
3091         (insert ")")))
3092       (buffer-string))))
3093
3094 (defun message-make-sender ()
3095   "Return the \"real\" user address.
3096 This function tries to ignore all user modifications, and
3097 give as trustworthy answer as possible."
3098   (concat (user-login-name) "@" (system-name)))
3099
3100 (defun message-make-address ()
3101   "Make the address of the user."
3102   (or (message-user-mail-address)
3103       (concat (user-login-name) "@" (message-make-domain))))
3104
3105 (defun message-user-mail-address ()
3106   "Return the pertinent part of `user-mail-address'."
3107   (when user-mail-address
3108     (if (string-match " " user-mail-address)
3109         (nth 1 (std11-extract-address-components user-mail-address))
3110       user-mail-address)))
3111
3112 (defun message-make-fqdn ()
3113   "Return user's fully qualified domain name."
3114   (let ((system-name (system-name))
3115         (user-mail (message-user-mail-address)))
3116     (cond
3117      ((string-match "[^.]\\.[^.]" system-name)
3118       ;; `system-name' returned the right result.
3119       system-name)
3120      ;; Try `mail-host-address'.
3121      ((and (boundp 'mail-host-address)
3122            (stringp mail-host-address)
3123            (string-match "\\." mail-host-address))
3124       mail-host-address)
3125      ;; We try `user-mail-address' as a backup.
3126      ((and user-mail
3127            (string-match "\\." user-mail)
3128            (string-match "@\\(.*\\)\\'" user-mail))
3129       (match-string 1 user-mail))
3130      ;; Default to this bogus thing.
3131      (t
3132       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
3133
3134 (defun message-make-host-name ()
3135   "Return the name of the host."
3136   (let ((fqdn (message-make-fqdn)))
3137     (string-match "^[^.]+\\." fqdn)
3138     (substring fqdn 0 (1- (match-end 0)))))
3139
3140 (defun message-make-domain ()
3141   "Return the domain name."
3142   (or mail-host-address
3143       (message-make-fqdn)))
3144
3145 ;; Dummy to avoid byte-compile warning.
3146 (defvar mule-version)
3147 (defvar emacs-beta-version)
3148 (defvar xemacs-codename)
3149 (defvar gnus-inviolable-extended-version)
3150
3151 (defun message-make-user-agent ()
3152   "Return user-agent info if the value `message-user-agent' is non-nil and the
3153 \"User-Agent\" field which includes the same value of `message-user-agent' does
3154 not exist in the narrowed header."
3155   (when message-user-agent
3156     (save-excursion
3157       (goto-char (point-min))
3158       (let ((case-fold-search t)
3159             user-agent start p end)
3160         (if (re-search-forward "^User-Agent:[\t ]*" nil t)
3161             (progn
3162               (setq start (match-beginning 0)
3163                     p (match-end 0)
3164                     end (std11-field-end)
3165                     user-agent (buffer-substring-no-properties p end))
3166               (unless (string-match (regexp-quote message-user-agent)
3167                                     user-agent)
3168                 (delete-region start (1+ end))
3169                 (concat message-user-agent " " user-agent)))
3170           message-user-agent)))))
3171
3172 (defun message-generate-headers (headers)
3173   "Prepare article HEADERS.
3174 Headers already prepared in the buffer are not modified."
3175   (save-restriction
3176     (message-narrow-to-headers)
3177     (let* ((Date (message-make-date))
3178            (Message-ID (message-make-message-id))
3179            (Organization (message-make-organization))
3180            (From (message-make-from))
3181            (Path (message-make-path))
3182            (Subject nil)
3183            (Newsgroups nil)
3184            (In-Reply-To (message-make-in-reply-to))
3185            (To nil)
3186            (Distribution (message-make-distribution))
3187            (Lines (message-make-lines))
3188            (User-Agent (message-make-user-agent))
3189            (Expires (message-make-expires))
3190            (case-fold-search t)
3191            header value elem)
3192       ;; First we remove any old generated headers.
3193       (let ((headers message-deletable-headers))
3194         (unless (buffer-modified-p)
3195           (setq headers (delq 'Message-ID (copy-sequence headers))))
3196         (while headers
3197           (goto-char (point-min))
3198           (and (re-search-forward
3199                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3200                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3201                (message-delete-line))
3202           (pop headers)))
3203       ;; Go through all the required headers and see if they are in the
3204       ;; articles already.  If they are not, or are empty, they are
3205       ;; inserted automatically - except for Subject, Newsgroups and
3206       ;; Distribution.
3207       (while headers
3208         (goto-char (point-min))
3209         (setq elem (pop headers))
3210         (if (consp elem)
3211             (if (eq (car elem) 'optional)
3212                 (setq header (cdr elem))
3213               (setq header (car elem)))
3214           (setq header elem))
3215         (when (or (not (re-search-forward
3216                         (concat "^"
3217                                 (regexp-quote
3218                                  (downcase
3219                                   (if (stringp header)
3220                                       header
3221                                     (symbol-name header))))
3222                                 ":")
3223                         nil t))
3224                   (progn
3225                     ;; The header was found.  We insert a space after the
3226                     ;; colon, if there is none.
3227                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
3228                     ;; Find out whether the header is empty...
3229                     (looking-at "[ \t]*$")))
3230           ;; So we find out what value we should insert.
3231           (setq value
3232                 (cond
3233                  ((and (consp elem) (eq (car elem) 'optional))
3234                   ;; This is an optional header.  If the cdr of this
3235                   ;; is something that is nil, then we do not insert
3236                   ;; this header.
3237                   (setq header (cdr elem))
3238                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3239                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3240                  ((consp elem)
3241                   ;; The element is a cons.  Either the cdr is a
3242                   ;; string to be inserted verbatim, or it is a
3243                   ;; function, and we insert the value returned from
3244                   ;; this function.
3245                   (or (and (stringp (cdr elem)) (cdr elem))
3246                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3247                  ((and (boundp header) (symbol-value header))
3248                   ;; The element is a symbol.  We insert the value
3249                   ;; of this symbol, if any.
3250                   (symbol-value header))
3251                  (t
3252                   ;; We couldn't generate a value for this header,
3253                   ;; so we just ask the user.
3254                   (read-from-minibuffer
3255                    (format "Empty header for %s; enter value: " header)))))
3256           ;; Finally insert the header.
3257           (when (and value
3258                      (not (equal value "")))
3259             (save-excursion
3260               (if (bolp)
3261                   (progn
3262                     ;; This header didn't exist, so we insert it.
3263                     (goto-char (point-max))
3264                     (insert (if (stringp header) header (symbol-name header))
3265                             ": " value "\n")
3266                     (forward-line -1))
3267                 ;; The value of this header was empty, so we clear
3268                 ;; totally and insert the new value.
3269                 (delete-region (point) (gnus-point-at-eol))
3270                 (insert value))
3271               ;; Add the deletable property to the headers that require it.
3272               (and (memq header message-deletable-headers)
3273                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3274                    (add-text-properties
3275                     (point) (match-end 0)
3276                     '(message-deletable t face italic) (current-buffer)))))))
3277       ;; Insert new Sender if the From is strange.
3278       (let ((from (message-fetch-field "from"))
3279             (sender (message-fetch-field "sender"))
3280             (secure-sender (message-make-sender)))
3281         (when (and from
3282                    (not (message-check-element 'sender))
3283                    (not (string=
3284                          (downcase
3285                           (cadr (std11-extract-address-components from)))
3286                          (downcase secure-sender)))
3287                    (or (null sender)
3288                        (not
3289                         (string=
3290                          (downcase
3291                           (cadr (std11-extract-address-components sender)))
3292                          (downcase secure-sender)))))
3293           (goto-char (point-min))
3294           ;; Rename any old Sender headers to Original-Sender.
3295           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3296             (beginning-of-line)
3297             (insert "Original-")
3298             (beginning-of-line))
3299           (when (or (message-news-p)
3300                     (string-match "@.+\\.." secure-sender))
3301             (insert "Sender: " secure-sender "\n")))))))
3302
3303 (defun message-insert-courtesy-copy ()
3304   "Insert a courtesy message in mail copies of combined messages."
3305   (let (newsgroups)
3306     (save-excursion
3307       (save-restriction
3308         (message-narrow-to-headers)
3309         (when (setq newsgroups (message-fetch-field "newsgroups"))
3310           (goto-char (point-max))
3311           (insert "Posted-To: " newsgroups "\n")))
3312       (forward-line 1)
3313       (when message-courtesy-message
3314         (cond
3315          ((string-match "%s" message-courtesy-message)
3316           (insert (format message-courtesy-message newsgroups)))
3317          (t
3318           (insert message-courtesy-message)))))))
3319
3320 ;;;
3321 ;;; Setting up a message buffer
3322 ;;;
3323
3324 (defun message-fill-address (header value)
3325   (save-restriction
3326     (narrow-to-region (point) (point))
3327     (insert (capitalize (symbol-name header))
3328             ": "
3329             (if (consp value) (car value) value)
3330             "\n")
3331     (narrow-to-region (point-min) (1- (point-max)))
3332     (let (quoted last)
3333       (goto-char (point-min))
3334       (while (not (eobp))
3335         (skip-chars-forward "^,\"" (point-max))
3336         (if (or (= (following-char) ?,)
3337                 (eobp))
3338             (when (not quoted)
3339               (if last
3340                   (save-excursion
3341                     (goto-char last)
3342                     (looking-at "[ \t]*")
3343                     (replace-match "\n " t t)))
3344               (setq last (1+ (point))))
3345           (setq quoted (not quoted)))
3346         (unless (eobp)
3347           (forward-char 1))))
3348     (goto-char (point-max))
3349     (widen)
3350     (forward-line 1)))
3351
3352 (defun message-fill-references (header value)
3353   (insert (capitalize (symbol-name header))
3354           ": "
3355           (std11-fill-msg-id-list-string
3356           (if (consp value) (car value) value))
3357           "\n"))
3358
3359 (defun message-fill-header (header value)
3360   (let ((begin (point))
3361         (fill-column 78)
3362         (fill-prefix " "))
3363     (insert (capitalize (symbol-name header))
3364             ": "
3365             (if (consp value) (car value) value)
3366             "\n")
3367     (save-restriction
3368       (narrow-to-region begin (point))
3369       (fill-region-as-paragraph begin (point))
3370       ;; Tapdance around looong Message-IDs.
3371       (forward-line -1)
3372       (when (looking-at "[ \t]*$")
3373         (message-delete-line))
3374       (goto-char begin)
3375       (re-search-forward ":" nil t)
3376       (when (looking-at "\n[ \t]+")
3377         (replace-match " " t t))
3378       (goto-char (point-max)))))
3379
3380 (defun message-shorten-references (header references)
3381   "Limit REFERENCES to be shorter than 988 characters."
3382   (let ((max 988)
3383         (cut 4)
3384         refs)
3385     (with-temp-buffer
3386       (insert references)
3387       (goto-char (point-min))
3388       (while (re-search-forward "<[^>]+>" nil t)
3389         (push (match-string 0) refs))
3390       (setq refs (nreverse refs))
3391       (while (> (length (mapconcat 'identity refs " ")) max)
3392         (when (< (length refs) (1+ cut))
3393           (decf cut))
3394         (setcdr (nthcdr cut refs) (cddr (nthcdr cut refs)))))
3395     (insert (capitalize (symbol-name header)) ": "
3396             (mapconcat 'identity refs " ") "\n")))
3397
3398 (defun message-position-point ()
3399   "Move point to where the user probably wants to find it."
3400   (message-narrow-to-headers)
3401   (cond
3402    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3403     (search-backward ":" )
3404     (widen)
3405     (forward-char 1)
3406     (if (= (following-char) ? )
3407         (forward-char 1)
3408       (insert " ")))
3409    (t
3410     (goto-char (point-max))
3411     (widen)
3412     (forward-line 1)
3413     (unless (looking-at "$")
3414       (forward-line 2)))
3415    (sit-for 0)))
3416
3417 (defun message-buffer-name (type &optional to group)
3418   "Return a new (unique) buffer name based on TYPE and TO."
3419   (cond
3420    ;; Check whether `message-generate-new-buffers' is a function,
3421    ;; and if so, call it.
3422    ((message-functionp message-generate-new-buffers)
3423     (funcall message-generate-new-buffers type to group))
3424    ;; Generate a new buffer name The Message Way.
3425    (message-generate-new-buffers
3426     (generate-new-buffer-name
3427      (concat "*" type
3428              (if to
3429                  (concat " to "
3430                          (or (car (std11-extract-address-components to))
3431                              to) "")
3432                "")
3433              (if (and group (not (string= group ""))) (concat " on " group) "")
3434              "*")))
3435    ;; Use standard name.
3436    (t
3437     (format "*%s message*" type))))
3438
3439 (defun message-pop-to-buffer (name)
3440   "Pop to buffer NAME, and warn if it already exists and is modified."
3441   (let ((pop-up-frames pop-up-frames)
3442         (special-display-buffer-names special-display-buffer-names)
3443         (special-display-regexps special-display-regexps)
3444         (same-window-buffer-names same-window-buffer-names)
3445         (same-window-regexps same-window-regexps)
3446         (buffer (get-buffer name))
3447         (cur (current-buffer)))
3448     (if (or (and (featurep 'xemacs)
3449                  (not (eq 'tty (device-type))))
3450             window-system
3451             (>= emacs-major-version 20))
3452         (when message-use-multi-frames
3453           (setq pop-up-frames t
3454                 special-display-buffer-names nil
3455                 special-display-regexps nil
3456                 same-window-buffer-names nil
3457                 same-window-regexps nil))
3458       (setq pop-up-frames nil))
3459     (if (and buffer
3460              (buffer-name buffer))
3461         (progn
3462           (set-buffer (pop-to-buffer buffer))
3463           (when (and (buffer-modified-p)
3464                      (not (y-or-n-p
3465                            "Message already being composed; erase? ")))
3466             (error "Message being composed")))
3467       (set-buffer (pop-to-buffer name)))
3468     (erase-buffer)
3469     (message-mode)
3470     (when pop-up-frames
3471       (make-local-variable 'message-original-frame)
3472       (setq message-original-frame (selected-frame)))))
3473
3474 (defun message-do-send-housekeeping ()
3475   "Kill old message buffers."
3476   ;; We might have sent this buffer already.  Delete it from the
3477   ;; list of buffers.
3478   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3479   (while (and message-max-buffers
3480               message-buffer-list
3481               (>= (length message-buffer-list) message-max-buffers))
3482     ;; Kill the oldest buffer -- unless it has been changed.
3483     (let ((buffer (pop message-buffer-list)))
3484       (when (and (buffer-name buffer)
3485                  (not (buffer-modified-p buffer)))
3486         (kill-buffer buffer))))
3487   ;; Rename the buffer.
3488   (if message-send-rename-function
3489       (funcall message-send-rename-function)
3490     (when (string-match "\\`\\*" (buffer-name))
3491       (rename-buffer
3492        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3493   ;; Push the current buffer onto the list.
3494   (when message-max-buffers
3495     (setq message-buffer-list
3496           (nconc message-buffer-list (list (current-buffer))))))
3497
3498 (defvar mc-modes-alist)
3499 (defun message-setup (headers &optional replybuffer actions)
3500   (when (and (boundp 'mc-modes-alist)
3501              (not (assq 'message-mode mc-modes-alist)))
3502     (push '(message-mode (encrypt . mc-encrypt-message)
3503                          (sign . mc-sign-message))
3504           mc-modes-alist))
3505   (when actions
3506     (setq message-send-actions actions))
3507   (setq message-reply-buffer replybuffer)
3508   (goto-char (point-min))
3509   ;; Insert all the headers.
3510   (mail-header-format
3511    (let ((h headers)
3512          (alist message-header-format-alist))
3513      (while h
3514        (unless (assq (caar h) message-header-format-alist)
3515          (push (list (caar h)) alist))
3516        (pop h))
3517      alist)
3518    headers)
3519   (delete-region (point) (progn (forward-line -1) (point)))
3520   (when message-default-headers
3521     (insert message-default-headers)
3522     (or (bolp) (insert ?\n)))
3523   (put-text-property
3524    (point)
3525    (progn
3526      (insert mail-header-separator "\n")
3527      (1- (point)))
3528    'read-only nil)
3529   (forward-line -1)
3530   (when (message-news-p)
3531     (when message-default-news-headers
3532       (insert message-default-news-headers)
3533       (or (bolp) (insert ?\n)))
3534     (when message-generate-headers-first
3535       (message-generate-headers
3536        (delq 'Lines
3537              (delq 'Subject
3538                    (copy-sequence message-required-news-headers))))))
3539   (when (message-mail-p)
3540     (when message-default-mail-headers
3541       (insert message-default-mail-headers)
3542       (or (bolp) (insert ?\n)))
3543     (when message-generate-headers-first
3544       (message-generate-headers
3545        (delq 'Lines
3546              (delq 'Subject
3547                    (copy-sequence message-required-mail-headers))))))
3548   (run-hooks 'message-signature-setup-hook)
3549   (message-insert-signature)
3550   (save-restriction
3551     (message-narrow-to-headers)
3552     (run-hooks 'message-header-setup-hook))
3553   (set-buffer-modified-p nil)
3554   (setq buffer-undo-list nil)
3555   (run-hooks 'message-setup-hook)
3556   (message-position-point)
3557   (undo-boundary))
3558
3559 (defun message-set-auto-save-file-name ()
3560   "Associate the message buffer with a file in the drafts directory."
3561   (when message-autosave-directory
3562     (if (gnus-alive-p)
3563         (setq message-draft-article
3564               (nndraft-request-associate-buffer "drafts"))
3565       (setq buffer-file-name (expand-file-name "*message*"
3566                                                message-autosave-directory))
3567       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
3568     (clear-visited-file-modtime)))
3569
3570 (defun message-disassociate-draft ()
3571   "Disassociate the message buffer from the drafts directory."
3572   (when message-draft-article
3573     (nndraft-request-expire-articles
3574      (list message-draft-article) "drafts" nil t)))
3575
3576 \f
3577
3578 ;;;
3579 ;;; Commands for interfacing with message
3580 ;;;
3581
3582 ;;;###autoload
3583 (defun message-mail (&optional to subject
3584                                other-headers continue switch-function
3585                                yank-action send-actions)
3586   "Start editing a mail message to be sent.
3587 OTHER-HEADERS is an alist of header/value pairs."
3588   (interactive)
3589   (let ((message-this-is-mail t))
3590     (message-pop-to-buffer (message-buffer-name "mail" to))
3591     (message-setup
3592      (nconc
3593       `((To . ,(or to "")) (Subject . ,(or subject "")))
3594       (when other-headers other-headers)))))
3595
3596 ;;;###autoload
3597 (defun message-news (&optional newsgroups subject)
3598   "Start editing a news article to be sent."
3599   (interactive)
3600   (let ((message-this-is-news t))
3601     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3602     (message-setup `((Newsgroups . ,(or newsgroups ""))
3603                      (Subject . ,(or subject ""))))))
3604
3605 ;;;###autoload
3606 (defun message-reply (&optional to-address wide)
3607   "Start editing a reply to the article in the current buffer."
3608   (interactive)
3609   (let ((cur (current-buffer))
3610         (inhibit-point-motion-hooks t)
3611         from date subject mct mft mrt
3612         never-mct to cc
3613         references message-id follow-to gnus-warning)
3614     (save-restriction
3615       (message-narrow-to-head)
3616       ;; Allow customizations to have their say.
3617       (if (not wide)
3618           ;; This is a regular reply.
3619           (if (message-functionp message-reply-to-function)
3620               (setq follow-to (funcall message-reply-to-function)))
3621         ;; This is a followup.
3622         (if (message-functionp message-wide-reply-to-function)
3623             (save-excursion
3624               (setq follow-to
3625                     (funcall message-wide-reply-to-function)))))
3626       ;; Find all relevant headers we need.
3627       (setq from (message-fetch-field "from")
3628             date (message-fetch-field "date" t)
3629             subject (or (message-fetch-field "subject") "none")
3630             references (message-fetch-field "references")
3631             message-id (message-fetch-field "message-id" t)
3632             to (message-fetch-field "to")
3633             cc (message-fetch-field "cc")
3634             mct (when (and wide message-use-mail-copies-to)
3635                   (message-fetch-field "mail-copies-to"))
3636             mft (when (and wide message-use-mail-followup-to)
3637                   (message-fetch-field "mail-followup-to"))
3638             mrt (when message-use-mail-reply-to
3639                   (or (message-fetch-field "mail-reply-to")
3640                       (message-fetch-field "reply-to")))
3641             gnus-warning (message-fetch-field "gnus-warning"))
3642       (when (and gnus-warning (string-match "<[^>]+>" gnus-warning))
3643         (setq message-id (match-string 0 gnus-warning)))
3644       ;; Remove any (buggy) Re:'s that are present and make a
3645       ;; proper one.
3646       (setq subject (message-make-followup-subject subject))
3647       (widen))
3648
3649     ;; Handle special values of Mail-Copies-To.
3650     (when mct
3651       (cond
3652        ((and (equal (downcase mct) "never")
3653              (or (not (eq message-use-mail-copies-to 'ask))
3654                  (message-y-or-n-p
3655                   (concat "Obey Mail-Copies-To: never? ") t "\
3656 You should normally obey the Mail-Copies-To: header.
3657
3658         `Mail-Copies-To: never'
3659 directs you not to send your response to the author.")))
3660         (setq never-mct t)
3661         (setq mct nil))
3662        ((and (equal (downcase mct) "always")
3663              (or (not (eq message-use-mail-copies-to 'ask))
3664                  (message-y-or-n-p
3665                   (concat "Obey Mail-Copies-To: always? ") t "\
3666 You should normally obey the Mail-Copies-To: header.
3667
3668         `Mail-Copies-To: always'
3669 sends a copy of your response to the author.")))
3670         (setq mct (or mrt from)))
3671        ((and (eq message-use-mail-copies-to 'ask)
3672              (not 
3673               (message-y-or-n-p
3674                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
3675 You should normally obey the Mail-Copies-To: header.
3676
3677         `Mail-Copies-To: " mct "'
3678 sends a copy of your response to " (if (string-match "," mct)
3679                                        "the specified addresses"
3680                                      "that address") ".")))
3681         (setq mct nil))
3682        ))
3683
3684     (unless follow-to
3685       (cond
3686        (to-address (setq follow-to (list (cons 'To to-address))))
3687        ((not wide) (setq follow-to (list (cons 'To (or mrt from)))))
3688        ;; Handle Mail-Followup-To.
3689        ((and mft
3690              (or (not (eq message-use-mail-followup-to 'ask))
3691                  (message-y-or-n-p
3692                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
3693 You should normally obey the Mail-Followup-To: header.
3694
3695         `Mail-Followup-To: " mft "'
3696 directs your response to " (if (string-match "," mft)
3697                                "the specified addresses"
3698                              "that address only") ".
3699
3700 A typical situation where Mail-Followup-To is used is when the author thinks
3701 that further discussion should take place only in "
3702                   (if (string-match "," mft)
3703                       "the specified mailing lists"
3704                     "that mailing list") ".")))
3705         (setq follow-to (list (cons 'To mft)))
3706         (when mct
3707           (push (cons 'Cc mct) follow-to)))
3708        (t
3709         (let (ccalist)
3710           (save-excursion
3711             (message-set-work-buffer)
3712             (unless never-mct
3713               (insert (or mrt from "")))
3714             (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3715             (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3716             (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
3717             (goto-char (point-min))
3718             (while (re-search-forward "[ \t]+" nil t)
3719               (replace-match " " t t))
3720             ;; Remove addresses that match `rmail-dont-reply-to-names'.
3721             (insert (prog1 (rmail-dont-reply-to (buffer-string))
3722                       (erase-buffer)))
3723             (goto-char (point-min))
3724             ;; Perhaps Mail-Copies-To: never removed the only address?
3725             (when (eobp)
3726               (insert (or mrt from "")))
3727             (setq ccalist
3728                   (mapcar
3729                    (lambda (addr)
3730                      (cons (mail-strip-quoted-names addr) addr))
3731                    (message-tokenize-header (buffer-string))))
3732             (let ((s ccalist))
3733               (while s
3734                 (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3735           (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3736           (when ccalist
3737             (let ((ccs (cons 'Cc (mapconcat
3738                                   (lambda (addr) (cdr addr)) ccalist ", "))))
3739               (when (string-match "^ +" (cdr ccs))
3740                 (setcdr ccs (substring (cdr ccs) (match-end 0))))
3741               (push ccs follow-to)))))))
3742
3743     (message-pop-to-buffer (message-buffer-name
3744                             (if wide "wide reply" "reply") from
3745                             (if wide to-address nil)))
3746
3747     (setq message-reply-headers
3748           (vector 0 subject from date message-id references 0 0 ""))
3749
3750     (message-setup
3751      `((Subject . ,subject)
3752        ,@follow-to
3753        ,@(if (or references message-id)
3754              `((References . ,(concat (or references "") (and references " ")
3755                                       (or message-id ""))))))
3756      cur)))
3757
3758 ;;;###autoload
3759 (defun message-wide-reply (&optional to-address)
3760   "Make a \"wide\" reply to the message in the current buffer."
3761   (interactive)
3762   (message-reply to-address t))
3763
3764 ;;;###autoload
3765 (defun message-followup (&optional to-newsgroups)
3766   "Follow up to the message in the current buffer."
3767   (interactive)
3768   (let ((cur (current-buffer))
3769         (inhibit-point-motion-hooks t)
3770         from date subject mct mft mrt
3771         (message-this-is-news t)
3772         followup-to distribution newsgroups posted-to
3773         references message-id follow-to gnus-warning)
3774     (save-restriction
3775       (message-narrow-to-head)
3776       ;; Allow customizations to have their say.
3777       ;; This is a followup.
3778       (when (message-functionp message-followup-to-function)
3779         (setq follow-to
3780               (funcall message-followup-to-function)))
3781       ;; Find all relevant headers we need.
3782       (setq from (message-fetch-field "from")
3783             date (message-fetch-field "date" t)
3784             subject (or (message-fetch-field "subject") "none")
3785             references (message-fetch-field "references")
3786             message-id (message-fetch-field "message-id" t)
3787             followup-to (when message-use-followup-to
3788                           (message-fetch-field "followup-to"))
3789             distribution (message-fetch-field "distribution")
3790             newsgroups (message-fetch-field "newsgroups")
3791             posted-to (message-fetch-field "posted-to")
3792             mct (when message-use-mail-copies-to
3793                   (message-fetch-field "mail-copies-to"))
3794             mft (when message-use-mail-followup-to
3795                   (message-fetch-field "mail-followup-to"))
3796             mrt (when message-use-mail-reply-to
3797                   (or (message-fetch-field "mail-reply-to")
3798                       (message-fetch-field "reply-to")))
3799             gnus-warning (message-fetch-field "gnus-warning"))
3800       (when (and gnus-warning (string-match "<[^>]+>" gnus-warning))
3801         (setq message-id (match-string 0 gnus-warning)))
3802       ;; Remove bogus distribution.
3803       (when (and (stringp distribution)
3804                  (let ((case-fold-search t))
3805                    (string-match "world" distribution)))
3806         (setq distribution nil))
3807       ;; Remove any (buggy) Re:'s that are present and make a
3808       ;; proper one.
3809       (setq subject (message-make-followup-subject subject))
3810       (widen))
3811
3812     ;; Handle special values of Mail-Copies-To.
3813     (when mct
3814       (cond
3815        ((and (equal (downcase mct) "never")
3816              (or (not (eq message-use-mail-copies-to 'ask))
3817                  (message-y-or-n-p
3818                   (concat "Obey Mail-Copies-To: never? ") t "\
3819 You should normally obey the Mail-Copies-To: header.
3820
3821         `Mail-Copies-To: never'
3822 directs you not to send your response to the author.")))
3823         (setq mct nil))
3824        ((and (equal (downcase mct) "always")
3825              (or (not (eq message-use-mail-copies-to 'ask))
3826                  (message-y-or-n-p
3827                   (concat "Obey Mail-Copies-To: always? ") t "\
3828 You should normally obey the Mail-Copies-To: header.
3829
3830         `Mail-Copies-To: always'
3831 sends a copy of your response to the author.")))
3832         (setq mct (or mrt from)))
3833        ((and (eq message-use-mail-copies-to 'ask)
3834              (not 
3835               (message-y-or-n-p
3836                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
3837 You should normally obey the Mail-Copies-To: header.
3838
3839         `Mail-Copies-To: " mct "'
3840 sends a copy of your response to " (if (string-match "," mct)
3841                                        "the specified addresses"
3842                                      "that address") ".")))
3843         (setq mct nil))
3844        ))
3845
3846     (unless follow-to
3847       (cond
3848        (to-newsgroups (setq follow-to (list (cons 'Newsgroups to-newsgroups))))
3849        ;; Handle Followup-To.
3850        (followup-to
3851         (cond
3852          ((equal (downcase followup-to) "poster")
3853           (if (or (eq message-use-followup-to 'use)
3854                   (message-y-or-n-p "Obey Followup-To: poster? " t "\
3855 You should normally obey the Followup-To: header.
3856
3857         `Followup-To: poster'
3858 sends your response via e-mail instead of news.
3859
3860 A typical situation where `Followup-To: poster' is used is when the author
3861 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3862               (setq message-this-is-news nil
3863                     distribution nil
3864                     follow-to (list (cons 'To (or mrt from ""))))
3865             (setq follow-to (list (cons 'Newsgroups newsgroups)))))
3866          (t
3867           (if (or (equal followup-to newsgroups)
3868                   (not (eq message-use-followup-to 'ask))
3869                   (message-y-or-n-p
3870                    (concat "Obey Followup-To: " followup-to "? ") t "\
3871 You should normally obey the Followup-To: header.
3872
3873         `Followup-To: " followup-to "'
3874 directs your response to " (if (string-match "," followup-to)
3875                                "the specified newsgroups"
3876                              "that newsgroup only") ".
3877
3878 If a message is posted to several newsgroups, Followup-To is often
3879 used to direct the following discussion to one newsgroup only,
3880 because discussions that are spread over several newsgroup tend to
3881 be fragmented and very difficult to follow.
3882
3883 Also, some source/announcement newsgroups are not indented for discussion;
3884 responses here are directed to other newsgroups."))
3885               (setq follow-to (list (cons 'Newsgroups followup-to)))
3886             (setq follow-to (list (cons 'Newsgroups newsgroups)))))))
3887        ;; Handle Mail-Followup-To, followup via e-mail.
3888        ((and mft
3889              (or (not (eq message-use-mail-followup-to 'ask))
3890                  (message-y-or-n-p
3891                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
3892 You should normally obey the Mail-Followup-To: header.
3893
3894         `Mail-Followup-To: " mft "'
3895 directs your response to " (if (string-match "," mft)
3896                                "the specified addresses"
3897                              "that address only") " instead of news.
3898
3899 A typical situation where Mail-Followup-To is used is when the author thinks
3900 that further discussion should take place only in "
3901                              (if (string-match "," mft)
3902                                  "the specified mailing lists"
3903                                "that mailing list") ".")))
3904         (setq message-this-is-news nil
3905               distribution nil
3906               follow-to (list (cons 'To mft))))
3907        (posted-to (setq follow-to (list (cons 'Newsgroups posted-to))))
3908        (t
3909         (setq follow-to (list (cons 'Newsgroups newsgroups))))))
3910
3911     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3912
3913     (setq message-reply-headers
3914           (vector 0 subject from date message-id references 0 0 ""))
3915
3916     (message-setup
3917      `((Subject . ,subject)
3918        ,@follow-to
3919        ,@(and mct (list (cons 'Cc mct)))
3920        ,@(and distribution (list (cons 'Distribution distribution)))
3921        ,@(if (or references message-id)
3922              `((References . ,(concat (or references "") (and references " ")
3923                                       (or message-id ""))))))
3924      cur)))
3925
3926 ;;;###autoload
3927 (defun message-cancel-news ()
3928   "Cancel an article you posted."
3929   (interactive)
3930   (unless (message-news-p)
3931     (error "This is not a news article; canceling is impossible"))
3932   (when (yes-or-no-p "Do you really want to cancel this article? ")
3933     (let (from newsgroups message-id distribution buf sender)
3934       (save-excursion
3935         ;; Get header info. from original article.
3936         (save-restriction
3937           (message-narrow-to-head)
3938           (setq from (message-fetch-field "from")
3939                 sender (message-fetch-field "sender")
3940                 newsgroups (message-fetch-field "newsgroups")
3941                 message-id (message-fetch-field "message-id" t)
3942                 distribution (message-fetch-field "distribution")))
3943         ;; Make sure that this article was written by the user.
3944         (unless (or (and sender
3945                          (string-equal
3946                           (downcase sender)
3947                           (downcase (message-make-sender))))
3948                     (string-equal
3949                      (downcase (cadr (std11-extract-address-components
3950                                       from)))
3951                      (downcase (cadr (std11-extract-address-components
3952                                       (message-make-from))))))
3953           (error "This article is not yours"))
3954         ;; Make control message.
3955         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
3956         (erase-buffer)
3957         (insert "Newsgroups: " newsgroups "\n"
3958                 "From: " (message-make-from) "\n"
3959                 "Subject: cmsg cancel " message-id "\n"
3960                 "Control: cancel " message-id "\n"
3961                 (if distribution
3962                     (concat "Distribution: " distribution "\n")
3963                   "")
3964                 mail-header-separator "\n"
3965                 message-cancel-message)
3966         (message "Canceling your article...")
3967         (if (let ((message-syntax-checks
3968                    'dont-check-for-anything-just-trust-me)
3969                   (message-encoding-buffer (current-buffer))
3970                   (message-edit-buffer (current-buffer)))
3971               (message-send-news))
3972             (message "Canceling your article...done"))
3973         (kill-buffer buf)))))
3974
3975 ;;;###autoload
3976 (defun message-supersede ()
3977   "Start composing a message to supersede the current message.
3978 This is done simply by taking the old article and adding a Supersedes
3979 header line with the old Message-ID."
3980   (interactive)
3981   (let ((cur (current-buffer))
3982         (sender (message-fetch-field "sender"))
3983         (from (message-fetch-field "from")))
3984     ;; Check whether the user owns the article that is to be superseded.
3985     (unless (or (and sender
3986                      (string-equal
3987                       (downcase sender)
3988                       (downcase (message-make-sender))))
3989                 (string-equal
3990                  (downcase (cadr (std11-extract-address-components from)))
3991                  (downcase (cadr (std11-extract-address-components
3992                                   (message-make-from))))))
3993       (error "This article is not yours"))
3994     ;; Get a normal message buffer.
3995     (message-pop-to-buffer (message-buffer-name "supersede"))
3996     (insert-buffer-substring cur)
3997     (message-narrow-to-head)
3998     ;; Remove unwanted headers.
3999     (when message-ignored-supersedes-headers
4000       (message-remove-header message-ignored-supersedes-headers t))
4001     (goto-char (point-min))
4002     (if (not (re-search-forward "^Message-ID: " nil t))
4003         (error "No Message-ID in this article")
4004       (replace-match "Supersedes: " t t))
4005     (goto-char (point-max))
4006     (insert mail-header-separator)
4007     (widen)
4008     (forward-line 1)))
4009
4010 ;;;###autoload
4011 (defun message-recover ()
4012   "Reread contents of current buffer from its last auto-save file."
4013   (interactive)
4014   (let ((file-name (make-auto-save-file-name)))
4015     (cond ((save-window-excursion
4016              (if (not (eq system-type 'vax-vms))
4017                  (with-output-to-temp-buffer "*Directory*"
4018                    (buffer-disable-undo standard-output)
4019                    (let ((default-directory "/"))
4020                      (call-process
4021                       "ls" nil standard-output nil "-l" file-name))))
4022              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
4023            (let ((buffer-read-only nil))
4024              (erase-buffer)
4025              (insert-file-contents file-name nil)))
4026           (t (error "message-recover cancelled")))))
4027
4028 ;;; Washing Subject:
4029
4030 (defun message-wash-subject (subject)
4031   "Remove junk like \"Re:\", \"(fwd)\", etc. that was added to the subject by previous forwarders, replyers, etc."
4032   (with-temp-buffer
4033     (insert-string subject)
4034     (goto-char (point-min))
4035     ;; strip Re/Fwd stuff off the beginning
4036     (while (re-search-forward
4037             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
4038       (replace-match ""))
4039
4040     ;; and gnus-style forwards [foo@bar.com] subject
4041     (goto-char (point-min))
4042     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
4043       (replace-match ""))
4044
4045     ;; and off the end
4046     (goto-char (point-max))
4047     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
4048       (replace-match ""))
4049
4050     ;; and finally, any whitespace that was left-over
4051     (goto-char (point-min))
4052     (while (re-search-forward "^[ \t]+" nil t)
4053       (replace-match ""))
4054     (goto-char (point-max))
4055     (while (re-search-backward "[ \t]+$" nil t)
4056       (replace-match ""))
4057
4058     (buffer-string)))
4059     
4060 ;;; Forwarding messages.
4061
4062 (defun message-forward-subject-author-subject (subject)
4063   "Generate a subject for a forwarded message.
4064 The form is: [Source] Subject, where if the original message was mail,
4065 Source is the sender, and if the original message was news, Source is
4066 the list of newsgroups is was posted to."
4067   (concat "["
4068           (or (message-fetch-field
4069                (if (message-news-p) "newsgroups" "from"))
4070               "(nowhere)")
4071           "] " subject))
4072
4073 (defun message-forward-subject-fwd (subject)
4074   "Generate a subject for a forwarded message.
4075 The form is: Fwd: Subject, where Subject is the original subject of
4076 the message."
4077   (concat "Fwd: " subject))
4078
4079 (defun message-make-forward-subject ()
4080   "Return a Subject header suitable for the message in the current buffer."
4081   (save-excursion
4082     (save-restriction
4083       (current-buffer)
4084       (message-narrow-to-head)
4085       (let ((funcs message-make-forward-subject-function)
4086             (subject (if message-wash-forwarded-subjects
4087                          (message-wash-subject
4088                           (or (eword-decode-unstructured-field-body
4089                                (message-fetch-field "Subject")) ""))
4090                        (or (eword-decode-unstructured-field-body
4091                             (message-fetch-field "Subject")) ""))))
4092         ;; Make sure funcs is a list.
4093         (and funcs
4094              (not (listp funcs))
4095              (setq funcs (list funcs)))
4096         ;; Apply funcs in order, passing subject generated by previous
4097         ;; func to the next one.
4098         (while funcs
4099           (when (message-functionp (car funcs))
4100             (setq subject (funcall (car funcs) subject)))
4101           (setq funcs (cdr funcs)))
4102         subject))))
4103
4104 ;;;###autoload
4105 (defun message-forward (&optional news)
4106   "Forward the current message via mail.
4107 Optional NEWS will use news to forward instead of mail."
4108   (interactive "P")
4109   (let ((cur (current-buffer))
4110         (subject (message-make-forward-subject))
4111         art-beg)
4112     (if news (message-news nil subject) (message-mail nil subject))
4113     ;; Put point where we want it before inserting the forwarded
4114     ;; message.
4115     (if message-signature-before-forwarded-message
4116         (goto-char (point-max))
4117       (message-goto-body))
4118     ;; Make sure we're at the start of the line.
4119     (unless (eolp)
4120       (insert "\n"))
4121     ;; Narrow to the area we are to insert.
4122     (narrow-to-region (point) (point))
4123     ;; Insert the separators and the forwarded buffer.
4124     (insert message-forward-start-separator)
4125     (setq art-beg (point))
4126     (insert-buffer-substring cur)
4127     (goto-char (point-max))
4128     (insert message-forward-end-separator)
4129     (set-text-properties (point-min) (point-max) nil)
4130     ;; Remove all unwanted headers.
4131     (goto-char art-beg)
4132     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
4133                                   (1- (point))
4134                                 (point)))
4135     (goto-char (point-min))
4136     (message-remove-header message-included-forward-headers t nil t)
4137     (widen)
4138     (message-position-point)))
4139
4140 ;;;###autoload
4141 (defun message-resend (address)
4142   "Resend the current article to ADDRESS."
4143   (interactive "sResend message to: ")
4144   (message "Resending message to %s..." address)
4145   (save-excursion
4146     (let ((cur (current-buffer))
4147           beg)
4148       ;; We first set up a normal mail buffer.
4149       (set-buffer (get-buffer-create " *message resend*"))
4150       (erase-buffer)
4151       ;; avoid to turn-on-mime-edit
4152       (let (message-setup-hook)
4153         (message-setup `((To . ,address)))
4154         )
4155       ;; Insert our usual headers.
4156       (message-generate-headers '(From Date To))
4157       (message-narrow-to-headers)
4158       ;; Rename them all to "Resent-*".
4159       (while (re-search-forward "^[A-Za-z]" nil t)
4160         (forward-char -1)
4161         (insert "Resent-"))
4162       (widen)
4163       (forward-line)
4164       (delete-region (point) (point-max))
4165       (setq beg (point))
4166       ;; Insert the message to be resent.
4167       (insert-buffer-substring cur)
4168       (goto-char (point-min))
4169       (search-forward "\n\n")
4170       (forward-char -1)
4171       (save-restriction
4172         (narrow-to-region beg (point))
4173         (message-remove-header message-ignored-resent-headers t)
4174         (goto-char (point-max)))
4175       (insert mail-header-separator)
4176       ;; Rename all old ("Also-")Resent headers.
4177       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
4178         (beginning-of-line)
4179         (insert "Also-"))
4180       ;; Quote any "From " lines at the beginning.
4181       (goto-char beg)
4182       (when (looking-at "From ")
4183         (replace-match "X-From-Line: "))
4184       ;; Send it.
4185       (let ((message-encoding-buffer (current-buffer))
4186             (message-edit-buffer (current-buffer)))
4187         (message-send-mail))
4188       (kill-buffer (current-buffer)))
4189     (message "Resending message to %s...done" address)))
4190
4191 ;;;###autoload
4192 (defun message-bounce ()
4193   "Re-mail the current message.
4194 This only makes sense if the current message is a bounce message than
4195 contains some mail you have written which has been bounced back to
4196 you."
4197   (interactive)
4198   (let ((cur (current-buffer))
4199         boundary)
4200     (message-pop-to-buffer (message-buffer-name "bounce"))
4201     (insert-buffer-substring cur)
4202     (undo-boundary)
4203     (message-narrow-to-head)
4204     (if (and (message-fetch-field "MIME-Version")
4205              (setq boundary (message-fetch-field "Content-Type")))
4206         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
4207             (setq boundary (concat (match-string 1 boundary) " *\n"
4208                                    "Content-Type: message/rfc822"))
4209           (setq boundary nil)))
4210     (widen)
4211     (goto-char (point-min))
4212     (search-forward "\n\n" nil t)
4213     (or (and boundary
4214              (re-search-forward boundary nil t)
4215              (forward-line 2))
4216         (and (re-search-forward message-unsent-separator nil t)
4217              (forward-line 1))
4218         (re-search-forward "^Return-Path:.*\n" nil t))
4219     ;; We remove everything before the bounced mail.
4220     (delete-region
4221      (point-min)
4222      (if (re-search-forward "^[^ \n\t]+:" nil t)
4223          (match-beginning 0)
4224        (point)))
4225     (save-restriction
4226       (message-narrow-to-head)
4227       (message-remove-header message-ignored-bounced-headers t)
4228       (goto-char (point-max))
4229       (insert mail-header-separator))
4230     (message-position-point)))
4231
4232 ;;;
4233 ;;; Interactive entry points for new message buffers.
4234 ;;;
4235
4236 ;;;###autoload
4237 (defun message-mail-other-window (&optional to subject)
4238   "Like `message-mail' command, but display mail buffer in another window."
4239   (interactive)
4240   (let ((pop-up-windows t)
4241         (special-display-buffer-names nil)
4242         (special-display-regexps nil)
4243         (same-window-buffer-names nil)
4244         (same-window-regexps nil))
4245     (message-pop-to-buffer (message-buffer-name "mail" to)))
4246   (let ((message-this-is-mail t))
4247     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4248
4249 ;;;###autoload
4250 (defun message-mail-other-frame (&optional to subject)
4251   "Like `message-mail' command, but display mail buffer in another frame."
4252   (interactive)
4253   (let ((pop-up-frames t)
4254         (special-display-buffer-names nil)
4255         (special-display-regexps nil)
4256         (same-window-buffer-names nil)
4257         (same-window-regexps nil))
4258     (message-pop-to-buffer (message-buffer-name "mail" to)))
4259   (let ((message-this-is-mail t))
4260     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4261
4262 ;;;###autoload
4263 (defun message-news-other-window (&optional newsgroups subject)
4264   "Start editing a news article to be sent."
4265   (interactive)
4266   (let ((pop-up-windows t)
4267         (special-display-buffer-names nil)
4268         (special-display-regexps nil)
4269         (same-window-buffer-names nil)
4270         (same-window-regexps nil))
4271     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4272   (let ((message-this-is-news t))
4273     (message-setup `((Newsgroups . ,(or newsgroups ""))
4274                      (Subject . ,(or subject ""))))))
4275
4276 ;;;###autoload
4277 (defun message-news-other-frame (&optional newsgroups subject)
4278   "Start editing a news article to be sent."
4279   (interactive)
4280   (let ((pop-up-frames t)
4281         (special-display-buffer-names nil)
4282         (special-display-regexps nil)
4283         (same-window-buffer-names nil)
4284         (same-window-regexps nil))
4285     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4286   (let ((message-this-is-news t))
4287     (message-setup `((Newsgroups . ,(or newsgroups ""))
4288                      (Subject . ,(or subject ""))))))
4289
4290 ;;; underline.el
4291
4292 ;; This code should be moved to underline.el (from which it is stolen).
4293
4294 ;;;###autoload
4295 (defun bold-region (start end)
4296   "Bold all nonblank characters in the region.
4297 Works by overstriking characters.
4298 Called from program, takes two arguments START and END
4299 which specify the range to operate on."
4300   (interactive "r")
4301   (save-excursion
4302     (let ((end1 (make-marker)))
4303       (move-marker end1 (max start end))
4304       (goto-char (min start end))
4305       (while (< (point) end1)
4306         (or (looking-at "[_\^@- ]")
4307             (insert (following-char) "\b"))
4308         (forward-char 1)))))
4309
4310 ;;;###autoload
4311 (defun unbold-region (start end)
4312   "Remove all boldness (overstruck characters) in the region.
4313 Called from program, takes two arguments START and END
4314 which specify the range to operate on."
4315   (interactive "r")
4316   (save-excursion
4317     (let ((end1 (make-marker)))
4318       (move-marker end1 (max start end))
4319       (goto-char (min start end))
4320       (while (re-search-forward "\b" end1 t)
4321         (if (eq (following-char) (char-after (- (point) 2)))
4322             (delete-char -2))))))
4323
4324 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
4325
4326 ;; Support for toolbar
4327 (when (string-match "XEmacs\\|Lucid" emacs-version)
4328   (require 'messagexmas))
4329
4330 ;;; Group name completion.
4331
4332 (defvar message-newgroups-header-regexp
4333   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
4334   "Regexp that match headers that lists groups.")
4335
4336 (defun message-tab ()
4337   "Expand group names in Newsgroups and Followup-To headers.
4338 Do a `tab-to-tab-stop' if not in those headers."
4339   (interactive)
4340   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
4341         (mail-abbrev-in-expansion-header-p))
4342       (message-expand-group)
4343     (tab-to-tab-stop)))
4344
4345 (defvar gnus-active-hashtb)
4346 (defun message-expand-group ()
4347   "Expand the group name under point."
4348   (let* ((b (save-excursion
4349               (save-restriction
4350                 (narrow-to-region
4351                  (save-excursion
4352                    (beginning-of-line)
4353                    (skip-chars-forward "^:")
4354                    (1+ (point)))
4355                  (point))
4356                 (skip-chars-backward "^, \t\n") (point))))
4357          (completion-ignore-case t)
4358          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
4359                                             (point))))
4360          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
4361          (completions (all-completions string hashtb))
4362          comp)
4363     (delete-region b (point))
4364     (cond
4365      ((= (length completions) 1)
4366       (if (string= (car completions) string)
4367           (progn
4368             (insert string)
4369             (message "Only matching group"))
4370         (insert (car completions))))
4371      ((and (setq comp (try-completion string hashtb))
4372            (not (string= comp string)))
4373       (insert comp))
4374      (t
4375       (insert string)
4376       (if (not comp)
4377           (message "No matching groups")
4378         (save-selected-window
4379           (pop-to-buffer "*Completions*")
4380           (buffer-disable-undo)
4381           (let ((buffer-read-only nil))
4382             (erase-buffer)
4383             (let ((standard-output (current-buffer)))
4384               (display-completion-list (sort completions 'string<)))
4385             (goto-char (point-min))
4386             (delete-region (point) (progn (forward-line 3) (point))))))))))
4387
4388 ;;; Help stuff.
4389
4390 (defun message-talkative-question (ask question show &rest text)
4391   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
4392 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
4393 The following arguments may contain lists of values."
4394   (if (and show
4395            (setq text (message-flatten-list text)))
4396       (save-window-excursion
4397         (save-excursion
4398           (with-output-to-temp-buffer " *MESSAGE information message*"
4399             (set-buffer " *MESSAGE information message*")
4400             (mapcar 'princ text)
4401             (goto-char (point-min))))
4402         (funcall ask question))
4403     (funcall ask question)))
4404
4405 (defun message-flatten-list (list)
4406   "Return a new, flat list that contains all elements of LIST.
4407
4408 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
4409 => (1 2 3 4 5 6 7)"
4410   (cond ((consp list)
4411          (apply 'append (mapcar 'message-flatten-list list)))
4412         (list
4413          (list list))))
4414
4415 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
4416   "Create and return a buffer with a name based on NAME using generate-new-buffer.
4417 Then clone the local variables and values from the old buffer to the
4418 new one, cloning only the locals having a substring matching the
4419 regexp varstr."
4420   (let ((oldbuf (current-buffer)))
4421     (save-excursion
4422       (set-buffer (generate-new-buffer name))
4423       (message-clone-locals oldbuf)
4424       (current-buffer))))
4425
4426 (defun message-clone-locals (buffer)
4427   "Clone the local variables from BUFFER to the current buffer."
4428   (let ((locals (save-excursion
4429                   (set-buffer buffer)
4430                   (buffer-local-variables)))
4431         (regexp "^gnus\\|^nn\\|^message"))
4432     (mapcar
4433      (lambda (local)
4434        (when (and (consp local)
4435                   (car local)
4436                   (string-match regexp (symbol-name (car local))))
4437          (ignore-errors
4438            (set (make-local-variable (car local))
4439                 (cdr local)))))
4440      locals)))
4441
4442
4443 ;;; @ for MIME Edit mode
4444 ;;;
4445
4446 (defun message-maybe-setup-default-charset ()
4447   (let ((charset
4448          (and (boundp 'gnus-summary-buffer)
4449               (buffer-live-p gnus-summary-buffer)
4450               (save-excursion
4451                 (set-buffer gnus-summary-buffer)
4452                 default-mime-charset))))
4453     (if charset
4454         (progn
4455           (make-local-variable 'default-mime-charset)
4456           (setq default-mime-charset charset)
4457           ))))
4458
4459 (defun message-maybe-encode ()
4460   (when message-mime-mode
4461     (run-hooks 'mime-edit-translate-hook)
4462     (if (catch 'mime-edit-error
4463           (save-excursion
4464             (mime-edit-translate-body)
4465             ))
4466         (error "Translation error!")
4467       )
4468     (end-of-invisible)
4469     (run-hooks 'mime-edit-exit-hook)
4470     ))
4471
4472 ;;; XXX: currently broken; message-yank-original resets message-reply-buffer.
4473 (defun message-mime-insert-article (&optional message)
4474   (interactive)
4475   (let ((message-cite-function 'mime-edit-inserted-message-filter)
4476         (message-reply-buffer gnus-original-article-buffer)
4477         )
4478     (message-yank-original nil)
4479     ))
4480
4481 (set-alist 'mime-edit-message-inserter-alist
4482            'message-mode (function message-mime-insert-article))
4483
4484 ;;; Miscellaneous functions
4485
4486 ;; stolen (and renamed) from nnheader.el
4487 (defun message-replace-chars-in-string (string from to)
4488   "Replace characters in STRING from FROM to TO."
4489   (let ((string (substring string 0))   ;Copy string.
4490         (len (length string))
4491         (idx 0))
4492     ;; Replace all occurrences of FROM with TO.
4493     (while (< idx len)
4494       (when (= (aref string idx) from)
4495         (aset string idx to))
4496       (setq idx (1+ idx)))
4497     string))
4498
4499 ;;;
4500 ;;; MIME functions
4501 ;;;
4502
4503 (defun message-encode-message-body ()
4504   "Examine the message body, encode it, and add the requisite headers."
4505   (when (featurep 'mule)
4506     (let (old-headers)
4507       (save-excursion
4508         (save-restriction
4509           (message-narrow-to-headers-or-head)
4510           (unless (setq old-headers (message-fetch-field "mime-version"))
4511             (message-remove-header
4512              "^Content-Transfer-Encoding:\\|^Content-Type:\\|^Mime-Version:" t))
4513           (goto-char (point-max))
4514           (widen)
4515           (narrow-to-region (point) (point-max))
4516           (let* ((charset (mm-encode-body))
4517                  (encoding (mm-body-encoding)))
4518             (when (consp charset)
4519               (error "Can't encode messages with multiple charsets (yet)"))
4520             (widen)
4521             (message-narrow-to-headers-or-head)
4522             (goto-char (point-max))
4523             (setq charset (or charset
4524                               (mm-mule-charset-to-mime-charset 'ascii)))
4525             ;; We don't insert MIME headers if they only say the default.
4526             (when (and (not old-headers)
4527                        (not (and (eq charset 'us-ascii)
4528                                  (eq encoding '7bit))))
4529               (mm-insert-rfc822-headers charset encoding))
4530             (mm-encode-body)))))))
4531
4532 (run-hooks 'message-load-hook)
4533
4534 (provide 'message)
4535
4536 ;;; message.el ends here