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