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