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