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