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