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