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