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