Sync up with Pterodactyl Gnus v0.51.
[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   (unless (eq 'message-mode major-mode)
2178     (error "%s must be invoked from a message buffer." this-command))
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 "")
2184             (string-equal bufname (buffer-name)))
2185         (message-kill-buffer)
2186       (message "%s must be invoked only for the current buffer." command))))
2187
2188 (defun message-delete-frame (frame org-frame)
2189   "Delete frame for editing message."
2190   (when (and (or (and (featurep 'xemacs)
2191                       (not (eq 'tty (device-type))))
2192                  window-system
2193                  (>= emacs-major-version 20))
2194              (or (and (eq message-delete-frame-on-exit t)
2195                       (select-frame frame)
2196                       (or (eq frame org-frame)
2197                           (prog1
2198                               (y-or-n-p "Delete this frame?")
2199                             (message ""))))
2200                  (and (eq message-delete-frame-on-exit 'ask)
2201                       (select-frame frame)
2202                       (prog1
2203                           (y-or-n-p "Delete this frame?")
2204                         (message "")))))
2205     (delete-frame frame)))
2206
2207 (defun message-bury (buffer)
2208   "Bury this mail buffer."
2209   (let ((newbuf (other-buffer buffer)))
2210     (bury-buffer buffer)
2211     (if (and (fboundp 'frame-parameters)
2212              (cdr (assq 'dedicated (frame-parameters)))
2213              (not (null (delq (selected-frame) (visible-frame-list)))))
2214         (delete-frame (selected-frame))
2215       (switch-to-buffer newbuf))))
2216
2217 (defun message-send (&optional arg)
2218   "Send the message in the current buffer.
2219 If `message-interactive' is non-nil, wait for success indication
2220 or error messages, and inform user.
2221 Otherwise any failure is reported in a message back to
2222 the user from the mailer."
2223   (interactive "P")
2224   ;; Disabled test.
2225   (when (or (buffer-modified-p)
2226             (message-check-element 'unchanged)
2227             (y-or-n-p "No changes in the buffer; really send? "))
2228     ;; Make it possible to undo the coming changes.
2229     (undo-boundary)
2230     (let ((inhibit-read-only t))
2231       (put-text-property (point-min) (point-max) 'read-only nil))
2232     (run-hooks 'message-send-hook)
2233     (message "Sending...")
2234     (let ((message-encoding-buffer
2235            (message-generate-new-buffer-clone-locals " message encoding"))
2236           (message-edit-buffer (current-buffer))
2237           (message-mime-mode mime-edit-mode-flag)
2238           (alist message-send-method-alist)
2239           (success t)
2240           elem sent)
2241       (save-excursion
2242         (set-buffer message-encoding-buffer)
2243         (erase-buffer)
2244         (insert-buffer message-edit-buffer)
2245         (funcall message-encode-function)
2246         (message-fix-before-sending)
2247         (while (and success
2248                     (setq elem (pop alist)))
2249           (when (and (or (not (funcall (cadr elem)))
2250                          (and (or (not (memq (car elem)
2251                                              message-sent-message-via))
2252                                   (y-or-n-p
2253                                    (format
2254                                     "Already sent message via %s; resend? "
2255                                     (car elem))))
2256                               (setq success (funcall (caddr elem) arg)))))
2257             (setq sent t))))
2258       (when (and success sent)
2259         (message-do-fcc)
2260         ;;(when (fboundp 'mail-hist-put-headers-into-history)
2261         ;; (mail-hist-put-headers-into-history))
2262         (run-hooks 'message-sent-hook)
2263         (message "Sending...done")
2264         ;; Mark the buffer as unmodified and delete autosave.
2265         (set-buffer-modified-p nil)
2266         (delete-auto-save-file-if-necessary t)
2267         (message-disassociate-draft)
2268         ;; Delete other mail buffers and stuff.
2269         (message-do-send-housekeeping)
2270         (message-do-actions message-send-actions)
2271         ;; Return success.
2272         t))))
2273
2274 (defun message-send-via-mail (arg)
2275   "Send the current message via mail."
2276   (message-send-mail arg))
2277
2278 (defun message-send-via-news (arg)
2279   "Send the current message via news."
2280   (message-send-news arg))
2281
2282 (defmacro message-check (type &rest forms)
2283   "Eval FORMS if TYPE is to be checked."
2284   `(or (message-check-element ,type)
2285        (save-excursion
2286          ,@forms)))
2287
2288 (put 'message-check 'lisp-indent-function 1)
2289 (put 'message-check 'edebug-form-spec '(form body))
2290
2291 (defun message-fix-before-sending ()
2292   "Do various things to make the message nice before sending it."
2293   ;; Make sure there's a newline at the end of the message.
2294   (goto-char (point-max))
2295   (unless (bolp)
2296     (insert "\n"))
2297   ;; Delete all invisible text.
2298   (message-check 'invisible-text
2299     (when (text-property-any (point-min) (point-max) 'invisible t)
2300       (put-text-property (point-min) (point-max) 'invisible nil)
2301       (unless (yes-or-no-p "Invisible text found and made visible; continue posting? ")
2302         (error "Invisible text found and made visible")))))
2303
2304 (defun message-add-action (action &rest types)
2305   "Add ACTION to be performed when doing an exit of type TYPES."
2306   (let (var)
2307     (while types
2308       (set (setq var (intern (format "message-%s-actions" (pop types))))
2309            (nconc (symbol-value var) (list action))))))
2310
2311 (defun message-do-actions (actions)
2312   "Perform all actions in ACTIONS."
2313   ;; Now perform actions on successful sending.
2314   (while actions
2315     (ignore-errors
2316       (cond
2317        ;; A simple function.
2318        ((message-functionp (car actions))
2319         (funcall (car actions)))
2320        ;; Something to be evaled.
2321        (t
2322         (eval (car actions)))))
2323     (pop actions)))
2324
2325 (defsubst message-maybe-split-and-send-mail ()
2326   "Split a message if necessary, and send it via mail.
2327 Returns nil if sending succeeded, returns any string if sending failed.
2328 This sub function is for exclusive use of `message-send-mail'."
2329   (let ((mime-edit-split-ignored-field-regexp
2330          mime-edit-split-ignored-field-regexp)
2331         (case-fold-search t)
2332         failure)
2333     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
2334       (setq mime-edit-split-ignored-field-regexp
2335             (concat (substring mime-edit-split-ignored-field-regexp
2336                                0 (match-beginning 0))
2337                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
2338                     "_so_don't_rape_it!"
2339                     (substring mime-edit-split-ignored-field-regexp
2340                                (match-end 0)))))
2341     (setq failure
2342           (or
2343            (catch 'message-sending-mail-failure
2344              (mime-edit-maybe-split-and-send
2345               (function
2346                (lambda ()
2347                  (interactive)
2348                  (save-restriction
2349                    (std11-narrow-to-header mail-header-separator)
2350                    (goto-char (point-min))
2351                    (when (re-search-forward "^Message-ID:" nil t)
2352                      (delete-region (match-end 0) (std11-field-end))
2353                      (insert " " (message-make-message-id))))
2354                  (condition-case err
2355                      (funcall message-send-mail-function)
2356                    (error
2357                     (throw 'message-sending-mail-failure err))))))
2358              nil)
2359            (condition-case err
2360                (progn
2361                  (funcall message-send-mail-function)
2362                  nil)
2363              (error err))))
2364     (when failure
2365       (if (eq 'error (car failure))
2366           (cadr failure)
2367         (prin1-to-string failure)))))
2368
2369 (defun message-send-mail (&optional arg)
2370   (require 'mail-utils)
2371   (let ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2372         (case-fold-search nil)
2373         (news (message-news-p))
2374         failure)
2375     (save-restriction
2376       (message-narrow-to-headers)
2377       ;; Insert some headers.
2378       (let ((message-deletable-headers
2379              (if news nil message-deletable-headers)))
2380         (message-generate-headers message-required-mail-headers))
2381       ;; Let the user do all of the above.
2382       (run-hooks 'message-header-hook))
2383     (if (not (message-check-mail-syntax))
2384         (progn
2385           (message "")
2386           nil)
2387       (unwind-protect
2388           (save-excursion
2389             (set-buffer tembuf)
2390             (erase-buffer)
2391             (insert-buffer message-encoding-buffer)
2392             ;; Remove some headers.
2393             (save-restriction
2394               (message-narrow-to-headers)
2395               ;; Remove some headers.
2396               (message-remove-header message-ignored-mail-headers t))
2397             (goto-char (point-max))
2398             ;; require one newline at the end.
2399             (or (= (preceding-char) ?\n)
2400                 (insert ?\n))
2401             (when (and news
2402                        (or (message-fetch-field "cc")
2403                            (message-fetch-field "to")))
2404               (message-insert-courtesy-copy))
2405             (setq failure (message-maybe-split-and-send-mail)))
2406         (kill-buffer tembuf))
2407       (set-buffer message-edit-buffer)
2408       (if failure
2409           (progn
2410             (message "Couldn't send message via mail: %s" failure)
2411             nil)
2412         (push 'mail message-sent-message-via)))))
2413
2414 (defun message-send-mail-with-sendmail ()
2415   "Send off the prepared buffer with sendmail."
2416   (let ((errbuf (if message-interactive
2417                     (generate-new-buffer " sendmail errors")
2418                   0))
2419         resend-to-addresses delimline)
2420     (let ((case-fold-search t))
2421       (save-restriction
2422         (message-narrow-to-headers)
2423         (setq resend-to-addresses (message-fetch-field "resent-to")))
2424       ;; Change header-delimiter to be what sendmail expects.
2425       (goto-char (point-min))
2426       (re-search-forward
2427        (concat "^" (regexp-quote mail-header-separator) "\n"))
2428       (replace-match "\n")
2429       (backward-char 1)
2430       (setq delimline (point-marker))
2431       (run-hooks 'message-send-mail-hook)
2432       ;; Insert an extra newline if we need it to work around
2433       ;; Sun's bug that swallows newlines.
2434       (goto-char (1+ delimline))
2435       (when (eval message-mailer-swallows-blank-line)
2436         (newline))
2437       (when message-interactive
2438         (save-excursion
2439           (set-buffer errbuf)
2440           (erase-buffer))))
2441     (let ((default-directory "/")
2442           (coding-system-for-write message-send-coding-system))
2443       (apply 'call-process-region
2444              (append (list (point-min) (point-max)
2445                            (if (boundp 'sendmail-program)
2446                                sendmail-program
2447                              "/usr/lib/sendmail")
2448                            nil errbuf nil "-oi")
2449                      ;; Always specify who from,
2450                      ;; since some systems have broken sendmails.
2451                      ;; But some systems are more broken with -f, so
2452                      ;; we'll let users override this.
2453                      (if (null message-sendmail-f-is-evil)
2454                          (list "-f" (user-login-name)))
2455                      ;; These mean "report errors by mail"
2456                      ;; and "deliver in background".
2457                      (if (null message-interactive) '("-oem" "-odb"))
2458                      ;; Get the addresses from the message
2459                      ;; unless this is a resend.
2460                      ;; We must not do that for a resend
2461                      ;; because we would find the original addresses.
2462                      ;; For a resend, include the specific addresses.
2463                      (if resend-to-addresses
2464                          (list resend-to-addresses)
2465                        '("-t")))))
2466     (when message-interactive
2467       (save-excursion
2468         (set-buffer errbuf)
2469         (goto-char (point-min))
2470         (while (re-search-forward "\n\n* *" nil t)
2471           (replace-match "; "))
2472         (if (not (zerop (buffer-size)))
2473             (error "Sending...failed to %s"
2474                    (buffer-substring (point-min) (point-max)))))
2475       (when (bufferp errbuf)
2476         (kill-buffer errbuf)))))
2477
2478 (defun message-send-mail-with-qmail ()
2479   "Pass the prepared message buffer to qmail-inject.
2480 Refer to the documentation for the variable `message-send-mail-function'
2481 to find out how to use this."
2482   ;; replace the header delimiter with a blank line
2483   (goto-char (point-min))
2484   (re-search-forward
2485    (concat "^" (regexp-quote mail-header-separator) "\n"))
2486   (replace-match "\n")
2487   (backward-char 1)
2488   (run-hooks 'message-send-mail-hook)
2489   ;; send the message
2490   (case
2491       (let ((coding-system-for-write message-send-coding-system))
2492         (apply
2493          'call-process-region 1 (point-max) message-qmail-inject-program
2494          nil nil nil
2495          ;; qmail-inject's default behaviour is to look for addresses on the
2496          ;; command line; if there're none, it scans the headers.
2497          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2498          ;;
2499          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2500          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2501          ;; message from stdin.
2502          ;;
2503          ;; qmail also has the advantage of not having been raped by
2504          ;; various vendors, so we don't have to allow for that, either --
2505          ;; compare this with message-send-mail-with-sendmail and weep
2506          ;; for sendmail's lost innocence.
2507          ;;
2508          ;; all this is way cool coz it lets us keep the arguments entirely
2509          ;; free for -inject-arguments -- a big win for the user and for us
2510          ;; since we don't have to play that double-guessing game and the user
2511          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2512          message-qmail-inject-args))
2513     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2514     ;; we have to look at the retval instead
2515     (0 nil)
2516     (1   (error "qmail-inject reported permanent failure"))
2517     (111 (error "qmail-inject reported transient failure"))
2518     ;; should never happen
2519     (t   (error "qmail-inject reported unknown failure"))))
2520
2521 (defun message-send-mail-with-mh ()
2522   "Send the prepared message buffer with mh."
2523   (let ((mh-previous-window-config nil)
2524         (name (mh-new-draft-name)))
2525     (setq buffer-file-name name)
2526     ;; MH wants to generate these headers itself.
2527     (when message-mh-deletable-headers
2528       (let ((headers message-mh-deletable-headers))
2529         (while headers
2530           (goto-char (point-min))
2531           (and (re-search-forward
2532                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2533                (message-delete-line))
2534           (pop headers))))
2535     (run-hooks 'message-send-mail-hook)
2536     ;; Pass it on to mh.
2537     (mh-send-letter)))
2538
2539 (defun message-send-mail-with-smtp ()
2540   "Send off the prepared buffer with SMTP."
2541   (require 'smtp) ; XXX
2542   (let ((case-fold-search t)
2543         recipients)
2544     (save-restriction
2545       (message-narrow-to-headers)
2546       (setq recipients
2547             ;; XXX: Should be replaced by better one.
2548             (smtp-deduce-address-list (current-buffer)
2549                                       (point-min) (point-max)))
2550       ;; Remove BCC lines.
2551       (message-remove-header "bcc"))
2552     ;; replace the header delimiter with a blank line.
2553     (goto-char (point-min))
2554     (re-search-forward
2555      (concat "^" (regexp-quote mail-header-separator) "\n"))
2556     (replace-match "\n")
2557     (backward-char 1)
2558     (run-hooks 'message-send-mail-hook)
2559     (if recipients
2560         (let ((result (smtp-via-smtp user-mail-address
2561                                      recipients
2562                                      (current-buffer))))
2563           (unless (eq result t)
2564             (error "Sending failed; " result)))
2565       (error "Sending failed; no recipients"))))
2566
2567 (defsubst message-maybe-split-and-send-news (method)
2568   "Split a message if necessary, and send it via news.
2569 Returns nil if sending succeeded, returns t if sending failed.
2570 This sub function is for exclusive use of `message-send-news'."
2571   (let ((mime-edit-split-ignored-field-regexp
2572          mime-edit-split-ignored-field-regexp)
2573         (case-fold-search t))
2574     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
2575       (setq mime-edit-split-ignored-field-regexp
2576             (concat (substring mime-edit-split-ignored-field-regexp
2577                                0 (match-beginning 0))
2578                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
2579                     "_so_don't_rape_it!"
2580                     (substring mime-edit-split-ignored-field-regexp
2581                                (match-end 0)))))
2582     (or
2583      (catch 'message-sending-news-failure
2584        (mime-edit-maybe-split-and-send
2585         (function
2586          (lambda ()
2587            (interactive)
2588            (save-restriction
2589              (std11-narrow-to-header mail-header-separator)
2590              (goto-char (point-min))
2591              (when (re-search-forward "^Message-ID:" nil t)
2592                (delete-region (match-end 0) (std11-field-end))
2593                (insert " " (message-make-message-id))))
2594            (unless (funcall message-send-news-function method)
2595              (throw 'message-sending-news-failure t)))))
2596        nil)
2597      (not (funcall message-send-news-function method)))))
2598
2599 (defun message-send-news (&optional arg)
2600   (let ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2601         (case-fold-search nil)
2602         (method (if (message-functionp message-post-method)
2603                     (funcall message-post-method arg)
2604                   message-post-method))
2605         (message-syntax-checks
2606          (if arg
2607              (cons '(existing-newsgroups . disabled)
2608                    message-syntax-checks)
2609            message-syntax-checks))
2610         result)
2611     (save-restriction
2612       (message-narrow-to-headers)
2613       ;; Insert some headers.
2614       (message-generate-headers message-required-news-headers)
2615       ;; Let the user do all of the above.
2616       (run-hooks 'message-header-hook))
2617     (message-cleanup-headers)
2618     (if (not (message-check-news-syntax))
2619         nil
2620       (unwind-protect
2621           (save-excursion
2622             (set-buffer tembuf)
2623             (buffer-disable-undo)
2624             (erase-buffer)
2625             (insert-buffer message-encoding-buffer)
2626             ;; Remove some headers.
2627             (save-restriction
2628               (message-narrow-to-headers)
2629               ;; Remove some headers.
2630               (message-remove-header message-ignored-news-headers t))
2631             (goto-char (point-max))
2632             ;; require one newline at the end.
2633             (or (= (preceding-char) ?\n)
2634                 (insert ?\n))
2635             (setq result (message-maybe-split-and-send-news method)))
2636         (kill-buffer tembuf))
2637       (set-buffer message-edit-buffer)
2638       (if result
2639           (progn
2640             (message "Couldn't send message via news: %s"
2641                      (nnheader-get-report (car method)))
2642             nil)
2643         (push 'news message-sent-message-via)))))
2644
2645 ;; 1997-09-29 by MORIOKA Tomohiko
2646 (defun message-send-news-with-gnus (method)
2647   (let ((case-fold-search t))
2648     ;; Remove the delimiter.
2649     (goto-char (point-min))
2650     (re-search-forward
2651      (concat "^" (regexp-quote mail-header-separator) "\n"))
2652     (replace-match "\n")
2653     (backward-char 1)
2654     (run-hooks 'message-send-news-hook)
2655     ;;(require (car method))
2656     ;;(funcall (intern (format "%s-open-server" (car method)))
2657     ;;(cadr method) (cddr method))
2658     ;;(setq result
2659     ;;    (funcall (intern (format "%s-request-post" (car method)))
2660     ;;             (cadr method)))
2661     (gnus-open-server method)
2662     (gnus-request-post method)
2663     ))
2664
2665 ;;;
2666 ;;; Header generation & syntax checking.
2667 ;;;
2668
2669 (defun message-check-element (type)
2670   "Returns non-nil if this type is not to be checked."
2671   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2672       t
2673     (let ((able (assq type message-syntax-checks)))
2674       (and (consp able)
2675            (eq (cdr able) 'disabled)))))
2676
2677 (defun message-check-news-syntax ()
2678   "Check the syntax of the message."
2679   (save-excursion
2680     (save-restriction
2681       (widen)
2682       (and
2683        ;; We narrow to the headers and check them first.
2684        (save-excursion
2685          (save-restriction
2686            (message-narrow-to-headers)
2687            (message-check-news-header-syntax)))
2688        ;; Check the body.
2689        (save-excursion
2690          (set-buffer message-edit-buffer)
2691          (message-check-news-body-syntax))))))
2692
2693 (defun message-check-news-header-syntax ()
2694   (and
2695    ;; Check the Subject header.
2696    (message-check 'subject
2697      (let* ((case-fold-search t)
2698             (subject (message-fetch-field "subject")))
2699        (or
2700         (and subject
2701              (not (string-match "\\`[ \t]*\\'" subject)))
2702         (ignore
2703          (message
2704           "The subject field is empty or missing.  Posting is denied.")))))
2705    ;; Check for commands in Subject.
2706    (message-check 'subject-cmsg
2707      (if (string-match "^cmsg " (message-fetch-field "subject"))
2708          (y-or-n-p
2709           "The control code \"cmsg\" is in the subject.  Really post? ")
2710        t))
2711    ;; Check for multiple identical headers.
2712    (message-check 'multiple-headers
2713      (let (found)
2714        (while (and (not found)
2715                    (re-search-forward "^[^ \t:]+: " nil t))
2716          (save-excursion
2717            (or (re-search-forward
2718                 (concat "^"
2719                         (regexp-quote
2720                          (setq found
2721                                (buffer-substring
2722                                 (match-beginning 0) (- (match-end 0) 2))))
2723                         ":")
2724                 nil t)
2725                (setq found nil))))
2726        (if found
2727            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2728          t)))
2729    ;; Check for Version and Sendsys.
2730    (message-check 'sendsys
2731      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2732          (y-or-n-p
2733           (format "The article contains a %s command.  Really post? "
2734                   (buffer-substring (match-beginning 0)
2735                                     (1- (match-end 0)))))
2736        t))
2737    ;; See whether we can shorten Followup-To.
2738    (message-check 'shorten-followup-to
2739      (let ((newsgroups (message-fetch-field "newsgroups"))
2740            (followup-to (message-fetch-field "followup-to"))
2741            to)
2742        (when (and newsgroups
2743                   (string-match "," newsgroups)
2744                   (not followup-to)
2745                   (not
2746                    (zerop
2747                     (length
2748                      (setq to (completing-read
2749                                "Followups to: (default all groups) "
2750                                (mapcar (lambda (g) (list g))
2751                                        (cons "poster"
2752                                              (message-tokenize-header
2753                                               newsgroups)))))))))
2754          (goto-char (point-min))
2755          (insert "Followup-To: " to "\n"))
2756        t))
2757    ;; Check "Shoot me".
2758    (message-check 'shoot
2759      (if (re-search-forward
2760           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2761          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2762        t))
2763    ;; Check for Approved.
2764    (message-check 'approved
2765      (if (re-search-forward "^Approved:" nil t)
2766          (y-or-n-p "The article contains an Approved header.  Really post? ")
2767        t))
2768    ;; Check the Message-ID header.
2769    (message-check 'message-id
2770      (let* ((case-fold-search t)
2771             (message-id (message-fetch-field "message-id" t)))
2772        (or (not message-id)
2773            ;; Is there an @ in the ID?
2774            (and (string-match "@" message-id)
2775                 ;; Is there a dot in the ID?
2776                 (string-match "@[^.]*\\." message-id)
2777                 ;; Does the ID end with a dot?
2778                 (not (string-match "\\.>" message-id)))
2779            (y-or-n-p
2780             (format "The Message-ID looks strange: \"%s\".  Really post? "
2781                     message-id)))))
2782    ;; Check the Newsgroups & Followup-To headers.
2783    (message-check 'existing-newsgroups
2784      (let* ((case-fold-search t)
2785             (newsgroups (message-fetch-field "newsgroups"))
2786             (followup-to (message-fetch-field "followup-to"))
2787             (groups (message-tokenize-header
2788                      (if followup-to
2789                          (concat newsgroups "," followup-to)
2790                        newsgroups)))
2791             (hashtb (and (boundp 'gnus-active-hashtb)
2792                          gnus-active-hashtb))
2793             errors)
2794        (if (or (not hashtb)
2795                (not (boundp 'gnus-read-active-file))
2796                (not gnus-read-active-file)
2797                (eq gnus-read-active-file 'some))
2798            t
2799          (while groups
2800            (when (and (not (boundp (intern (car groups) hashtb)))
2801                       (not (equal (car groups) "poster")))
2802              (push (car groups) errors))
2803            (pop groups))
2804          (if (not errors)
2805              t
2806            (y-or-n-p
2807             (format
2808              "Really post to %s unknown group%s: %s "
2809              (if (= (length errors) 1) "this" "these")
2810              (if (= (length errors) 1) "" "s")
2811              (mapconcat 'identity errors ", ")))))))
2812    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2813    (message-check 'valid-newsgroups
2814      (let ((case-fold-search t)
2815            (headers '("Newsgroups" "Followup-To"))
2816            header error)
2817        (while (and headers (not error))
2818          (when (setq header (mail-fetch-field (car headers)))
2819            (if (or
2820                 (not
2821                  (string-match
2822                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2823                   header))
2824                 (memq
2825                  nil (mapcar
2826                       (lambda (g)
2827                         (not (string-match "\\.\\'\\|\\.\\." g)))
2828                       (message-tokenize-header header ","))))
2829                (setq error t)))
2830          (unless error
2831            (pop headers)))
2832        (if (not error)
2833            t
2834          (y-or-n-p
2835           (format "The %s header looks odd: \"%s\".  Really post? "
2836                   (car headers) header)))))
2837    (message-check 'repeated-newsgroups
2838      (let ((case-fold-search t)
2839            (headers '("Newsgroups" "Followup-To"))
2840            header error groups group)
2841        (while (and headers
2842                    (not error))
2843          (when (setq header (mail-fetch-field (pop headers)))
2844            (setq groups (message-tokenize-header header ","))
2845            (while (setq group (pop groups))
2846              (when (member group groups)
2847                (setq error group
2848                      groups nil)))))
2849        (if (not error)
2850            t
2851          (y-or-n-p
2852           (format "Group %s is repeated in headers.  Really post? " error)))))
2853    ;; Check the From header.
2854    (message-check 'from
2855      (let* ((case-fold-search t)
2856             (from (message-fetch-field "from"))
2857             (ad (nth 1 (std11-extract-address-components from))))
2858        (cond
2859         ((not from)
2860          (message "There is no From line.  Posting is denied.")
2861          nil)
2862         ((or (not (string-match "@[^\\.]*\\." ad)) ;larsi@ifi
2863              (string-match "\\.\\." ad) ;larsi@ifi..uio
2864              (string-match "@\\." ad)   ;larsi@.ifi.uio
2865              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2866              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2867              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2868          (message
2869           "Denied posting -- the From looks strange: \"%s\"." from)
2870          nil)
2871         (t t))))))
2872
2873 (defun message-check-news-body-syntax ()
2874   (and
2875    ;; Check for long lines.
2876    (message-check 'long-lines
2877      (goto-char (point-min))
2878      (re-search-forward
2879       (concat "^" (regexp-quote mail-header-separator) "$"))
2880      (while (and
2881              (progn
2882                (end-of-line)
2883                (< (current-column) 80))
2884              (zerop (forward-line 1))))
2885      (or (bolp)
2886          (eobp)
2887          (y-or-n-p
2888           "You have lines longer than 79 characters.  Really post? ")))
2889    ;; Check whether the article is empty.
2890    (message-check 'empty
2891      (goto-char (point-min))
2892      (re-search-forward
2893       (concat "^" (regexp-quote mail-header-separator) "$"))
2894      (forward-line 1)
2895      (let ((b (point)))
2896        (goto-char (point-max))
2897        (re-search-backward message-signature-separator nil t)
2898        (beginning-of-line)
2899        (or (re-search-backward "[^ \n\t]" b t)
2900            (y-or-n-p "Empty article.  Really post? "))))
2901    ;; Check for control characters.
2902    (message-check 'control-chars
2903      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
2904          (y-or-n-p
2905           "The article contains control characters.  Really post? ")
2906        t))
2907    ;; Check 8bit characters.
2908    (message-check '8bit
2909      (message-check-8bit))
2910    ;; Check excessive size.
2911    (message-check 'size
2912      (if (> (buffer-size) 60000)
2913          (y-or-n-p
2914           (format "The article is %d octets long.  Really post? "
2915                   (buffer-size)))
2916        t))
2917    ;; Check whether any new text has been added.
2918    (message-check 'new-text
2919      (or
2920       (not message-checksum)
2921       (not (eq (message-checksum) message-checksum))
2922       (y-or-n-p
2923        "It looks like no new text has been added.  Really post? ")))
2924    ;; Check the length of the signature.
2925    (message-check 'signature
2926      (goto-char (point-max))
2927      (if (or (not (re-search-backward message-signature-separator nil t))
2928              (search-forward message-forward-end-separator nil t))
2929          t
2930        (if (> (count-lines (point) (point-max)) 5)
2931            (y-or-n-p
2932             (format
2933              "Your .sig is %d lines; it should be max 4.  Really post? "
2934              (1- (count-lines (point) (point-max)))))
2935          t)))))
2936
2937 (defun message-check-mail-syntax ()
2938   "Check the syntax of the message."
2939   (save-excursion
2940     (save-restriction
2941       (widen)
2942       (and
2943        ;; We narrow to the headers and check them first.
2944        (save-excursion
2945          (save-restriction
2946            (message-narrow-to-headers)
2947            (message-check-mail-header-syntax)))
2948        ;; Check the body.
2949        (save-excursion
2950          (set-buffer message-edit-buffer)
2951          (message-check-mail-body-syntax))))))
2952
2953 (defun message-check-mail-header-syntax ()
2954   t)
2955
2956 (defun message-check-mail-body-syntax ()
2957   (and
2958    ;; Check 8bit characters.
2959    (message-check '8bit
2960      (message-check-8bit)
2961      )))
2962
2963 (defun message-check-8bit ()
2964   "Check the article contains 8bit characters."
2965   (save-excursion
2966     (set-buffer message-encoding-buffer)
2967     (message-narrow-to-headers)
2968     (let* ((case-fold-search t)
2969            (field-value (message-fetch-field "content-transfer-encoding")))
2970       (if (and field-value
2971                (member (downcase field-value) message-8bit-encoding-list))
2972           t
2973         (widen)
2974         (set-buffer (get-buffer-create " message syntax"))
2975         (erase-buffer)
2976         (goto-char (point-min))
2977         (set-buffer-multibyte nil)
2978         (insert-buffer message-encoding-buffer)
2979         (goto-char (point-min))
2980         (if (re-search-forward "[^\x00-\x7f]" nil t)
2981             (y-or-n-p
2982              "The article contains 8bit characters.  Really post? ")
2983           t)))))
2984
2985 (defun message-checksum ()
2986   "Return a \"checksum\" for the current buffer."
2987   (let ((sum 0))
2988     (save-excursion
2989       (goto-char (point-min))
2990       (re-search-forward
2991        (concat "^" (regexp-quote mail-header-separator) "$"))
2992       (while (not (eobp))
2993         (when (not (looking-at "[ \t\n]"))
2994           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
2995                             (char-after))))
2996         (forward-char 1)))
2997     sum))
2998
2999 (defun message-do-fcc ()
3000   "Process Fcc headers in the current buffer."
3001   (let ((case-fold-search t)
3002         (coding-system-for-write 'raw-text)
3003         list file)
3004     (save-excursion
3005       (set-buffer (get-buffer-create " *message temp*"))
3006       (erase-buffer)
3007       (insert-buffer-substring message-encoding-buffer)
3008       (save-restriction
3009         (message-narrow-to-headers)
3010         (while (setq file (message-fetch-field "fcc"))
3011           (push file list)
3012           (message-remove-header "fcc" nil t)))
3013       (goto-char (point-min))
3014       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
3015       (replace-match "" t t)
3016       ;; Process FCC operations.
3017       (while list
3018         (setq file (pop list))
3019         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
3020             ;; Pipe the article to the program in question.
3021             (call-process-region (point-min) (point-max) shell-file-name
3022                                  nil nil nil shell-command-switch
3023                                  (match-string 1 file))
3024           ;; Save the article.
3025           (setq file (expand-file-name file))
3026           (unless (file-exists-p (file-name-directory file))
3027             (make-directory (file-name-directory file) t))
3028           (if (and message-fcc-handler-function
3029                    (not (eq message-fcc-handler-function 'rmail-output)))
3030               (funcall message-fcc-handler-function file)
3031             (if (and (file-readable-p file) (mail-file-babyl-p file))
3032                 (rmail-output file 1 nil t)
3033               (let ((mail-use-rfc822 t))
3034                 (rmail-output file 1 t t))))))
3035       (kill-buffer (current-buffer)))))
3036
3037 (defun message-output (filename)
3038   "Append this article to Unix/babyl mail file.."
3039   (if (and (file-readable-p filename)
3040            (mail-file-babyl-p filename))
3041       (rmail-output-to-rmail-file filename t)
3042     (gnus-output-to-mail filename t)))
3043
3044 (defun message-cleanup-headers ()
3045   "Do various automatic cleanups of the headers."
3046   ;; Remove empty lines in the header.
3047   (save-restriction
3048     (message-narrow-to-headers)
3049     ;; Remove blank lines.
3050     (while (re-search-forward "^[ \t]*\n" nil t)
3051       (replace-match "" t t))
3052
3053     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
3054     ;; spaces to comma and eliminate spaces around commas.  Eliminate
3055     ;; embedded line breaks.
3056     (goto-char (point-min))
3057     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
3058       (save-restriction
3059         (narrow-to-region
3060          (point)
3061          (if (re-search-forward "^[^ \t]" nil t)
3062              (match-beginning 0)
3063            (forward-line 1)
3064            (point)))
3065         (goto-char (point-min))
3066         (while (re-search-forward "\n[ \t]+" nil t)
3067           (replace-match " " t t))      ;No line breaks (too confusing)
3068         (goto-char (point-min))
3069         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
3070           (replace-match "," t t))
3071         (goto-char (point-min))
3072         ;; Remove trailing commas.
3073         (when (re-search-forward ",+$" nil t)
3074           (replace-match "" t t))))))
3075
3076 (defun message-make-date (&optional now)
3077   "Make a valid data header.
3078 If NOW, use that time instead."
3079   (let* ((now (or now (current-time)))
3080          (zone (nth 8 (decode-time now)))
3081          (sign "+"))
3082     (when (< zone 0)
3083       (setq sign "-")
3084       (setq zone (- zone)))
3085     (concat
3086      (format-time-string "%d" now)
3087      ;; The month name of the %b spec is locale-specific.  Pfff.
3088      (format " %s "
3089              (capitalize (car (rassoc (nth 4 (decode-time now))
3090                                       parse-time-months))))
3091      (format-time-string "%Y %H:%M:%S " now)
3092      ;; We do all of this because XEmacs doesn't have the %z spec.
3093      (format "%s%02d%02d" sign (/ zone 3600) (% zone 3600)))))
3094
3095 (defun message-make-followup-subject (subject)
3096   "Make a followup Subject."
3097   (cond
3098    ((and (eq message-use-subject-re 'guess)
3099          (string-match message-subject-encoded-re-regexp subject))
3100     subject)
3101    (message-use-subject-re
3102     (concat "Re: " (message-strip-subject-re subject)))
3103    (t subject)))
3104
3105 (defun message-make-message-id ()
3106   "Make a unique Message-ID."
3107   (concat "<" (message-unique-id)
3108           (let ((psubject (save-excursion (message-fetch-field "subject")))
3109                 (psupersedes
3110                  (save-excursion (message-fetch-field "supersedes"))))
3111             (if (or
3112                  (and message-reply-headers
3113                       (mail-header-references message-reply-headers)
3114                       (mail-header-subject message-reply-headers)
3115                       psubject
3116                       (mail-header-subject message-reply-headers)
3117                       (not (string=
3118                             (message-strip-subject-re
3119                              (mail-header-subject message-reply-headers))
3120                             (message-strip-subject-re psubject))))
3121                  (and psupersedes
3122                       (string-match "_-_@" psupersedes)))
3123                 "_-_" ""))
3124           "@" (message-make-fqdn) ">"))
3125
3126 (defvar message-unique-id-char nil)
3127
3128 ;; If you ever change this function, make sure the new version
3129 ;; cannot generate IDs that the old version could.
3130 ;; You might for example insert a "." somewhere (not next to another dot
3131 ;; or string boundary), or modify the "fsf" string.
3132 (defun message-unique-id ()
3133   ;; Don't use microseconds from (current-time), they may be unsupported.
3134   ;; Instead we use this randomly inited counter.
3135   (setq message-unique-id-char
3136         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
3137            ;; (current-time) returns 16-bit ints,
3138            ;; and 2^16*25 just fits into 4 digits i base 36.
3139            (* 25 25)))
3140   (let ((tm (current-time)))
3141     (concat
3142      (if (memq system-type '(ms-dos emx vax-vms))
3143          (let ((user (downcase (user-login-name))))
3144            (while (string-match "[^a-z0-9_]" user)
3145              (aset user (match-beginning 0) ?_))
3146            user)
3147        (message-number-base36 (user-uid) -1))
3148      (message-number-base36 (+ (car   tm)
3149                                (lsh (% message-unique-id-char 25) 16)) 4)
3150      (message-number-base36 (+ (nth 1 tm)
3151                                (lsh (/ message-unique-id-char 25) 16)) 4)
3152      ;; Append the newsreader name, because while the generated
3153      ;; ID is unique to this newsreader, other newsreaders might
3154      ;; otherwise generate the same ID via another algorithm.
3155      ".fsf")))
3156
3157 (defun message-number-base36 (num len)
3158   (if (if (< len 0)
3159           (<= num 0)
3160         (= len 0))
3161       ""
3162     (concat (message-number-base36 (/ num 36) (1- len))
3163             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
3164                                   (% num 36))))))
3165
3166 (defun message-make-organization ()
3167   "Make an Organization header."
3168   (let* ((organization
3169           (when message-user-organization
3170                 (if (message-functionp message-user-organization)
3171                     (funcall message-user-organization)
3172                   message-user-organization))))
3173     (save-excursion
3174       (message-set-work-buffer)
3175       (cond ((stringp organization)
3176              (insert organization))
3177             ((and (eq t organization)
3178                   message-user-organization-file
3179                   (file-exists-p message-user-organization-file))
3180              (insert-file-contents message-user-organization-file)))
3181       (goto-char (point-min))
3182       (while (re-search-forward "[\t\n]+" nil t)
3183         (replace-match "" t t))
3184       (unless (zerop (buffer-size))
3185         (buffer-string)))))
3186
3187 (defun message-make-lines ()
3188   "Count the number of lines and return numeric string."
3189   (save-excursion
3190     (save-restriction
3191       (widen)
3192       (goto-char (point-min))
3193       (re-search-forward
3194        (concat "^" (regexp-quote mail-header-separator) "$"))
3195       (forward-line 1)
3196       (int-to-string (count-lines (point) (point-max))))))
3197
3198 (defun message-make-in-reply-to ()
3199   "Return the In-Reply-To header for this message."
3200   (when message-reply-headers
3201     (let ((mid (mail-header-message-id message-reply-headers))
3202           (from (mail-header-from message-reply-headers))
3203           (date (mail-header-date message-reply-headers)))
3204       (when mid
3205         (concat mid
3206                 (when from
3207                   (let ((pair (std11-extract-address-components from)))
3208                     (concat "\n ("
3209                             (or (car pair) (cadr pair))
3210                             "'s message of \""
3211                             (if (or (not date) (string= date ""))
3212                                 "(unknown date)" date)
3213                             "\")"))))))))
3214
3215 (defun message-make-distribution ()
3216   "Make a Distribution header."
3217   (let ((orig-distribution (message-fetch-reply-field "distribution")))
3218     (cond ((message-functionp message-distribution-function)
3219            (funcall message-distribution-function))
3220           (t orig-distribution))))
3221
3222 (defun message-make-expires ()
3223   "Return an Expires header based on `message-expires'."
3224   (let ((current (current-time))
3225         (future (* 1.0 message-expires 60 60 24)))
3226     ;; Add the future to current.
3227     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
3228     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
3229     (message-make-date current)))
3230
3231 (defun message-make-path ()
3232   "Return uucp path."
3233   (let ((login-name (user-login-name)))
3234     (cond ((null message-user-path)
3235            (concat (system-name) "!" login-name))
3236           ((stringp message-user-path)
3237            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
3238            (concat message-user-path "!" login-name))
3239           (t login-name))))
3240
3241 (defun message-make-from ()
3242   "Make a From header."
3243   (let* ((style message-from-style)
3244          (login (message-make-address))
3245          (fullname
3246           (or (and (boundp 'user-full-name)
3247                    user-full-name)
3248               (user-full-name))))
3249     (when (string= fullname "&")
3250       (setq fullname (user-login-name)))
3251     (save-excursion
3252       (message-set-work-buffer)
3253       (cond
3254        ((or (null style)
3255             (equal fullname ""))
3256         (insert login))
3257        ((or (eq style 'angles)
3258             (and (not (eq style 'parens))
3259                  ;; Use angles if no quoting is needed, or if parens would
3260                  ;; need quoting too.
3261                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
3262                      (let ((tmp (concat fullname nil)))
3263                        (while (string-match "([^()]*)" tmp)
3264                          (aset tmp (match-beginning 0) ?-)
3265                          (aset tmp (1- (match-end 0)) ?-))
3266                        (string-match "[\\()]" tmp)))))
3267         (insert fullname)
3268         (goto-char (point-min))
3269         ;; Look for a character that cannot appear unquoted
3270         ;; according to RFC 822.
3271         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
3272           ;; Quote fullname, escaping specials.
3273           (goto-char (point-min))
3274           (insert "\"")
3275           (while (re-search-forward "[\"\\]" nil 1)
3276             (replace-match "\\\\\\&" t))
3277           (insert "\""))
3278         (insert " <" login ">"))
3279        (t                               ; 'parens or default
3280         (insert login " (")
3281         (let ((fullname-start (point)))
3282           (insert fullname)
3283           (goto-char fullname-start)
3284           ;; RFC 822 says \ and nonmatching parentheses
3285           ;; must be escaped in comments.
3286           ;; Escape every instance of ()\ ...
3287           (while (re-search-forward "[()\\]" nil 1)
3288             (replace-match "\\\\\\&" t))
3289           ;; ... then undo escaping of matching parentheses,
3290           ;; including matching nested parentheses.
3291           (goto-char fullname-start)
3292           (while (re-search-forward
3293                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3294                   nil 1)
3295             (replace-match "\\1(\\3)" t)
3296             (goto-char fullname-start)))
3297         (insert ")")))
3298       (buffer-string))))
3299
3300 (defun message-make-sender ()
3301   "Return the \"real\" user address.
3302 This function tries to ignore all user modifications, and
3303 give as trustworthy answer as possible."
3304   (concat (user-login-name) "@" (system-name)))
3305
3306 (defun message-make-address ()
3307   "Make the address of the user."
3308   (or (message-user-mail-address)
3309       (concat (user-login-name) "@" (message-make-domain))))
3310
3311 (defun message-user-mail-address ()
3312   "Return the pertinent part of `user-mail-address'."
3313   (when user-mail-address
3314     (if (string-match " " user-mail-address)
3315         (nth 1 (std11-extract-address-components user-mail-address))
3316       user-mail-address)))
3317
3318 (defun message-make-fqdn ()
3319   "Return user's fully qualified domain name."
3320   (let ((system-name (system-name))
3321         (user-mail (message-user-mail-address)))
3322     (cond
3323      ((string-match "[^.]\\.[^.]" system-name)
3324       ;; `system-name' returned the right result.
3325       system-name)
3326      ;; Try `mail-host-address'.
3327      ((and (boundp 'mail-host-address)
3328            (stringp mail-host-address)
3329            (string-match "\\." mail-host-address))
3330       mail-host-address)
3331      ;; We try `user-mail-address' as a backup.
3332      ((and user-mail
3333            (string-match "\\." user-mail)
3334            (string-match "@\\(.*\\)\\'" user-mail))
3335       (match-string 1 user-mail))
3336      ;; Default to this bogus thing.
3337      (t
3338       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
3339
3340 (defun message-make-host-name ()
3341   "Return the name of the host."
3342   (let ((fqdn (message-make-fqdn)))
3343     (string-match "^[^.]+\\." fqdn)
3344     (substring fqdn 0 (1- (match-end 0)))))
3345
3346 (defun message-make-domain ()
3347   "Return the domain name."
3348   (or mail-host-address
3349       (message-make-fqdn)))
3350
3351 ;; Dummy to avoid byte-compile warning.
3352 (defvar mule-version)
3353 (defvar emacs-beta-version)
3354 (defvar xemacs-codename)
3355 (defvar gnus-inviolable-extended-version)
3356
3357 (defun message-make-user-agent ()
3358   "Return user-agent info if the value `message-user-agent' is non-nil. If the
3359 \"User-Agent\" field has already exist, it's value will be added in the return
3360 string."
3361   (when message-user-agent
3362     (save-excursion
3363       (goto-char (point-min))
3364       (let ((case-fold-search t)
3365             user-agent start p end)
3366         (if (re-search-forward "^User-Agent:[\t ]*" nil t)
3367             (progn
3368               (setq start (match-beginning 0)
3369                     p (match-end 0)
3370                     end (std11-field-end)
3371                     user-agent (buffer-substring-no-properties p end))
3372               (delete-region start (1+ end))
3373               (concat message-user-agent " " user-agent))
3374           message-user-agent)))))
3375
3376 (defun message-generate-headers (headers)
3377   "Prepare article HEADERS.
3378 Headers already prepared in the buffer are not modified."
3379   (save-restriction
3380     (message-narrow-to-headers)
3381     (let* ((Date (message-make-date))
3382            (Message-ID (message-make-message-id))
3383            (Organization (message-make-organization))
3384            (From (message-make-from))
3385            (Path (message-make-path))
3386            (Subject nil)
3387            (Newsgroups nil)
3388            (In-Reply-To (message-make-in-reply-to))
3389            (To nil)
3390            (Distribution (message-make-distribution))
3391            (Lines (message-make-lines))
3392            (User-Agent (message-make-user-agent))
3393            (Expires (message-make-expires))
3394            (case-fold-search t)
3395            header value elem)
3396       ;; First we remove any old generated headers.
3397       (let ((headers message-deletable-headers))
3398         (unless (buffer-modified-p)
3399           (setq headers (delq 'Message-ID (copy-sequence headers))))
3400         (while headers
3401           (goto-char (point-min))
3402           (and (re-search-forward
3403                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3404                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3405                (message-delete-line))
3406           (pop headers)))
3407       ;; Go through all the required headers and see if they are in the
3408       ;; articles already.  If they are not, or are empty, they are
3409       ;; inserted automatically - except for Subject, Newsgroups and
3410       ;; Distribution.
3411       (while headers
3412         (goto-char (point-min))
3413         (setq elem (pop headers))
3414         (if (consp elem)
3415             (if (eq (car elem) 'optional)
3416                 (setq header (cdr elem))
3417               (setq header (car elem)))
3418           (setq header elem))
3419         (when (or (not (re-search-forward
3420                         (concat "^"
3421                                 (regexp-quote
3422                                  (downcase
3423                                   (if (stringp header)
3424                                       header
3425                                     (symbol-name header))))
3426                                 ":")
3427                         nil t))
3428                   (progn
3429                     ;; The header was found.  We insert a space after the
3430                     ;; colon, if there is none.
3431                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
3432                     ;; Find out whether the header is empty...
3433                     (looking-at "[ \t]*$")))
3434           ;; So we find out what value we should insert.
3435           (setq value
3436                 (cond
3437                  ((and (consp elem) (eq (car elem) 'optional))
3438                   ;; This is an optional header.  If the cdr of this
3439                   ;; is something that is nil, then we do not insert
3440                   ;; this header.
3441                   (setq header (cdr elem))
3442                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3443                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3444                  ((consp elem)
3445                   ;; The element is a cons.  Either the cdr is a
3446                   ;; string to be inserted verbatim, or it is a
3447                   ;; function, and we insert the value returned from
3448                   ;; this function.
3449                   (or (and (stringp (cdr elem)) (cdr elem))
3450                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3451                  ((and (boundp header) (symbol-value header))
3452                   ;; The element is a symbol.  We insert the value
3453                   ;; of this symbol, if any.
3454                   (symbol-value header))
3455                  (t
3456                   ;; We couldn't generate a value for this header,
3457                   ;; so we just ask the user.
3458                   (read-from-minibuffer
3459                    (format "Empty header for %s; enter value: " header)))))
3460           ;; Finally insert the header.
3461           (when (and value
3462                      (not (equal value "")))
3463             (save-excursion
3464               (if (bolp)
3465                   (progn
3466                     ;; This header didn't exist, so we insert it.
3467                     (goto-char (point-max))
3468                     (insert (if (stringp header) header (symbol-name header))
3469                             ": " value "\n")
3470                     (forward-line -1))
3471                 ;; The value of this header was empty, so we clear
3472                 ;; totally and insert the new value.
3473                 (delete-region (point) (gnus-point-at-eol))
3474                 (insert value))
3475               ;; Add the deletable property to the headers that require it.
3476               (and (memq header message-deletable-headers)
3477                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3478                    (add-text-properties
3479                     (point) (match-end 0)
3480                     '(message-deletable t face italic) (current-buffer)))))))
3481       ;; Insert new Sender if the From is strange.
3482       (let ((from (message-fetch-field "from"))
3483             (sender (message-fetch-field "sender"))
3484             (secure-sender (message-make-sender)))
3485         (when (and from
3486                    (not (message-check-element 'sender))
3487                    (not (string=
3488                          (downcase
3489                           (cadr (std11-extract-address-components from)))
3490                          (downcase secure-sender)))
3491                    (or (null sender)
3492                        (not
3493                         (string=
3494                          (downcase
3495                           (cadr (std11-extract-address-components sender)))
3496                          (downcase secure-sender)))))
3497           (goto-char (point-min))
3498           ;; Rename any old Sender headers to Original-Sender.
3499           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3500             (beginning-of-line)
3501             (insert "Original-")
3502             (beginning-of-line))
3503           (when (or (message-news-p)
3504                     (string-match "@.+\\.." secure-sender))
3505             (insert "Sender: " secure-sender "\n")))))))
3506
3507 (defun message-insert-courtesy-copy ()
3508   "Insert a courtesy message in mail copies of combined messages."
3509   (let (newsgroups)
3510     (save-excursion
3511       (save-restriction
3512         (message-narrow-to-headers)
3513         (when (setq newsgroups (message-fetch-field "newsgroups"))
3514           (goto-char (point-max))
3515           (insert "Posted-To: " newsgroups "\n")))
3516       (forward-line 1)
3517       (when message-courtesy-message
3518         (cond
3519          ((string-match "%s" message-courtesy-message)
3520           (insert (format message-courtesy-message newsgroups)))
3521          (t
3522           (insert message-courtesy-message)))))))
3523
3524 ;;;
3525 ;;; Setting up a message buffer
3526 ;;;
3527
3528 (defun message-fill-address (header value)
3529   (save-restriction
3530     (narrow-to-region (point) (point))
3531     (insert (capitalize (symbol-name header))
3532             ": "
3533             (if (consp value) (car value) value)
3534             "\n")
3535     (narrow-to-region (point-min) (1- (point-max)))
3536     (let (quoted last)
3537       (goto-char (point-min))
3538       (while (not (eobp))
3539         (skip-chars-forward "^,\"" (point-max))
3540         (if (or (eq (char-after) ?,)
3541                 (eobp))
3542             (when (not quoted)
3543               (if (and (> (current-column) 78)
3544                        last)
3545                   (save-excursion
3546                     (goto-char last)
3547                     (looking-at "[ \t]*")
3548                     (replace-match "\n " t t)))
3549               (setq last (1+ (point))))
3550           (setq quoted (not quoted)))
3551         (unless (eobp)
3552           (forward-char 1))))
3553     (goto-char (point-max))
3554     (widen)
3555     (forward-line 1)))
3556
3557 (defun message-fill-references (header value)
3558   (insert (capitalize (symbol-name header))
3559           ": "
3560           (std11-fill-msg-id-list-string
3561           (if (consp value) (car value) value))
3562           "\n"))
3563
3564 (defun message-fill-header (header value)
3565   (let ((begin (point))
3566         (fill-column 78)
3567         (fill-prefix " "))
3568     (insert (capitalize (symbol-name header))
3569             ": "
3570             (if (consp value) (car value) value)
3571             "\n")
3572     (save-restriction
3573       (narrow-to-region begin (point))
3574       (fill-region-as-paragraph begin (point))
3575       ;; Tapdance around looong Message-IDs.
3576       (forward-line -1)
3577       (when (looking-at "[ \t]*$")
3578         (message-delete-line))
3579       (goto-char begin)
3580       (re-search-forward ":" nil t)
3581       (when (looking-at "\n[ \t]+")
3582         (replace-match " " t t))
3583       (goto-char (point-max)))))
3584
3585 (defun message-shorten-references (header references)
3586   "Limit REFERENCES to be shorter than 988 characters."
3587   (let ((max 988)
3588         (cut 4)
3589         refs)
3590     (with-temp-buffer
3591       (insert references)
3592       (goto-char (point-min))
3593       (while (re-search-forward "<[^>]+>" nil t)
3594         (push (match-string 0) refs))
3595       (setq refs (nreverse refs))
3596       (while (> (length (mapconcat 'identity refs " ")) max)
3597         (when (< (length refs) (1+ cut))
3598           (decf cut))
3599         (setcdr (nthcdr cut refs) (cddr (nthcdr cut refs)))))
3600     (insert (capitalize (symbol-name header)) ": "
3601             (mapconcat 'identity refs " ") "\n")))
3602
3603 (defun message-position-point ()
3604   "Move point to where the user probably wants to find it."
3605   (message-narrow-to-headers)
3606   (cond
3607    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3608     (search-backward ":" )
3609     (widen)
3610     (forward-char 1)
3611     (if (eq (char-after) ? )
3612         (forward-char 1)
3613       (insert " ")))
3614    (t
3615     (goto-char (point-max))
3616     (widen)
3617     (forward-line 1)
3618     (unless (looking-at "$")
3619       (forward-line 2)))
3620    (sit-for 0)))
3621
3622 (defun message-buffer-name (type &optional to group)
3623   "Return a new (unique) buffer name based on TYPE and TO."
3624   (cond
3625    ;; Check whether `message-generate-new-buffers' is a function,
3626    ;; and if so, call it.
3627    ((message-functionp message-generate-new-buffers)
3628     (funcall message-generate-new-buffers type to group))
3629    ;; Generate a new buffer name The Message Way.
3630    ((eq message-generate-new-buffers 'unique)
3631     (generate-new-buffer-name
3632      (concat "*" type
3633              (if to
3634                  (concat " to "
3635                          (or (car (std11-extract-address-components to))
3636                              to) "")
3637                "")
3638              (if (and group (not (string= group ""))) (concat " on " group) "")
3639              "*")))
3640    ((eq message-generate-new-buffers 'unsent)
3641     (generate-new-buffer-name
3642      (concat "*unsent " type
3643              (if to
3644                  (concat " to "
3645                          (or (car (mail-extract-address-components to))
3646                              to) "")
3647                "")
3648              (if (and group (not (string= group ""))) (concat " on " group) "")
3649              "*")))
3650    ;; Use standard name.
3651    (t
3652     (format "*%s message*" type))))
3653
3654 (defun message-pop-to-buffer (name)
3655   "Pop to buffer NAME, and warn if it already exists and is modified."
3656   (let ((pop-up-frames pop-up-frames)
3657         (special-display-buffer-names special-display-buffer-names)
3658         (special-display-regexps special-display-regexps)
3659         (same-window-buffer-names same-window-buffer-names)
3660         (same-window-regexps same-window-regexps)
3661         (buffer (get-buffer name))
3662         (cur (current-buffer)))
3663     (if (or (and (featurep 'xemacs)
3664                  (not (eq 'tty (device-type))))
3665             window-system
3666             (>= emacs-major-version 20))
3667         (when message-use-multi-frames
3668           (setq pop-up-frames t
3669                 special-display-buffer-names nil
3670                 special-display-regexps nil
3671                 same-window-buffer-names nil
3672                 same-window-regexps nil))
3673       (setq pop-up-frames nil))
3674     (if (and buffer
3675              (buffer-name buffer))
3676         (progn
3677           (set-buffer (pop-to-buffer buffer))
3678           (when (and (buffer-modified-p)
3679                      (not (y-or-n-p
3680                            "Message already being composed; erase? ")))
3681             (error "Message being composed")))
3682       (set-buffer (pop-to-buffer name)))
3683     (erase-buffer)
3684     (message-mode)
3685     (when pop-up-frames
3686       (make-local-variable 'message-original-frame)
3687       (setq message-original-frame (selected-frame)))))
3688
3689 (defun message-do-send-housekeeping ()
3690   "Kill old message buffers."
3691   ;; We might have sent this buffer already.  Delete it from the
3692   ;; list of buffers.
3693   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3694   (while (and message-max-buffers
3695               message-buffer-list
3696               (>= (length message-buffer-list) message-max-buffers))
3697     ;; Kill the oldest buffer -- unless it has been changed.
3698     (let ((buffer (pop message-buffer-list)))
3699       (when (and (buffer-name buffer)
3700                  (not (buffer-modified-p buffer)))
3701         (kill-buffer buffer))))
3702   ;; Rename the buffer.
3703   (if message-send-rename-function
3704       (funcall message-send-rename-function)
3705     (when (string-match "\\`\\*\\(unsent \\)?" (buffer-name))
3706       (rename-buffer
3707        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3708   ;; Push the current buffer onto the list.
3709   (when message-max-buffers
3710     (setq message-buffer-list
3711           (nconc message-buffer-list (list (current-buffer))))))
3712
3713 (defvar mc-modes-alist)
3714 (defun message-setup (headers &optional replybuffer actions)
3715   (when (and (boundp 'mc-modes-alist)
3716              (not (assq 'message-mode mc-modes-alist)))
3717     (push '(message-mode (encrypt . mc-encrypt-message)
3718                          (sign . mc-sign-message))
3719           mc-modes-alist))
3720   (when actions
3721     (setq message-send-actions actions))
3722   (setq message-reply-buffer
3723         (or (cdr (assq 'reply-buffer message-parameter-alist))
3724             replybuffer))
3725   (goto-char (point-min))
3726   ;; Insert all the headers.
3727   (mail-header-format
3728    (let ((h headers)
3729          (alist message-header-format-alist))
3730      (while h
3731        (unless (assq (caar h) message-header-format-alist)
3732          (push (list (caar h)) alist))
3733        (pop h))
3734      alist)
3735    headers)
3736   (delete-region (point) (progn (forward-line -1) (point)))
3737   (when message-default-headers
3738     (insert message-default-headers)
3739     (or (bolp) (insert ?\n)))
3740   (put-text-property
3741    (point)
3742    (progn
3743      (insert mail-header-separator "\n")
3744      (1- (point)))
3745    'read-only nil)
3746   (forward-line -1)
3747   (when (message-news-p)
3748     (when message-default-news-headers
3749       (insert message-default-news-headers)
3750       (or (bolp) (insert ?\n)))
3751     (when message-generate-headers-first
3752       (message-generate-headers
3753        (delq 'Lines
3754              (delq 'Subject
3755                    (copy-sequence message-required-news-headers))))))
3756   (when (message-mail-p)
3757     (when message-default-mail-headers
3758       (insert message-default-mail-headers)
3759       (or (bolp) (insert ?\n)))
3760     (when message-generate-headers-first
3761       (message-generate-headers
3762        (delq 'Lines
3763              (delq 'Subject
3764                    (copy-sequence message-required-mail-headers))))))
3765   (run-hooks 'message-signature-setup-hook)
3766   (message-insert-signature)
3767   (save-restriction
3768     (message-narrow-to-headers)
3769     (run-hooks 'message-header-setup-hook))
3770   (set-buffer-modified-p nil)
3771   (setq buffer-undo-list nil)
3772   (run-hooks 'message-setup-hook)
3773   (message-position-point)
3774   (undo-boundary))
3775
3776 (defun message-set-auto-save-file-name ()
3777   "Associate the message buffer with a file in the drafts directory."
3778   (when message-auto-save-directory
3779     (if (gnus-alive-p)
3780         (setq message-draft-article
3781               (nndraft-request-associate-buffer "drafts"))
3782       (setq buffer-file-name (expand-file-name "*message*"
3783                                                message-auto-save-directory))
3784       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
3785     (clear-visited-file-modtime)))
3786
3787 (defun message-disassociate-draft ()
3788   "Disassociate the message buffer from the drafts directory."
3789   (when message-draft-article
3790     (nndraft-request-expire-articles
3791      (list message-draft-article) "drafts" nil t)))
3792
3793 \f
3794
3795 ;;;
3796 ;;; Commands for interfacing with message
3797 ;;;
3798
3799 ;;;###autoload
3800 (defun message-mail (&optional to subject
3801                                other-headers continue switch-function
3802                                yank-action send-actions)
3803   "Start editing a mail message to be sent.
3804 OTHER-HEADERS is an alist of header/value pairs."
3805   (interactive)
3806   (let ((message-this-is-mail t))
3807     (message-pop-to-buffer (message-buffer-name "mail" to))
3808     (message-setup
3809      (nconc
3810       `((To . ,(or to "")) (Subject . ,(or subject "")))
3811       (when other-headers other-headers)))))
3812
3813 ;;;###autoload
3814 (defun message-news (&optional newsgroups subject)
3815   "Start editing a news article to be sent."
3816   (interactive)
3817   (let ((message-this-is-news t))
3818     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3819     (message-setup `((Newsgroups . ,(or newsgroups ""))
3820                      (Subject . ,(or subject ""))))))
3821
3822 ;;;###autoload
3823 (defun message-reply (&optional to-address wide)
3824   "Start editing a reply to the article in the current buffer."
3825   (interactive)
3826   (let ((cur (current-buffer))
3827         from subject date to cc
3828         references message-id follow-to
3829         (inhibit-point-motion-hooks t)
3830         mct never-mct mft mrt gnus-warning)
3831     (save-restriction
3832       (message-narrow-to-head)
3833       ;; Allow customizations to have their say.
3834       (if (not wide)
3835           ;; This is a regular reply.
3836           (if (message-functionp message-reply-to-function)
3837               (setq follow-to (funcall message-reply-to-function)))
3838         ;; This is a followup.
3839         (if (message-functionp message-wide-reply-to-function)
3840             (save-excursion
3841               (setq follow-to
3842                     (funcall message-wide-reply-to-function)))))
3843       ;; Find all relevant headers we need.
3844       (setq from (message-fetch-field "from")
3845             date (message-fetch-field "date" t)
3846             subject (or (message-fetch-field "subject") "none")
3847             references (message-fetch-field "references")
3848             message-id (message-fetch-field "message-id" t)
3849             to (message-fetch-field "to")
3850             cc (message-fetch-field "cc")
3851             mct (when (and wide message-use-mail-copies-to)
3852                   (message-fetch-field "mail-copies-to"))
3853             mft (when (and wide message-use-mail-followup-to)
3854                   (message-fetch-field "mail-followup-to"))
3855             mrt (when message-use-mail-reply-to
3856                   (or (message-fetch-field "mail-reply-to")
3857                       (message-fetch-field "reply-to")))
3858             gnus-warning (message-fetch-field "gnus-warning"))
3859       (when (and gnus-warning (string-match "<[^>]+>" gnus-warning))
3860         (setq message-id (match-string 0 gnus-warning)))
3861       ;; Remove any (buggy) Re:'s that are present and make a
3862       ;; proper one.
3863       (setq subject (message-make-followup-subject subject))
3864       (widen))
3865
3866     ;; Handle special values of Mail-Copies-To.
3867     (when mct
3868       (cond
3869        ((and (or (equal (downcase mct) "never")
3870                  (equal (downcase mct) "nobody"))
3871              (or (not (eq message-use-mail-copies-to 'ask))
3872                  (message-y-or-n-p
3873                   (concat "Obey Mail-Copies-To: never? ") t "\
3874 You should normally obey the Mail-Copies-To: header.
3875
3876         `Mail-Copies-To: never'
3877 directs you not to send your response to the author.")))
3878         (setq never-mct t)
3879         (setq mct nil))
3880        ((and (or (equal (downcase mct) "always")
3881                  (equal (downcase mct) "poster"))
3882              (or (not (eq message-use-mail-copies-to 'ask))
3883                  (message-y-or-n-p
3884                   (concat "Obey Mail-Copies-To: always? ") t "\
3885 You should normally obey the Mail-Copies-To: header.
3886
3887         `Mail-Copies-To: always'
3888 sends a copy of your response to the author.")))
3889         (setq mct (or mrt from)))
3890        ((and (eq message-use-mail-copies-to 'ask)
3891              (not 
3892               (message-y-or-n-p
3893                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
3894 You should normally obey the Mail-Copies-To: header.
3895
3896         `Mail-Copies-To: " mct "'
3897 sends a copy of your response to " (if (string-match "," mct)
3898                                        "the specified addresses"
3899                                      "that address") ".")))
3900         (setq mct nil))
3901        ))
3902
3903     (unless follow-to
3904       (cond
3905        (to-address (setq follow-to (list (cons 'To to-address))))
3906        ((not wide) (setq follow-to (list (cons 'To (or mrt from)))))
3907        ;; Handle Mail-Followup-To.
3908        ((and mft
3909              (or (not (eq message-use-mail-followup-to 'ask))
3910                  (message-y-or-n-p
3911                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
3912 You should normally obey the Mail-Followup-To: header.
3913
3914         `Mail-Followup-To: " mft "'
3915 directs your response to " (if (string-match "," mft)
3916                                "the specified addresses"
3917                              "that address only") ".
3918
3919 A typical situation where Mail-Followup-To is used is when the author thinks
3920 that further discussion should take place only in "
3921                   (if (string-match "," mft)
3922                       "the specified mailing lists"
3923                     "that mailing list") ".")))
3924         (setq follow-to (list (cons 'To mft)))
3925         (when mct
3926           (push (cons 'Cc mct) follow-to)))
3927        (t
3928         (let (ccalist)
3929           (save-excursion
3930             (message-set-work-buffer)
3931             (unless never-mct
3932               (insert (or mrt from "")))
3933             (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3934             (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3935             (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
3936             (goto-char (point-min))
3937             (while (re-search-forward "[ \t]+" nil t)
3938               (replace-match " " t t))
3939             ;; Remove addresses that match `rmail-dont-reply-to-names'.
3940             (insert (prog1 (rmail-dont-reply-to (buffer-string))
3941                       (erase-buffer)))
3942             (goto-char (point-min))
3943             ;; Perhaps Mail-Copies-To: never removed the only address?
3944             (when (eobp)
3945               (insert (or mrt from "")))
3946             (setq ccalist
3947                   (mapcar
3948                    (lambda (addr)
3949                      (cons (mail-strip-quoted-names addr) addr))
3950                    (message-tokenize-header (buffer-string))))
3951             (let ((s ccalist))
3952               (while s
3953                 (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3954           (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3955           (when ccalist
3956             (let ((ccs (cons 'Cc (mapconcat
3957                                   (lambda (addr) (cdr addr)) ccalist ", "))))
3958               (when (string-match "^ +" (cdr ccs))
3959                 (setcdr ccs (substring (cdr ccs) (match-end 0))))
3960               (push ccs follow-to)))))))
3961
3962     (message-pop-to-buffer (message-buffer-name
3963                             (if wide "wide reply" "reply") from
3964                             (if wide to-address nil)))
3965
3966     (setq message-reply-headers
3967           (make-full-mail-header-from-decoded-header
3968            0 subject from date message-id references 0 0 ""))
3969
3970     (message-setup
3971      `((Subject . ,subject)
3972        ,@follow-to
3973        ,@(if (or references message-id)
3974              `((References . ,(concat (or references "") (and references " ")
3975                                       (or message-id ""))))))
3976      cur)))
3977
3978 ;;;###autoload
3979 (defun message-wide-reply (&optional to-address)
3980   "Make a \"wide\" reply to the message in the current buffer."
3981   (interactive)
3982   (message-reply to-address t))
3983
3984 ;;;###autoload
3985 (defun message-followup (&optional to-newsgroups)
3986   "Follow up to the message in the current buffer.
3987 If TO-NEWSGROUPS, use that as the new Newsgroups line."
3988   (interactive)
3989   (let ((cur (current-buffer))
3990         from subject date mct
3991         references message-id follow-to
3992         (inhibit-point-motion-hooks t)
3993         (message-this-is-news t)
3994         followup-to distribution newsgroups gnus-warning posted-to mft mrt)
3995     (save-restriction
3996       (message-narrow-to-head)
3997       (when (message-functionp message-followup-to-function)
3998         (setq follow-to
3999               (funcall message-followup-to-function)))
4000       (setq from (message-fetch-field "from")
4001             date (message-fetch-field "date" t)
4002             subject (or (message-fetch-field "subject") "none")
4003             references (message-fetch-field "references")
4004             message-id (message-fetch-field "message-id" t)
4005             followup-to (when message-use-followup-to
4006                           (message-fetch-field "followup-to"))
4007             distribution (message-fetch-field "distribution")
4008             newsgroups (message-fetch-field "newsgroups")
4009             posted-to (message-fetch-field "posted-to")
4010             mct (when message-use-mail-copies-to
4011                   (message-fetch-field "mail-copies-to"))
4012             mft (when message-use-mail-followup-to
4013                   (message-fetch-field "mail-followup-to"))
4014             mrt (when message-use-mail-reply-to
4015                   (or (message-fetch-field "mail-reply-to")
4016                       (message-fetch-field "reply-to")))
4017             gnus-warning (message-fetch-field "gnus-warning"))
4018       (when (and gnus-warning (string-match "<[^>]+>" gnus-warning))
4019         (setq message-id (match-string 0 gnus-warning)))
4020       ;; Remove bogus distribution.
4021       (when (and (stringp distribution)
4022                  (let ((case-fold-search t))
4023                    (string-match "world" distribution)))
4024         (setq distribution nil))
4025       ;; Remove any (buggy) Re:'s that are present and make a
4026       ;; proper one.
4027       (setq subject (message-make-followup-subject subject))
4028       (widen))
4029
4030     ;; Handle special values of Mail-Copies-To.
4031     (when mct
4032       (cond
4033        ((and (or (equal (downcase mct) "never")
4034                  (equal (downcase mct) "nobody"))
4035              (or (not (eq message-use-mail-copies-to 'ask))
4036                  (message-y-or-n-p
4037                   (concat "Obey Mail-Copies-To: never? ") t "\
4038 You should normally obey the Mail-Copies-To: header.
4039
4040         `Mail-Copies-To: never'
4041 directs you not to send your response to the author.")))
4042         (setq mct nil))
4043        ((and (or (equal (downcase mct) "always")
4044                  (equal (downcase mct) "poster"))
4045              (or (not (eq message-use-mail-copies-to 'ask))
4046                  (message-y-or-n-p
4047                   (concat "Obey Mail-Copies-To: always? ") t "\
4048 You should normally obey the Mail-Copies-To: header.
4049
4050         `Mail-Copies-To: always'
4051 sends a copy of your response to the author.")))
4052         (setq mct (or mrt from)))
4053        ((and (eq message-use-mail-copies-to 'ask)
4054              (not 
4055               (message-y-or-n-p
4056                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
4057 You should normally obey the Mail-Copies-To: header.
4058
4059         `Mail-Copies-To: " mct "'
4060 sends a copy of your response to " (if (string-match "," mct)
4061                                        "the specified addresses"
4062                                      "that address") ".")))
4063         (setq mct nil))
4064        ))
4065
4066     (unless follow-to
4067       (cond
4068        (to-newsgroups (setq follow-to (list (cons 'Newsgroups to-newsgroups))))
4069        ;; Handle Followup-To.
4070        (followup-to
4071         (cond
4072          ((equal (downcase followup-to) "poster")
4073           (if (or (eq message-use-followup-to 'use)
4074                   (message-y-or-n-p "Obey Followup-To: poster? " t "\
4075 You should normally obey the Followup-To: header.
4076
4077         `Followup-To: poster'
4078 sends your response via e-mail instead of news.
4079
4080 A typical situation where `Followup-To: poster' is used is when the author
4081 does not read the newsgroup, so he wouldn't see any replies sent to it."))
4082               (setq message-this-is-news nil
4083                     distribution nil
4084                     follow-to (list (cons 'To (or mrt from ""))))
4085             (setq follow-to (list (cons 'Newsgroups newsgroups)))))
4086          (t
4087           (if (or (equal followup-to newsgroups)
4088                   (not (eq message-use-followup-to 'ask))
4089                   (message-y-or-n-p
4090                    (concat "Obey Followup-To: " followup-to "? ") t "\
4091 You should normally obey the Followup-To: header.
4092
4093         `Followup-To: " followup-to "'
4094 directs your response to " (if (string-match "," followup-to)
4095                                "the specified newsgroups"
4096                              "that newsgroup only") ".
4097
4098 If a message is posted to several newsgroups, Followup-To is often
4099 used to direct the following discussion to one newsgroup only,
4100 because discussions that are spread over several newsgroup tend to
4101 be fragmented and very difficult to follow.
4102
4103 Also, some source/announcement newsgroups are not indented for discussion;
4104 responses here are directed to other newsgroups."))
4105               (setq follow-to (list (cons 'Newsgroups followup-to)))
4106             (setq follow-to (list (cons 'Newsgroups newsgroups)))))))
4107        ;; Handle Mail-Followup-To, followup via e-mail.
4108        ((and mft
4109              (or (not (eq message-use-mail-followup-to 'ask))
4110                  (message-y-or-n-p
4111                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
4112 You should normally obey the Mail-Followup-To: header.
4113
4114         `Mail-Followup-To: " mft "'
4115 directs your response to " (if (string-match "," mft)
4116                                "the specified addresses"
4117                              "that address only") " instead of news.
4118
4119 A typical situation where Mail-Followup-To is used is when the author thinks
4120 that further discussion should take place only in "
4121                              (if (string-match "," mft)
4122                                  "the specified mailing lists"
4123                                "that mailing list") ".")))
4124         (setq message-this-is-news nil
4125               distribution nil
4126               follow-to (list (cons 'To mft))))
4127        (posted-to (setq follow-to (list (cons 'Newsgroups posted-to))))
4128        (t
4129         (setq follow-to (list (cons 'Newsgroups newsgroups))))))
4130
4131     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
4132
4133     (setq message-reply-headers
4134           (make-full-mail-header-from-decoded-header
4135            0 subject from date message-id references 0 0 ""))
4136
4137     (message-setup
4138      `((Subject . ,subject)
4139        ,@follow-to
4140        ,@(and mct (list (cons 'Cc mct)))
4141        ,@(and distribution (list (cons 'Distribution distribution)))
4142        ,@(if (or references message-id)
4143              `((References . ,(concat (or references "") (and references " ")
4144                                       (or message-id ""))))))
4145      cur)))
4146
4147 ;;;###autoload
4148 (defun message-cancel-news ()
4149   "Cancel an article you posted."
4150   (interactive)
4151   (unless (message-news-p)
4152     (error "This is not a news article; canceling is impossible"))
4153   (when (yes-or-no-p "Do you really want to cancel this article? ")
4154     (let (from newsgroups message-id distribution buf sender)
4155       (save-excursion
4156         ;; Get header info. from original article.
4157         (save-restriction
4158           (message-narrow-to-head)
4159           (setq from (message-fetch-field "from")
4160                 sender (message-fetch-field "sender")
4161                 newsgroups (message-fetch-field "newsgroups")
4162                 message-id (message-fetch-field "message-id" t)
4163                 distribution (message-fetch-field "distribution")))
4164         ;; Make sure that this article was written by the user.
4165         (unless (or (and sender
4166                          (string-equal
4167                           (downcase sender)
4168                           (downcase (message-make-sender))))
4169                     (string-equal
4170                      (downcase (cadr (std11-extract-address-components
4171                                       from)))
4172                      (downcase (cadr (std11-extract-address-components
4173                                       (message-make-from))))))
4174           (error "This article is not yours"))
4175         ;; Make control message.
4176         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
4177         (erase-buffer)
4178         (insert "Newsgroups: " newsgroups "\n"
4179                 "From: " (message-make-from) "\n"
4180                 "Subject: cmsg cancel " message-id "\n"
4181                 "Control: cancel " message-id "\n"
4182                 (if distribution
4183                     (concat "Distribution: " distribution "\n")
4184                   "")
4185                 mail-header-separator "\n"
4186                 message-cancel-message)
4187         (message "Canceling your article...")
4188         (if (let ((message-syntax-checks
4189                    'dont-check-for-anything-just-trust-me)
4190                   (message-encoding-buffer (current-buffer))
4191                   (message-edit-buffer (current-buffer)))
4192               (message-send-news))
4193             (message "Canceling your article...done"))
4194         (kill-buffer buf)))))
4195
4196 ;;;###autoload
4197 (defun message-supersede ()
4198   "Start composing a message to supersede the current message.
4199 This is done simply by taking the old article and adding a Supersedes
4200 header line with the old Message-ID."
4201   (interactive)
4202   (let ((cur (current-buffer))
4203         (sender (message-fetch-field "sender"))
4204         (from (message-fetch-field "from")))
4205     ;; Check whether the user owns the article that is to be superseded.
4206     (unless (or (and sender
4207                      (string-equal
4208                       (downcase sender)
4209                       (downcase (message-make-sender))))
4210                 (string-equal
4211                  (downcase (cadr (std11-extract-address-components from)))
4212                  (downcase (cadr (std11-extract-address-components
4213                                   (message-make-from))))))
4214       (error "This article is not yours"))
4215     ;; Get a normal message buffer.
4216     (message-pop-to-buffer (message-buffer-name "supersede"))
4217     (insert-buffer-substring cur)
4218     (message-narrow-to-head)
4219     ;; Remove unwanted headers.
4220     (when message-ignored-supersedes-headers
4221       (message-remove-header message-ignored-supersedes-headers t))
4222     (goto-char (point-min))
4223     (if (not (re-search-forward "^Message-ID: " nil t))
4224         (error "No Message-ID in this article")
4225       (replace-match "Supersedes: " t t))
4226     (goto-char (point-max))
4227     (insert mail-header-separator)
4228     (widen)
4229     (forward-line 1)))
4230
4231 ;;;###autoload
4232 (defun message-recover ()
4233   "Reread contents of current buffer from its last auto-save file."
4234   (interactive)
4235   (let ((file-name (make-auto-save-file-name)))
4236     (cond ((save-window-excursion
4237              (if (not (eq system-type 'vax-vms))
4238                  (with-output-to-temp-buffer "*Directory*"
4239                    (buffer-disable-undo standard-output)
4240                    (let ((default-directory "/"))
4241                      (call-process
4242                       "ls" nil standard-output nil "-l" file-name))))
4243              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
4244            (let ((buffer-read-only nil))
4245              (erase-buffer)
4246              (insert-file-contents file-name nil)))
4247           (t (error "message-recover cancelled")))))
4248
4249 ;;; Washing Subject:
4250
4251 (defun message-wash-subject (subject)
4252   "Remove junk like \"Re:\", \"(fwd)\", etc. that was added to the subject by previous forwarders, replyers, etc."
4253   (with-temp-buffer
4254     (insert-string subject)
4255     (goto-char (point-min))
4256     ;; strip Re/Fwd stuff off the beginning
4257     (while (re-search-forward
4258             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
4259       (replace-match ""))
4260
4261     ;; and gnus-style forwards [foo@bar.com] subject
4262     (goto-char (point-min))
4263     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
4264       (replace-match ""))
4265
4266     ;; and off the end
4267     (goto-char (point-max))
4268     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
4269       (replace-match ""))
4270
4271     ;; and finally, any whitespace that was left-over
4272     (goto-char (point-min))
4273     (while (re-search-forward "^[ \t]+" nil t)
4274       (replace-match ""))
4275     (goto-char (point-max))
4276     (while (re-search-backward "[ \t]+$" nil t)
4277       (replace-match ""))
4278
4279     (buffer-string)))
4280     
4281 ;;; Forwarding messages.
4282
4283 (defun message-forward-subject-author-subject (subject)
4284   "Generate a subject for a forwarded message.
4285 The form is: [Source] Subject, where if the original message was mail,
4286 Source is the sender, and if the original message was news, Source is
4287 the list of newsgroups is was posted to."
4288   (concat "["
4289           (or (message-fetch-field
4290                (if (message-news-p) "newsgroups" "from"))
4291               "(nowhere)")
4292           "] " subject))
4293
4294 (defun message-forward-subject-fwd (subject)
4295   "Generate a subject for a forwarded message.
4296 The form is: Fwd: Subject, where Subject is the original subject of
4297 the message."
4298   (concat "Fwd: " subject))
4299
4300 (defun message-make-forward-subject ()
4301   "Return a Subject header suitable for the message in the current buffer."
4302   (save-excursion
4303     (save-restriction
4304       (current-buffer)
4305       (message-narrow-to-head)
4306       (let ((funcs message-make-forward-subject-function)
4307             (subject (if message-wash-forwarded-subjects
4308                          (message-wash-subject
4309                           (or (nnheader-decode-subject
4310                                (message-fetch-field "Subject"))
4311                               ""))
4312                        (or (nnheader-decode-subject
4313                             (message-fetch-field "Subject"))
4314                            ""))))
4315         ;; Make sure funcs is a list.
4316         (and funcs
4317              (not (listp funcs))
4318              (setq funcs (list funcs)))
4319         ;; Apply funcs in order, passing subject generated by previous
4320         ;; func to the next one.
4321         (while funcs
4322           (when (message-functionp (car funcs))
4323             (setq subject (funcall (car funcs) subject)))
4324           (setq funcs (cdr funcs)))
4325         subject))))
4326
4327 ;;;###autoload
4328 (defun message-forward (&optional news)
4329   "Forward the current message via mail.
4330 Optional NEWS will use news to forward instead of mail."
4331   (interactive "P")
4332   (let ((cur (current-buffer))
4333         (subject (message-make-forward-subject))
4334         art-beg)
4335     (if news (message-news nil subject) (message-mail nil subject))
4336     ;; Put point where we want it before inserting the forwarded
4337     ;; message.
4338     (if message-signature-before-forwarded-message
4339         (goto-char (point-max))
4340       (message-goto-body))
4341     ;; Make sure we're at the start of the line.
4342     (unless (eolp)
4343       (insert "\n"))
4344     ;; Narrow to the area we are to insert.
4345     (narrow-to-region (point) (point))
4346     ;; Insert the separators and the forwarded buffer.
4347     (insert message-forward-start-separator)
4348     (setq art-beg (point))
4349     (insert-buffer-substring cur)
4350     (goto-char (point-max))
4351     (insert message-forward-end-separator)
4352     (set-text-properties (point-min) (point-max) nil)
4353     ;; Remove all unwanted headers.
4354     (goto-char art-beg)
4355     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
4356                                   (1- (point))
4357                                 (point)))
4358     (goto-char (point-min))
4359     (message-remove-header message-included-forward-headers t nil t)
4360     (widen)
4361     (message-position-point)))
4362
4363 ;;;###autoload
4364 (defun message-resend (address)
4365   "Resend the current article to ADDRESS."
4366   (interactive "sResend message to: ")
4367   (message "Resending message to %s..." address)
4368   (save-excursion
4369     (let ((cur (current-buffer))
4370           beg)
4371       ;; We first set up a normal mail buffer.
4372       (set-buffer (get-buffer-create " *message resend*"))
4373       (erase-buffer)
4374       ;; avoid to turn-on-mime-edit
4375       (let (message-setup-hook)
4376         (message-setup `((To . ,address)))
4377         )
4378       ;; Insert our usual headers.
4379       (message-generate-headers '(From Date To))
4380       (message-narrow-to-headers)
4381       ;; Rename them all to "Resent-*".
4382       (while (re-search-forward "^[A-Za-z]" nil t)
4383         (forward-char -1)
4384         (insert "Resent-"))
4385       (widen)
4386       (forward-line)
4387       (delete-region (point) (point-max))
4388       (setq beg (point))
4389       ;; Insert the message to be resent.
4390       (insert-buffer-substring cur)
4391       (goto-char (point-min))
4392       (search-forward "\n\n")
4393       (forward-char -1)
4394       (save-restriction
4395         (narrow-to-region beg (point))
4396         (message-remove-header message-ignored-resent-headers t)
4397         (goto-char (point-max)))
4398       (insert mail-header-separator)
4399       ;; Rename all old ("Also-")Resent headers.
4400       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
4401         (beginning-of-line)
4402         (insert "Also-"))
4403       ;; Quote any "From " lines at the beginning.
4404       (goto-char beg)
4405       (when (looking-at "From ")
4406         (replace-match "X-From-Line: "))
4407       ;; Send it.
4408       (let ((message-encoding-buffer (current-buffer))
4409             (message-edit-buffer (current-buffer)))
4410         (let (message-required-mail-headers)
4411           (message-send-mail)))
4412       (kill-buffer (current-buffer)))
4413     (message "Resending message to %s...done" address)))
4414
4415 (defun message-bounce-setup-for-mime-edit ()
4416   (goto-char (point-min))
4417   (when (search-forward (concat "\n" mail-header-separator "\n") nil t)
4418     (replace-match "\n\n"))
4419   (set (make-local-variable 'message-setup-hook) nil)
4420   (mime-edit-again))
4421
4422 ;;;###autoload
4423 (defun message-bounce ()
4424   "Re-mail the current message.
4425 This only makes sense if the current message is a bounce message than
4426 contains some mail you have written which has been bounced back to
4427 you."
4428   (interactive)
4429   (let ((cur (current-buffer))
4430         boundary)
4431     (message-pop-to-buffer (message-buffer-name "bounce"))
4432     (insert-buffer-substring cur)
4433     (undo-boundary)
4434     (message-narrow-to-head)
4435     (if (and (message-fetch-field "MIME-Version")
4436              (setq boundary (message-fetch-field "Content-Type")))
4437         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
4438             (setq boundary (concat (match-string 1 boundary) " *\n"
4439                                    "Content-Type: message/rfc822"))
4440           (setq boundary nil)))
4441     (widen)
4442     (goto-char (point-min))
4443     (search-forward "\n\n" nil t)
4444     (or (and boundary
4445              (re-search-forward boundary nil t)
4446              (forward-line 2))
4447         (and (re-search-forward message-unsent-separator nil t)
4448              (forward-line 1))
4449         (re-search-forward "^Return-Path:.*\n" nil t))
4450     ;; We remove everything before the bounced mail.
4451     (delete-region
4452      (point-min)
4453      (if (re-search-forward "^[^ \n\t]+:" nil t)
4454          (match-beginning 0)
4455        (point)))
4456     (save-restriction
4457       (message-narrow-to-head)
4458       (message-remove-header message-ignored-bounced-headers t)
4459       (goto-char (point-max))
4460       (insert mail-header-separator))
4461     (when message-bounce-setup-function
4462       (funcall message-bounce-setup-function))
4463     (run-hooks 'message-bounce-setup-hook)
4464     (message-position-point)))
4465
4466 ;;;
4467 ;;; Interactive entry points for new message buffers.
4468 ;;;
4469
4470 ;;;###autoload
4471 (defun message-mail-other-window (&optional to subject)
4472   "Like `message-mail' command, but display mail buffer in another window."
4473   (interactive)
4474   (let ((pop-up-windows t)
4475         (special-display-buffer-names nil)
4476         (special-display-regexps nil)
4477         (same-window-buffer-names nil)
4478         (same-window-regexps nil))
4479     (message-pop-to-buffer (message-buffer-name "mail" to)))
4480   (let ((message-this-is-mail t))
4481     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4482
4483 ;;;###autoload
4484 (defun message-mail-other-frame (&optional to subject)
4485   "Like `message-mail' command, but display mail buffer in another frame."
4486   (interactive)
4487   (let ((pop-up-frames t)
4488         (special-display-buffer-names nil)
4489         (special-display-regexps nil)
4490         (same-window-buffer-names nil)
4491         (same-window-regexps nil))
4492     (message-pop-to-buffer (message-buffer-name "mail" to)))
4493   (let ((message-this-is-mail t))
4494     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4495
4496 ;;;###autoload
4497 (defun message-news-other-window (&optional newsgroups subject)
4498   "Start editing a news article to be sent."
4499   (interactive)
4500   (let ((pop-up-windows t)
4501         (special-display-buffer-names nil)
4502         (special-display-regexps nil)
4503         (same-window-buffer-names nil)
4504         (same-window-regexps nil))
4505     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4506   (let ((message-this-is-news t))
4507     (message-setup `((Newsgroups . ,(or newsgroups ""))
4508                      (Subject . ,(or subject ""))))))
4509
4510 ;;;###autoload
4511 (defun message-news-other-frame (&optional newsgroups subject)
4512   "Start editing a news article to be sent."
4513   (interactive)
4514   (let ((pop-up-frames t)
4515         (special-display-buffer-names nil)
4516         (special-display-regexps nil)
4517         (same-window-buffer-names nil)
4518         (same-window-regexps nil))
4519     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4520   (let ((message-this-is-news t))
4521     (message-setup `((Newsgroups . ,(or newsgroups ""))
4522                      (Subject . ,(or subject ""))))))
4523
4524 ;;; underline.el
4525
4526 ;; This code should be moved to underline.el (from which it is stolen).
4527
4528 ;;;###autoload
4529 (defun bold-region (start end)
4530   "Bold all nonblank characters in the region.
4531 Works by overstriking characters.
4532 Called from program, takes two arguments START and END
4533 which specify the range to operate on."
4534   (interactive "r")
4535   (save-excursion
4536     (let ((end1 (make-marker)))
4537       (move-marker end1 (max start end))
4538       (goto-char (min start end))
4539       (while (< (point) end1)
4540         (or (looking-at "[_\^@- ]")
4541             (insert (char-after) "\b"))
4542         (forward-char 1)))))
4543
4544 ;;;###autoload
4545 (defun unbold-region (start end)
4546   "Remove all boldness (overstruck characters) in the region.
4547 Called from program, takes two arguments START and END
4548 which specify the range to operate on."
4549   (interactive "r")
4550   (save-excursion
4551     (let ((end1 (make-marker)))
4552       (move-marker end1 (max start end))
4553       (goto-char (min start end))
4554       (while (re-search-forward "\b" end1 t)
4555         (if (eq (char-after) (char-after (- (point) 2)))
4556             (delete-char -2))))))
4557
4558 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
4559
4560 ;; Support for toolbar
4561 (when (string-match "XEmacs\\|Lucid" emacs-version)
4562   (require 'messagexmas))
4563
4564 ;;; Group name completion.
4565
4566 (defvar message-newgroups-header-regexp
4567   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
4568   "Regexp that match headers that lists groups.")
4569
4570 (defun message-tab ()
4571   "Expand group names in Newsgroups and Followup-To headers.
4572 Do a `tab-to-tab-stop' if not in those headers."
4573   (interactive)
4574   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
4575         (mail-abbrev-in-expansion-header-p))
4576       (message-expand-group)
4577     (tab-to-tab-stop)))
4578
4579 (defvar gnus-active-hashtb)
4580 (defun message-expand-group ()
4581   "Expand the group name under point."
4582   (let* ((b (save-excursion
4583               (save-restriction
4584                 (narrow-to-region
4585                  (save-excursion
4586                    (beginning-of-line)
4587                    (skip-chars-forward "^:")
4588                    (1+ (point)))
4589                  (point))
4590                 (skip-chars-backward "^, \t\n") (point))))
4591          (completion-ignore-case t)
4592          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
4593                                             (point))))
4594          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
4595          (completions (all-completions string hashtb))
4596          comp)
4597     (delete-region b (point))
4598     (cond
4599      ((= (length completions) 1)
4600       (if (string= (car completions) string)
4601           (progn
4602             (insert string)
4603             (message "Only matching group"))
4604         (insert (car completions))))
4605      ((and (setq comp (try-completion string hashtb))
4606            (not (string= comp string)))
4607       (insert comp))
4608      (t
4609       (insert string)
4610       (if (not comp)
4611           (message "No matching groups")
4612         (save-selected-window
4613           (pop-to-buffer "*Completions*")
4614           (buffer-disable-undo)
4615           (let ((buffer-read-only nil))
4616             (erase-buffer)
4617             (let ((standard-output (current-buffer)))
4618               (display-completion-list (sort completions 'string<)))
4619             (goto-char (point-min))
4620             (delete-region (point) (progn (forward-line 3) (point))))))))))
4621
4622 ;;; Help stuff.
4623
4624 (defun message-talkative-question (ask question show &rest text)
4625   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
4626 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
4627 The following arguments may contain lists of values."
4628   (if (and show
4629            (setq text (message-flatten-list text)))
4630       (save-window-excursion
4631         (save-excursion
4632           (with-output-to-temp-buffer " *MESSAGE information message*"
4633             (set-buffer " *MESSAGE information message*")
4634             (mapcar 'princ text)
4635             (goto-char (point-min))))
4636         (funcall ask question))
4637     (funcall ask question)))
4638
4639 (defun message-flatten-list (list)
4640   "Return a new, flat list that contains all elements of LIST.
4641
4642 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
4643 => (1 2 3 4 5 6 7)"
4644   (cond ((consp list)
4645          (apply 'append (mapcar 'message-flatten-list list)))
4646         (list
4647          (list list))))
4648
4649 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
4650   "Create and return a buffer with a name based on NAME using generate-new-buffer.
4651 Then clone the local variables and values from the old buffer to the
4652 new one, cloning only the locals having a substring matching the
4653 regexp varstr."
4654   (let ((oldbuf (current-buffer)))
4655     (save-excursion
4656       (set-buffer (generate-new-buffer name))
4657       (message-clone-locals oldbuf)
4658       (current-buffer))))
4659
4660 (defun message-clone-locals (buffer)
4661   "Clone the local variables from BUFFER to the current buffer."
4662   (let ((locals (save-excursion
4663                   (set-buffer buffer)
4664                   (buffer-local-variables)))
4665         (regexp
4666          "^\\(gnus\\|nn\\|message\\|user-\\(mail-address\\|full-name\\)\\)"))
4667     (mapcar
4668      (lambda (local)
4669        (when (and (consp local)
4670                   (car local)
4671                   (string-match regexp (symbol-name (car local))))
4672          (ignore-errors
4673            (set (make-local-variable (car local))
4674                 (cdr local)))))
4675      locals)))
4676
4677
4678 ;;; @ for MIME Edit mode
4679 ;;;
4680
4681 (defun message-maybe-encode ()
4682   (when message-mime-mode
4683     (run-hooks 'mime-edit-translate-hook)
4684     (if (catch 'mime-edit-error
4685           (save-excursion
4686             (mime-edit-translate-body)
4687             ))
4688         (error "Translation error!")
4689       )
4690     (end-of-invisible)
4691     (run-hooks 'mime-edit-exit-hook)
4692     ))
4693
4694 (defun message-mime-insert-article (&optional full-headers)
4695   (interactive "P")
4696   (let ((message-cite-function 'mime-edit-inserted-message-filter)
4697         (message-reply-buffer (message-get-original-reply-buffer))
4698         (start (point)))
4699     (message-yank-original nil)
4700     (save-excursion
4701       (narrow-to-region (goto-char start)
4702                         (if (search-forward "\n\n" nil t)
4703                             (1- (point))
4704                           (point-max)))
4705       (goto-char (point-min))
4706       (let ((message-included-forward-headers
4707              (if full-headers "" message-included-forward-headers)))
4708         (message-remove-header message-included-forward-headers t nil t))
4709       (widen))))
4710
4711 (set-alist 'mime-edit-message-inserter-alist
4712            'message-mode (function message-mime-insert-article))
4713
4714 ;;; Miscellaneous functions
4715
4716 ;; stolen (and renamed) from nnheader.el
4717 (defun message-replace-chars-in-string (string from to)
4718   "Replace characters in STRING from FROM to TO."
4719   (let ((string (substring string 0))   ;Copy string.
4720         (len (length string))
4721         (idx 0))
4722     ;; Replace all occurrences of FROM with TO.
4723     (while (< idx len)
4724       (when (= (aref string idx) from)
4725         (aset string idx to))
4726       (setq idx (1+ idx)))
4727     string))
4728
4729 ;;;
4730 ;;; MIME functions
4731 ;;;
4732
4733 (defun message-insert-mime-part (file type)
4734   "Insert a multipart/alternative part into the buffer."
4735   (interactive
4736    (let* ((file (read-file-name "Insert file: " nil nil t))
4737           (type (mm-default-file-encoding file)))
4738      (list file
4739            (completing-read
4740             (format "MIME type for %s: " file)
4741             (delete-duplicates
4742              (mapcar (lambda (m) (list (cdr m))) mailcap-mime-extensions))
4743             nil nil type))))
4744   (insert (format "<#part type=%s filename=\"%s\"><#/part>\n"
4745                   type file)))
4746
4747 (defun message-encode-message-body ()
4748   (let (lines multipart-p)
4749     (message-goto-body)
4750     (save-restriction
4751       (narrow-to-region (point) (point-max))
4752       (let ((new (mml-generate-mime)))
4753         (delete-region (point-min) (point-max))
4754         (insert new)
4755         (goto-char (point-min))
4756         (if (eq (aref new 0) ?\n)
4757             (delete-char 1)
4758           (search-forward "\n\n")
4759           (setq lines (buffer-substring (point-min) (1- (point))))
4760           (delete-region (point-min)  (point)))))
4761     (save-restriction
4762       (message-narrow-to-headers-or-head)
4763       (message-remove-header "Mime-Version")
4764       (goto-char (point-max))
4765       (insert "Mime-Version: 1.0\n")
4766       (when lines
4767         (insert lines))
4768       (setq multipart-p
4769             (re-search-backward "^Content-Type: multipart/" nil t)))
4770     (when multipart-p
4771       (message-goto-body)
4772       (insert "This is a MIME multipart message.  If you are reading\n")
4773       (insert "this, you shouldn't.\n"))))
4774
4775 (defvar message-save-buffer " *encoding")
4776 (defun message-save-drafts ()
4777   (interactive)
4778   (if (not (get-buffer message-save-buffer))
4779       (get-buffer-create message-save-buffer))
4780   (let ((filename buffer-file-name)
4781         (buffer (current-buffer)))
4782     (set-buffer message-save-buffer)
4783     (erase-buffer)
4784     (insert-buffer buffer)
4785     (mime-edit-translate-buffer)
4786     (write-region (point-min) (point-max) filename)
4787     (set-buffer buffer)
4788     (set-buffer-modified-p nil)))
4789
4790 (run-hooks 'message-load-hook)
4791
4792 (provide 'message)
4793
4794 ;;; message.el ends here