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