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