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