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