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