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