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