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