e2b15999473521b63bec80989d984bcc74ea52de
[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   (define-key message-mode-map "\C-c\C-fc" 'message-goto-mail-copies-to)
1678
1679   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1680   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1681
1682   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1683   (define-key message-mode-map "\C-c\M-\C-y" 'message-yank-buffer)
1684   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1685   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1686   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
1687   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1688   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1689   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1690
1691   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1692   (define-key message-mode-map "\C-c\C-s" 'message-send)
1693   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1694   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1695
1696   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1697   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1698   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1699   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1700
1701   (define-key message-mode-map "\t" 'message-tab)
1702
1703   (define-key message-mode-map "\C-x\C-s" 'message-save-drafts)
1704   (define-key message-mode-map "\C-xk" 'message-mimic-kill-buffer))
1705
1706 (easy-menu-define
1707  message-mode-menu message-mode-map "Message Menu."
1708  '("Message"
1709    ["Sort Headers" message-sort-headers t]
1710    ["Yank Original" message-yank-original t]
1711    ["Fill Yanked Message" message-fill-yanked-message t]
1712    ["Insert Signature" message-insert-signature t]
1713    ["Caesar (rot13) Message" message-caesar-buffer-body t]
1714    ["Caesar (rot13) Region" message-caesar-region (mark t)]
1715    ["Elide Region" message-elide-region (mark t)]
1716    ["Delete Outside Region" message-delete-not-region (mark t)]
1717    ["Kill To Signature" message-kill-to-signature t]
1718    ["Newline and Reformat" message-newline-and-reformat t]
1719    ["Rename buffer" message-rename-buffer t]
1720    ["Spellcheck" ispell-message t]
1721    ["Attach file as MIME" mime-edit-insert-file t]
1722    "----"
1723    ["Send Message" message-send-and-exit t]
1724    ["Abort Message" message-dont-send t]
1725    ["Kill Message" message-kill-buffer t]))
1726
1727 (easy-menu-define
1728  message-mode-field-menu message-mode-map ""
1729  '("Field"
1730    ["Fetch To" message-insert-to t]
1731    ["Fetch Newsgroups" message-insert-newsgroups t]
1732    "----"
1733    ["To" message-goto-to t]
1734    ["Subject" message-goto-subject t]
1735    ["Cc" message-goto-cc t]
1736    ["Reply-To" message-goto-reply-to t]
1737    ["Mail-Reply-To" message-goto-mail-reply-to t]
1738    ["Mail-Followup-To" message-goto-mail-followup-to t]
1739    ["Mail-Copies-To" message-goto-mail-copies-to t]
1740    ["Summary" message-goto-summary t]
1741    ["Keywords" message-goto-keywords t]
1742    ["Newsgroups" message-goto-newsgroups t]
1743    ["Followup-To" message-goto-followup-to t]
1744    ["Distribution" message-goto-distribution t]
1745    ["Body" message-goto-body t]
1746    ["Signature" message-goto-signature t]))
1747
1748 (defvar facemenu-add-face-function)
1749 (defvar facemenu-remove-face-function)
1750
1751 ;;;###autoload
1752 (defun message-mode ()
1753   "Major mode for editing mail and news to be sent.
1754 Like Text Mode but with these additional commands:
1755 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
1756 C-c C-d  Pospone sending the message        C-c C-k  Kill the message
1757 C-c C-f  move to a header field (and create it if there isn't):
1758          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1759          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1760          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1761          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1762          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1763          C-c C-f C-m  move to Mail-Followup-To
1764          C-c C-f C-f  move to Followup-To
1765 C-c C-t  message-insert-to (add a To header to a news followup)
1766 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
1767 C-c C-b  message-goto-body (move to beginning of message text).
1768 C-c C-i  message-goto-signature (move to the beginning of the signature).
1769 C-c C-w  message-insert-signature (insert `message-signature-file' file).
1770 C-c C-y  message-yank-original (insert current message, if any).
1771 C-c C-q  message-fill-yanked-message (fill what was yanked).
1772 C-c C-e  message-elide-region (elide the text between point and mark).
1773 C-c C-v  message-delete-not-region (remove the text outside the region).
1774 C-c C-z  message-kill-to-signature (kill the text up to the signature).
1775 C-c C-r  message-caesar-buffer-body (rot13 the message body).
1776 M-RET    message-newline-and-reformat (break the line and reformat)."
1777   (interactive)
1778   (kill-all-local-variables)
1779   (set (make-local-variable 'message-reply-buffer) nil)
1780   (make-local-variable 'message-send-actions)
1781   (make-local-variable 'message-exit-actions)
1782   (make-local-variable 'message-kill-actions)
1783   (make-local-variable 'message-postpone-actions)
1784   (make-local-variable 'message-draft-article)
1785   (make-local-hook 'kill-buffer-hook)
1786   (set-syntax-table message-mode-syntax-table)
1787   (use-local-map message-mode-map)
1788   (setq local-abbrev-table message-mode-abbrev-table)
1789   (setq major-mode 'message-mode)
1790   (setq mode-name "Message")
1791   (setq buffer-offer-save t)
1792   (make-local-variable 'facemenu-add-face-function)
1793   (make-local-variable 'facemenu-remove-face-function)
1794   (setq facemenu-add-face-function
1795         (lambda (face end)
1796           (let ((face-fun (cdr (assq face message-face-alist))))
1797             (if face-fun
1798                 (funcall face-fun (point) end)
1799               (error "Face %s not configured for %s mode" face mode-name)))
1800           "")
1801         facemenu-remove-face-function t)
1802   (make-local-variable 'paragraph-separate)
1803   (make-local-variable 'paragraph-start)
1804   ;; `-- ' precedes the signature.  `-----' appears at the start of the
1805   ;; lines that delimit forwarded messages.
1806   ;; Lines containing just >= 3 dashes, perhaps after whitespace,
1807   ;; are also sometimes used and should be separators.
1808   (setq paragraph-start
1809         (concat (regexp-quote mail-header-separator)
1810                 "$\\|[ \t]*[a-z0-9A-Z]*>+[ \t]*$\\|[ \t]*$\\|"
1811                 "-- $\\|---+$\\|"
1812                 page-delimiter
1813                 ;;!!! Uhm... shurely this can't be right?
1814                 "[> " (regexp-quote message-yank-prefix) "]+$"))
1815   (setq paragraph-separate paragraph-start)
1816   (make-local-variable 'message-reply-headers)
1817   (setq message-reply-headers nil)
1818   (make-local-variable 'message-user-agent)
1819   (make-local-variable 'message-post-method)
1820   (set (make-local-variable 'message-sent-message-via) nil)
1821   (set (make-local-variable 'message-checksum) nil)
1822   (make-local-variable 'message-parameter-alist)
1823   (setq message-parameter-alist
1824         (copy-sequence message-startup-parameter-alist))
1825   ;;(when (fboundp 'mail-hist-define-keys)
1826   ;;  (mail-hist-define-keys))
1827   (when (string-match "XEmacs\\|Lucid" emacs-version)
1828     (message-setup-toolbar))
1829   (easy-menu-add message-mode-menu message-mode-map)
1830   (easy-menu-add message-mode-field-menu message-mode-map)
1831   ;; Allow mail alias things.
1832   (when (eq message-mail-alias-type 'abbrev)
1833     (if (fboundp 'mail-abbrevs-setup)
1834         (mail-abbrevs-setup)
1835       (mail-aliases-setup)))
1836   (message-set-auto-save-file-name)
1837   (unless (string-match "XEmacs" emacs-version)
1838     (set (make-local-variable 'font-lock-defaults)
1839          '((message-font-lock-keywords
1840             message-font-lock-keywords-1
1841             message-font-lock-keywords-2)
1842            nil nil nil nil
1843            (font-lock-mark-block-function . mark-paragraph))))
1844   (set (make-local-variable 'message-font-lock-last-position) nil)
1845   (make-local-variable 'adaptive-fill-regexp)
1846   (setq adaptive-fill-regexp
1847         (concat "[ \t]*[-a-z0-9A-Z]*\\(>[ \t]*\\)+[ \t]*\\|"
1848                 adaptive-fill-regexp))
1849   (unless (boundp 'adaptive-fill-first-line-regexp)
1850     (setq adaptive-fill-first-line-regexp nil))
1851   (make-local-variable 'adaptive-fill-first-line-regexp)
1852   (setq adaptive-fill-first-line-regexp
1853         (concat "[ \t]*[-a-z0-9A-Z]*\\(>[ \t]*\\)+[ \t]*\\|"
1854                 adaptive-fill-first-line-regexp))
1855   (make-local-variable 'indent-tabs-mode) ;Turn off tabs for indentation.
1856   (setq indent-tabs-mode nil)
1857   (run-hooks 'text-mode-hook 'message-mode-hook))
1858
1859 \f
1860
1861 ;;;
1862 ;;; Message mode commands
1863 ;;;
1864
1865 ;;; Movement commands
1866
1867 (defun message-goto-to ()
1868   "Move point to the To header."
1869   (interactive)
1870   (message-position-on-field "To"))
1871
1872 (defun message-goto-subject ()
1873   "Move point to the Subject header."
1874   (interactive)
1875   (message-position-on-field "Subject"))
1876
1877 (defun message-goto-cc ()
1878   "Move point to the Cc header."
1879   (interactive)
1880   (message-position-on-field "Cc" "To"))
1881
1882 (defun message-goto-bcc ()
1883   "Move point to the Bcc  header."
1884   (interactive)
1885   (message-position-on-field "Bcc" "Cc" "To"))
1886
1887 (defun message-goto-fcc ()
1888   "Move point to the Fcc header."
1889   (interactive)
1890   (message-position-on-field "Fcc" "To" "Newsgroups"))
1891
1892 (defun message-goto-reply-to ()
1893   "Move point to the Reply-To header."
1894   (interactive)
1895   (message-position-on-field "Reply-To" "Subject"))
1896
1897 (defun message-goto-mail-reply-to ()
1898   "Move point to the Mail-Reply-To header."
1899   (interactive)
1900   (message-position-on-field "Mail-Reply-To" "Subject"))
1901
1902 (defun message-goto-mail-followup-to ()
1903   "Move point to the Mail-Followup-To header.  If the header is newly created
1904 and To field contains only one address, the address is inserted in default."
1905   (interactive)
1906   (unless (message-position-on-field "Mail-Followup-To" "Subject")
1907     (let ((start (point))
1908           addresses)
1909       (save-restriction
1910         (message-narrow-to-headers)
1911         (setq addresses (split-string (mail-strip-quoted-names
1912                                        (or (std11-fetch-field "to") ""))
1913                                       "[ \f\t\n\r\v,]+"))
1914         (when (eq 1 (length addresses))
1915           (goto-char start)
1916           (insert (car addresses))
1917           (goto-char start))))))
1918
1919 (defun message-goto-mail-copies-to ()
1920   "Move point to the Mail-Copies-To header.  If the header is newly created,
1921 a string \"never\" is inserted in default."
1922   (interactive)
1923   (unless (message-position-on-field "Mail-Copies-To" "Subject")
1924     (insert "never")
1925     (backward-char 5)))
1926
1927 (defun message-goto-newsgroups ()
1928   "Move point to the Newsgroups header."
1929   (interactive)
1930   (message-position-on-field "Newsgroups"))
1931
1932 (defun message-goto-distribution ()
1933   "Move point to the Distribution header."
1934   (interactive)
1935   (message-position-on-field "Distribution"))
1936
1937 (defun message-goto-followup-to ()
1938   "Move point to the Followup-To header."
1939   (interactive)
1940   (message-position-on-field "Followup-To" "Newsgroups"))
1941
1942 (defun message-goto-keywords ()
1943   "Move point to the Keywords header."
1944   (interactive)
1945   (message-position-on-field "Keywords" "Subject"))
1946
1947 (defun message-goto-summary ()
1948   "Move point to the Summary header."
1949   (interactive)
1950   (message-position-on-field "Summary" "Subject"))
1951
1952 (defun message-goto-body ()
1953   "Move point to the beginning of the message body."
1954   (interactive)
1955   (if (looking-at "[ \t]*\n") (expand-abbrev))
1956   (goto-char (point-min))
1957   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
1958       (search-forward "\n\n" nil t)))
1959
1960 (defun message-goto-eoh ()
1961   "Move point to the end of the headers."
1962   (interactive)
1963   (message-goto-body)
1964   (forward-line -1))
1965
1966 (defun message-goto-signature ()
1967   "Move point to the beginning of the message signature.
1968 If there is no signature in the article, go to the end and
1969 return nil."
1970   (interactive)
1971   (goto-char (point-min))
1972   (if (re-search-forward message-signature-separator nil t)
1973       (forward-line 1)
1974     (goto-char (point-max))
1975     nil))
1976
1977 \f
1978
1979 (defun message-insert-to (&optional force)
1980   "Insert a To header that points to the author of the article being replied to.
1981 If the original author requested not to be sent mail, the function signals
1982 an error.
1983 With the prefix argument FORCE, insert the header anyway."
1984   (interactive "P")
1985   (let ((co (message-fetch-reply-field "mail-copies-to")))
1986     (when (and (null force)
1987                co
1988                (or (equal (downcase co) "never")
1989                    (equal (downcase co) "nobody")))
1990       (error "The user has requested not to have copies sent via mail")))
1991   (when (and (message-position-on-field "To")
1992              (mail-fetch-field "to")
1993              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1994     (insert ", "))
1995   (insert (or (message-fetch-reply-field "reply-to")
1996               (message-fetch-reply-field "from") "")))
1997
1998 (defun message-insert-newsgroups ()
1999   "Insert the Newsgroups header from the article being replied to."
2000   (interactive)
2001   (when (and (message-position-on-field "Newsgroups")
2002              (mail-fetch-field "newsgroups")
2003              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
2004     (insert ","))
2005   (insert (or (message-fetch-reply-field "newsgroups") "")))
2006
2007 \f
2008
2009 ;;; Various commands
2010
2011 (defun message-delete-not-region (beg end)
2012   "Delete everything in the body of the current message that is outside of the region."
2013   (interactive "r")
2014   (save-excursion
2015     (goto-char end)
2016     (delete-region (point) (if (not (message-goto-signature))
2017                                (point)
2018                              (forward-line -2)
2019                              (point)))
2020     (insert "\n")
2021     (goto-char beg)
2022     (delete-region beg (progn (message-goto-body)
2023                               (forward-line 2)
2024                               (point))))
2025   (when (message-goto-signature)
2026     (forward-line -2)))
2027
2028 (defun message-kill-to-signature ()
2029   "Deletes all text up to the signature."
2030   (interactive)
2031   (let ((point (point)))
2032     (message-goto-signature)
2033     (unless (eobp)
2034       (forward-line -2))
2035     (kill-region point (point))
2036     (unless (bolp)
2037       (insert "\n"))))
2038
2039 (defun message-newline-and-reformat ()
2040   "Insert four newlines, and then reformat if inside quoted text."
2041   (interactive)
2042   (let ((prefix "[]>»|:}+ \t]*")
2043         (supercite-thing "[-._a-zA-Z0-9]*[>]+[ \t]*")
2044         quoted point)
2045     (unless (bolp)
2046       (save-excursion
2047         (beginning-of-line)
2048         (when (looking-at (concat prefix
2049                                   supercite-thing))
2050           (setq quoted (match-string 0))))
2051       (insert "\n"))
2052     (setq point (point))
2053     (insert "\n\n\n")
2054     (delete-region (point) (re-search-forward "[ \t]*"))
2055     (when quoted
2056       (insert quoted))
2057     (fill-paragraph nil)
2058     (goto-char point)
2059     (forward-line 1)))
2060
2061 (defun message-insert-signature (&optional force)
2062   "Insert a signature.  See documentation for the `message-signature' variable."
2063   (interactive (list 0))
2064   (let* ((signature
2065           (cond
2066            ((and (null message-signature)
2067                  (eq force 0))
2068             (save-excursion
2069               (goto-char (point-max))
2070               (not (re-search-backward message-signature-separator nil t))))
2071            ((and (null message-signature)
2072                  force)
2073             t)
2074            ((message-functionp message-signature)
2075             (funcall message-signature))
2076            ((listp message-signature)
2077             (eval message-signature))
2078            (t message-signature)))
2079          (signature
2080           (cond ((stringp signature)
2081                  signature)
2082                 ((and (eq t signature)
2083                       message-signature-file
2084                       (file-exists-p message-signature-file))
2085                  signature))))
2086     (when signature
2087       (goto-char (point-max))
2088       ;; Insert the signature.
2089       (unless (bolp)
2090         (insert "\n"))
2091       (insert "\n-- \n")
2092       (if (eq signature t)
2093           (insert-file-contents message-signature-file)
2094         (insert signature))
2095       (goto-char (point-max))
2096       (or (bolp) (insert "\n")))))
2097
2098 (defun message-elide-region (b e)
2099   "Elide the text between point and mark.
2100 An ellipsis (from `message-elide-ellipsis') will be inserted where the
2101 text was killed."
2102   (interactive "r")
2103   (kill-region b e)
2104   (insert message-elide-ellipsis))
2105
2106 (defvar message-caesar-translation-table nil)
2107
2108 (defun message-caesar-region (b e &optional n)
2109   "Caesar rotation of region by N, default 13, for decrypting netnews."
2110   (interactive
2111    (list
2112     (min (point) (or (mark t) (point)))
2113     (max (point) (or (mark t) (point)))
2114     (when current-prefix-arg
2115       (prefix-numeric-value current-prefix-arg))))
2116
2117   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
2118   (unless (or (zerop n)                 ; no action needed for a rot of 0
2119               (= b e))                  ; no region to rotate
2120     ;; We build the table, if necessary.
2121     (when (or (not message-caesar-translation-table)
2122               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
2123         (setq message-caesar-translation-table
2124               (message-make-caesar-translation-table n)))
2125     ;; Then we translate the region.  Do it this way to retain
2126     ;; text properties.
2127     (while (< b e)
2128       (when (< (char-after b) 255)
2129         (subst-char-in-region
2130          b (1+ b) (char-after b)
2131          (aref message-caesar-translation-table (char-after b))))
2132       (incf b))))
2133
2134 (defun message-make-caesar-translation-table (n)
2135   "Create a rot table with offset N."
2136   (let ((i -1)
2137         (table (make-string 256 0)))
2138     (while (< (incf i) 256)
2139       (aset table i i))
2140     (concat
2141      (substring table 0 ?A)
2142      (substring table (+ ?A n) (+ ?A n (- 26 n)))
2143      (substring table ?A (+ ?A n))
2144      (substring table (+ ?A 26) ?a)
2145      (substring table (+ ?a n) (+ ?a n (- 26 n)))
2146      (substring table ?a (+ ?a n))
2147      (substring table (+ ?a 26) 255))))
2148
2149 (defun message-caesar-buffer-body (&optional rotnum)
2150   "Caesar rotates all letters in the current buffer by 13 places.
2151 Used to encode/decode possiblyun offensive messages (commonly in net.jokes).
2152 With prefix arg, specifies the number of places to rotate each letter forward.
2153 Mail and USENET news headers are not rotated."
2154   (interactive (if current-prefix-arg
2155                    (list (prefix-numeric-value current-prefix-arg))
2156                  (list nil)))
2157   (save-excursion
2158     (save-restriction
2159       (when (message-goto-body)
2160         (narrow-to-region (point) (point-max)))
2161       (message-caesar-region (point-min) (point-max) rotnum))))
2162
2163 (defun message-pipe-buffer-body (program)
2164   "Pipe the message body in the current buffer through PROGRAM."
2165   (save-excursion
2166     (save-restriction
2167       (when (message-goto-body)
2168         (narrow-to-region (point) (point-max)))
2169       (let ((body (buffer-substring (point-min) (point-max))))
2170         (unless (equal 0 (call-process-region
2171                            (point-min) (point-max) program t t))
2172             (insert body)
2173             (message "%s failed" program))))))
2174
2175 (defun message-rename-buffer (&optional enter-string)
2176   "Rename the *message* buffer to \"*message* RECIPIENT\".
2177 If the function is run with a prefix, it will ask for a new buffer
2178 name, rather than giving an automatic name."
2179   (interactive "Pbuffer name: ")
2180   (save-excursion
2181     (save-restriction
2182       (goto-char (point-min))
2183       (narrow-to-region (point)
2184                         (search-forward mail-header-separator nil 'end))
2185       (let* ((mail-to (or
2186                        (if (message-news-p) (message-fetch-field "Newsgroups")
2187                          (message-fetch-field "To"))
2188                        ""))
2189              (mail-trimmed-to
2190               (if (string-match "," mail-to)
2191                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
2192                 mail-to))
2193              (name-default (concat "*message* " mail-trimmed-to))
2194              (name (if enter-string
2195                        (read-string "New buffer name: " name-default)
2196                      name-default)))
2197         (rename-buffer name t)))))
2198
2199 (defun message-fill-yanked-message (&optional justifyp)
2200   "Fill the paragraphs of a message yanked into this one.
2201 Numeric argument means justify as well."
2202   (interactive "P")
2203   (save-excursion
2204     (goto-char (point-min))
2205     (search-forward (concat "\n" mail-header-separator "\n") nil t)
2206     (let ((fill-prefix message-yank-prefix))
2207       (fill-individual-paragraphs (point) (point-max) justifyp))))
2208
2209 (defun message-indent-citation ()
2210   "Modify text just inserted from a message to be cited.
2211 The inserted text should be the region.
2212 When this function returns, the region is again around the modified text.
2213
2214 Normally, indent each nonblank line `message-indentation-spaces' spaces.
2215 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
2216   (let ((start (point)))
2217     ;; Remove unwanted headers.
2218     (when message-ignored-cited-headers
2219       (let (all-removed)
2220         (save-restriction
2221           (narrow-to-region
2222            (goto-char start)
2223            (if (search-forward "\n\n" nil t)
2224                (1- (point))
2225              (point)))
2226           (message-remove-header message-ignored-cited-headers t)
2227           (when (= (point-min) (point-max))
2228             (setq all-removed t))
2229           (goto-char (point-max)))
2230         (if all-removed
2231             (goto-char start)
2232           (forward-line 1))))
2233     ;; Delete blank lines at the start of the buffer.
2234     (while (and (point-min)
2235                 (eolp)
2236                 (not (eobp)))
2237       (message-delete-line))
2238     ;; Delete blank lines at the end of the buffer.
2239     (goto-char (point-max))
2240     (unless (eolp)
2241       (insert "\n"))
2242     (while (and (zerop (forward-line -1))
2243                 (looking-at "$"))
2244       (message-delete-line))
2245     ;; Do the indentation.
2246     (if (null message-yank-prefix)
2247         (indent-rigidly start (mark t) message-indentation-spaces)
2248       (save-excursion
2249         (goto-char start)
2250         (while (< (point) (mark t))
2251           (insert message-yank-prefix)
2252           (forward-line 1))))
2253     (goto-char start)))
2254
2255 (defun message-list-references (refs-list &rest refs-strs)
2256   "Add `Message-ID's which appear in REFS-STRS but not in REFS-LIST,
2257 to REFS-LIST."
2258   (let (refs ref id saved-id)
2259     (when (and refs-list
2260                (integerp message-list-references-add-position))
2261       (let ((pos message-list-references-add-position))
2262         (while (and refs-list
2263                     (> pos 0))
2264           (setq saved-id (cons (car refs-list) saved-id)
2265                 refs-list (cdr refs-list)
2266                 pos (1- pos)))))
2267     (while refs-strs
2268       (setq refs (car refs-strs)
2269             refs-strs (cdr refs-strs))
2270       (when refs
2271         (setq refs (std11-parse-msg-ids (std11-lexical-analyze refs)))
2272         (while refs
2273           (setq ref (car refs)
2274                 refs (cdr refs))
2275           (when (eq (car ref) 'msg-id)
2276             (setq id (concat "<"
2277                              (mapconcat
2278                               (function (lambda (p) (cdr p)))
2279                               (cdr ref) "")
2280                              ">"))
2281             (or (member id refs-list)
2282                 (push id refs-list))))))
2283     (while saved-id
2284       (setq refs-list (cons (car saved-id) refs-list)
2285             saved-id (cdr saved-id)))
2286     refs-list))
2287
2288 (defvar gnus-article-copy)
2289 (defun message-yank-original (&optional arg)
2290   "Insert the message being replied to, if any.
2291 Puts point before the text and mark after.
2292 Normally indents each nonblank line ARG spaces (default 3).  However,
2293 if `message-yank-prefix' is non-nil, insert that prefix on each line.
2294
2295 This function uses `message-cite-function' to do the actual citing.
2296
2297 Just \\[universal-argument] as argument means don't indent, insert no
2298 prefix, and don't delete any headers.
2299
2300 In addition, if `message-yank-add-new-references' is non-nil and this
2301 command is called interactively, new IDs from the yanked article will
2302 be added to \"References\" field.
2303 \(See also `message-yank-add-new-references'.)"
2304   (interactive "P")
2305   (let ((modified (buffer-modified-p))
2306         (buffer (message-eval-parameter message-reply-buffer))
2307         start end refs)
2308     (when (and buffer
2309                message-cite-function)
2310       (delete-windows-on buffer t)
2311       (insert-buffer buffer) ; mark will be set at the end of article.
2312       (setq start (point)
2313             end (mark t))
2314
2315       ;; Add new IDs to References field.
2316       (when (and message-yank-add-new-references (interactive-p))
2317         (save-excursion
2318           (save-restriction
2319             (message-narrow-to-headers)
2320             (setq refs (message-list-references
2321                         nil
2322                         (message-fetch-field "References")))
2323             (widen)
2324             (narrow-to-region start end)
2325             (std11-narrow-to-header)
2326             (when (setq refs (message-list-references
2327                               refs
2328                               (unless (eq message-yank-add-new-references
2329                                           'message-id-only)
2330                                 (or (message-fetch-field "References")
2331                                     (message-fetch-field "In-Reply-To")))
2332                               (message-fetch-field "Message-ID")))
2333               (widen)
2334               (message-narrow-to-headers)
2335               (goto-char (point-min))
2336               (let ((case-fold-search t))
2337                 (if (re-search-forward "^References:\\([\t ]+.+\n\\)+" nil t)
2338                     (replace-match "")
2339                   (goto-char (point-max))))
2340               (mail-header-format
2341                (list (or (assq 'References message-header-format-alist)
2342                          '(References . message-fill-references)))
2343                (list (cons 'References
2344                            (mapconcat 'identity (nreverse refs) " "))))
2345               (backward-delete-char 1)))))
2346
2347       (funcall message-cite-function)
2348       (message-exchange-point-and-mark)
2349       (unless (bolp)
2350         (insert ?\n))
2351       (unless modified
2352         (setq message-checksum (message-checksum))))))
2353
2354 (defun message-yank-buffer (buffer)
2355   "Insert BUFFER into the current buffer and quote it."
2356   (interactive "bYank buffer: ")
2357   (let ((message-reply-buffer buffer))
2358     (save-window-excursion
2359       (message-yank-original))))
2360
2361 (defun message-buffers ()
2362   "Return a list of active message buffers."
2363   (let (buffers)
2364     (save-excursion
2365       (dolist (buffer (buffer-list t))
2366         (set-buffer buffer)
2367         (when (and (eq major-mode 'message-mode)
2368                    (null message-sent-message-via))
2369           (push (buffer-name buffer) buffers))))
2370     (nreverse buffers)))
2371
2372 (defun message-cite-original-without-signature ()
2373   "Cite function in the standard Message manner."
2374   (let ((start (point))
2375         (end (mark t))
2376         (functions
2377          (when message-indent-citation-function
2378            (if (listp message-indent-citation-function)
2379                message-indent-citation-function
2380              (list message-indent-citation-function)))))
2381     (goto-char end)
2382     (when (re-search-backward message-signature-separator start t)
2383       ;; Also peel off any blank lines before the signature.
2384       (forward-line -1)
2385       (while (looking-at "^[ \t]*$")
2386         (forward-line -1))
2387       (forward-line 1)
2388       (delete-region (point) end))
2389     (goto-char start)
2390     (while functions
2391       (funcall (pop functions)))
2392     (when message-citation-line-function
2393       (unless (bolp)
2394         (insert "\n"))
2395       (funcall message-citation-line-function))))
2396
2397 (defvar mail-citation-hook)             ;Compiler directive
2398 (defun message-cite-original ()
2399   "Cite function in the standard Message manner."
2400   (if (and (boundp 'mail-citation-hook)
2401            mail-citation-hook)
2402       (run-hooks 'mail-citation-hook)
2403     (let ((start (point))
2404           (end (mark t))
2405           (functions
2406            (when message-indent-citation-function
2407              (if (listp message-indent-citation-function)
2408                  message-indent-citation-function
2409                (list message-indent-citation-function)))))
2410       (goto-char start)
2411       (while functions
2412         (funcall (pop functions)))
2413       (when message-citation-line-function
2414         (unless (bolp)
2415           (insert "\n"))
2416         (funcall message-citation-line-function)))))
2417
2418 (defun message-insert-citation-line ()
2419   "Function that inserts a simple citation line."
2420   (when message-reply-headers
2421     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
2422
2423 (defun message-position-on-field (header &rest afters)
2424   (let ((case-fold-search t))
2425     (save-restriction
2426       (narrow-to-region
2427        (goto-char (point-min))
2428        (progn
2429          (re-search-forward
2430           (concat "^" (regexp-quote mail-header-separator) "$"))
2431          (match-beginning 0)))
2432       (goto-char (point-min))
2433       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
2434           (progn
2435             (re-search-forward "^[^ \t]" nil 'move)
2436             (beginning-of-line)
2437             (skip-chars-backward "\n")
2438             t)
2439         (while (and afters
2440                     (not (re-search-forward
2441                           (concat "^" (regexp-quote (car afters)) ":")
2442                           nil t)))
2443           (pop afters))
2444         (when afters
2445           (re-search-forward "^[^ \t]" nil 'move)
2446           (beginning-of-line))
2447         (insert header ": \n")
2448         (forward-char -1)
2449         nil))))
2450
2451 (defun message-remove-signature ()
2452   "Remove the signature from the text between point and mark.
2453 The text will also be indented the normal way."
2454   (save-excursion
2455     (let ((start (point))
2456           mark)
2457       (if (not (re-search-forward message-signature-separator (mark t) t))
2458           ;; No signature here, so we just indent the cited text.
2459           (message-indent-citation)
2460         ;; Find the last non-empty line.
2461         (forward-line -1)
2462         (while (looking-at "[ \t]*$")
2463           (forward-line -1))
2464         (forward-line 1)
2465         (setq mark (set-marker (make-marker) (point)))
2466         (goto-char start)
2467         (message-indent-citation)
2468         ;; Enable undoing the deletion.
2469         (undo-boundary)
2470         (delete-region mark (mark t))
2471         (set-marker mark nil)))))
2472
2473 \f
2474
2475 ;;;
2476 ;;; Sending messages
2477 ;;;
2478
2479 ;; Avoid byte-compile warning.
2480 (defvar message-encoding-buffer nil)
2481 (defvar message-edit-buffer nil)
2482 (defvar message-mime-mode nil)
2483
2484 (defun message-send-and-exit (&optional arg)
2485   "Send message like `message-send', then, if no errors, exit from mail buffer."
2486   (interactive "P")
2487   (let ((buf (current-buffer))
2488         (actions message-exit-actions)
2489         (frame (selected-frame))
2490         (org-frame message-original-frame))
2491     (when (and (message-send arg)
2492                (buffer-name buf))
2493       (if message-kill-buffer-on-exit
2494           (kill-buffer buf)
2495         (bury-buffer buf)
2496         (when (eq buf (current-buffer))
2497           (message-bury buf)))
2498       (message-do-actions actions)
2499       (message-delete-frame frame org-frame)
2500       t)))
2501
2502 (defun message-dont-send ()
2503   "Don't send the message you have been editing."
2504   (interactive)
2505   (message-save-drafts)
2506   (let ((actions message-postpone-actions)
2507         (frame (selected-frame))
2508         (org-frame message-original-frame))
2509     (message-bury (current-buffer))
2510     (message-do-actions actions)
2511     (message-delete-frame frame org-frame)))
2512
2513 (defun message-kill-buffer ()
2514   "Kill the current buffer."
2515   (interactive)
2516   (when (or (not (buffer-modified-p))
2517             (eq t message-kill-buffer-query-function)
2518             (funcall message-kill-buffer-query-function
2519                      "The buffer modified; kill anyway? "))
2520     (let ((actions message-kill-actions)
2521           (frame (selected-frame))
2522           (org-frame message-original-frame))
2523       (setq buffer-file-name nil)
2524       (kill-buffer (current-buffer))
2525       (message-do-actions actions)
2526       (message-delete-frame frame org-frame)))
2527   (message ""))
2528
2529 (defun message-mimic-kill-buffer ()
2530   "Kill the current buffer with query."
2531   (interactive)
2532   (unless (eq 'message-mode major-mode)
2533     (error "%s must be invoked from a message buffer." this-command))
2534   (let ((command this-command)
2535         (bufname (read-buffer (format "Kill buffer: (default %s) "
2536                                       (buffer-name)))))
2537     (if (or (not bufname)
2538             (string-equal bufname "")
2539             (string-equal bufname (buffer-name)))
2540         (message-kill-buffer)
2541       (message "%s must be invoked only for the current buffer." command))))
2542
2543 (defun message-delete-frame (frame org-frame)
2544   "Delete frame for editing message."
2545   (when (and (or (static-if (featurep 'xemacs)
2546                      (device-on-window-system-p)
2547                    window-system)
2548                  (>= emacs-major-version 20))
2549              (or (and (eq message-delete-frame-on-exit t)
2550                       (select-frame frame)
2551                       (or (eq frame org-frame)
2552                           (prog1
2553                               (y-or-n-p "Delete this frame?")
2554                             (message ""))))
2555                  (and (eq message-delete-frame-on-exit 'ask)
2556                       (select-frame frame)
2557                       (prog1
2558                           (y-or-n-p "Delete this frame?")
2559                         (message "")))))
2560     (delete-frame frame)))
2561
2562 (defun message-bury (buffer)
2563   "Bury this mail buffer."
2564   (let ((newbuf (other-buffer buffer)))
2565     (bury-buffer buffer)
2566     (if (and (fboundp 'frame-parameters)
2567              (cdr (assq 'dedicated (frame-parameters)))
2568              (not (null (delq (selected-frame) (visible-frame-list)))))
2569         (delete-frame (selected-frame))
2570       (switch-to-buffer newbuf))))
2571
2572 (defun message-send (&optional arg)
2573   "Send the message in the current buffer.
2574 If `message-interactive' is non-nil, wait for success indication
2575 or error messages, and inform user.
2576 Otherwise any failure is reported in a message back to
2577 the user from the mailer."
2578   (interactive "P")
2579   ;; Disabled test.
2580   (when (or (buffer-modified-p)
2581             (message-check-element 'unchanged)
2582             (y-or-n-p "No changes in the buffer; really send? "))
2583     ;; Make it possible to undo the coming changes.
2584     (undo-boundary)
2585     (let ((inhibit-read-only t))
2586       (put-text-property (point-min) (point-max) 'read-only nil))
2587     (run-hooks 'message-send-hook)
2588     (message "Sending...")
2589     (let ((message-encoding-buffer
2590            (message-generate-new-buffer-clone-locals " message encoding"))
2591           (message-edit-buffer (current-buffer))
2592           (message-mime-mode mime-edit-mode-flag)
2593           (alist message-send-method-alist)
2594           (success t)
2595           elem sent)
2596       (save-excursion
2597         (set-buffer message-encoding-buffer)
2598         (erase-buffer)
2599         (insert-buffer message-edit-buffer)
2600         (funcall message-encode-function)
2601         (message-fix-before-sending)
2602         (while (and success
2603                     (setq elem (pop alist)))
2604           (when (or (not (funcall (cadr elem)))
2605                     (and (or (not (memq (car elem)
2606                                         message-sent-message-via))
2607                              (y-or-n-p
2608                               (format
2609                                "Already sent message via %s; resend? "
2610                                (car elem))))
2611                          (setq success (funcall (caddr elem) arg))))
2612             (setq sent t))))
2613       (unless (or sent (not success))
2614         (error "No methods specified to send by"))
2615       (prog1
2616           (when (and success sent)
2617             (message-do-fcc)
2618             (save-excursion
2619               (run-hooks 'message-sent-hook))
2620             (message "Sending...done")
2621             ;; Mark the buffer as unmodified and delete autosave.
2622             (set-buffer-modified-p nil)
2623             (delete-auto-save-file-if-necessary t)
2624             (message-disassociate-draft)
2625             ;; Delete other mail buffers and stuff.
2626             (message-do-send-housekeeping)
2627             (message-do-actions message-send-actions)
2628             ;; Return success.
2629             t)
2630         (kill-buffer message-encoding-buffer)))))
2631
2632 (defun message-send-via-mail (arg)
2633   "Send the current message via mail."
2634   (message-send-mail arg))
2635
2636 (defun message-send-via-news (arg)
2637   "Send the current message via news."
2638   (message-send-news arg))
2639
2640 (defmacro message-check (type &rest forms)
2641   "Eval FORMS if TYPE is to be checked."
2642   `(or (message-check-element ,type)
2643        (save-excursion
2644          ,@forms)))
2645
2646 (put 'message-check 'lisp-indent-function 1)
2647 (put 'message-check 'edebug-form-spec '(form body))
2648
2649 (defun message-fix-before-sending ()
2650   "Do various things to make the message nice before sending it."
2651   ;; Make sure there's a newline at the end of the message.
2652   (goto-char (point-max))
2653   (unless (bolp)
2654     (insert "\n"))
2655   ;; Delete all invisible text.
2656   (message-check 'invisible-text
2657     (when (text-property-any (point-min) (point-max) 'invisible t)
2658       (put-text-property (point-min) (point-max) 'invisible nil)
2659       (unless (yes-or-no-p
2660                "Invisible text found and made visible; continue posting? ")
2661         (error "Invisible text found and made visible")))))
2662
2663 (defun message-add-action (action &rest types)
2664   "Add ACTION to be performed when doing an exit of type TYPES."
2665   (let (var)
2666     (while types
2667       (set (setq var (intern (format "message-%s-actions" (pop types))))
2668            (nconc (symbol-value var) (list action))))))
2669
2670 (defun message-do-actions (actions)
2671   "Perform all actions in ACTIONS."
2672   ;; Now perform actions on successful sending.
2673   (while actions
2674     (ignore-errors
2675       (cond
2676        ;; A simple function.
2677        ((message-functionp (car actions))
2678         (funcall (car actions)))
2679        ;; Something to be evaled.
2680        (t
2681         (eval (car actions)))))
2682     (pop actions)))
2683
2684 (defsubst message-maybe-split-and-send-mail ()
2685   "Split a message if necessary, and send it via mail.
2686 Returns nil if sending succeeded, returns any string if sending failed.
2687 This sub function is for exclusive use of `message-send-mail'."
2688   (let ((mime-edit-split-ignored-field-regexp
2689          mime-edit-split-ignored-field-regexp)
2690         (case-fold-search t)
2691         failure)
2692     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
2693       (setq mime-edit-split-ignored-field-regexp
2694             (concat (substring mime-edit-split-ignored-field-regexp
2695                                0 (match-beginning 0))
2696                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
2697                     "_so_don't_rape_it!"
2698                     (substring mime-edit-split-ignored-field-regexp
2699                                (match-end 0)))))
2700     (setq failure
2701           (or
2702            (catch 'message-sending-mail-failure
2703              (mime-edit-maybe-split-and-send
2704               (function
2705                (lambda ()
2706                  (interactive)
2707                  (save-restriction
2708                    (std11-narrow-to-header mail-header-separator)
2709                    (goto-char (point-min))
2710                    (when (re-search-forward "^Message-ID:" nil t)
2711                      (delete-region (match-end 0) (std11-field-end))
2712                      (insert " " (message-make-message-id))))
2713                  (condition-case err
2714                      (funcall message-send-mail-function)
2715                    (error
2716                     (throw 'message-sending-mail-failure err))))))
2717              nil)
2718            (condition-case err
2719                (progn
2720                  (funcall message-send-mail-function)
2721                  nil)
2722              (error err))))
2723     (when failure
2724       (if (eq 'error (car failure))
2725           (cadr failure)
2726         (prin1-to-string failure)))))
2727
2728 (defun message-send-mail (&optional arg)
2729   (require 'mail-utils)
2730   (let ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2731         (case-fold-search nil)
2732         (news (message-news-p))
2733         failure)
2734     (save-restriction
2735       (message-narrow-to-headers)
2736       ;; Insert some headers.
2737       (let ((message-deletable-headers
2738              (if news nil message-deletable-headers)))
2739         (message-generate-headers message-required-mail-headers))
2740       ;; Let the user do all of the above.
2741       (run-hooks 'message-header-hook))
2742     (if (not (message-check-mail-syntax))
2743         (progn
2744           (message "")
2745           nil)
2746       (unwind-protect
2747           (save-excursion
2748             (set-buffer tembuf)
2749             (erase-buffer)
2750             (insert-buffer message-encoding-buffer)
2751             ;; Remove some headers.
2752             (save-restriction
2753               (message-narrow-to-headers)
2754 ;; We Semi-gnus people have no use for it.
2755 ;;            ;; We (re)generate the Lines header.
2756 ;;            (when (memq 'Lines message-required-mail-headers)
2757 ;;              (message-generate-headers '(Lines)))
2758               ;; Remove some headers.
2759               (message-remove-header message-ignored-mail-headers t))
2760             (goto-char (point-max))
2761             ;; require one newline at the end.
2762             (or (= (preceding-char) ?\n)
2763                 (insert ?\n))
2764             (when (and news
2765                        (or (message-fetch-field "cc")
2766                            (message-fetch-field "to")))
2767               (message-insert-courtesy-copy))
2768             (setq failure (message-maybe-split-and-send-mail)))
2769         (kill-buffer tembuf))
2770       (set-buffer message-edit-buffer)
2771       (if failure
2772           (progn
2773             (message "Couldn't send message via mail: %s" failure)
2774             nil)
2775         (push 'mail message-sent-message-via)))))
2776
2777 (defun message-send-mail-with-sendmail ()
2778   "Send off the prepared buffer with sendmail."
2779   (let ((errbuf (if message-interactive
2780                     (message-generate-new-buffer-clone-locals " sendmail errors")
2781                   0))
2782         resend-to-addresses delimline)
2783     (let ((case-fold-search t))
2784       (save-restriction
2785         (message-narrow-to-headers)
2786         (setq resend-to-addresses (message-fetch-field "resent-to")))
2787       ;; Change header-delimiter to be what sendmail expects.
2788       (goto-char (point-min))
2789       (re-search-forward
2790        (concat "^" (regexp-quote mail-header-separator) "\n"))
2791       (replace-match "\n")
2792       (backward-char 1)
2793       (setq delimline (point-marker))
2794       (run-hooks 'message-send-mail-hook)
2795       ;; Insert an extra newline if we need it to work around
2796       ;; Sun's bug that swallows newlines.
2797       (goto-char (1+ delimline))
2798       (when (eval message-mailer-swallows-blank-line)
2799         (newline))
2800       (when message-interactive
2801         (save-excursion
2802           (set-buffer errbuf)
2803           (erase-buffer))))
2804     (let ((default-directory "/"))
2805       (as-binary-process
2806        (apply 'call-process-region
2807               (append (list (point-min) (point-max)
2808                             (if (boundp 'sendmail-program)
2809                                 sendmail-program
2810                               "/usr/lib/sendmail")
2811                             nil errbuf nil "-oi")
2812                       ;; Always specify who from,
2813                       ;; since some systems have broken sendmails.
2814                       ;; But some systems are more broken with -f, so
2815                       ;; we'll let users override this.
2816                       (if (null message-sendmail-f-is-evil)
2817                           (list "-f"
2818                                 (if (null user-mail-address)
2819                                     (user-login-name)
2820                                   user-mail-address)))
2821                       ;; These mean "report errors by mail"
2822                       ;; and "deliver in background".
2823                       (if (null message-interactive) '("-oem" "-odb"))
2824                       ;; Get the addresses from the message
2825                       ;; unless this is a resend.
2826                       ;; We must not do that for a resend
2827                       ;; because we would find the original addresses.
2828                       ;; For a resend, include the specific addresses.
2829                       (if resend-to-addresses
2830                           (list resend-to-addresses)
2831                         '("-t"))))))
2832     (when message-interactive
2833       (save-excursion
2834         (set-buffer errbuf)
2835         (goto-char (point-min))
2836         (while (re-search-forward "\n\n* *" nil t)
2837           (replace-match "; "))
2838         (if (not (zerop (buffer-size)))
2839             (error "Sending...failed to %s"
2840                    (buffer-substring (point-min) (point-max)))))
2841       (when (bufferp errbuf)
2842         (kill-buffer errbuf)))))
2843
2844 (defun message-send-mail-with-qmail ()
2845   "Pass the prepared message buffer to qmail-inject.
2846 Refer to the documentation for the variable `message-send-mail-function'
2847 to find out how to use this."
2848   ;; replace the header delimiter with a blank line
2849   (goto-char (point-min))
2850   (re-search-forward
2851    (concat "^" (regexp-quote mail-header-separator) "\n"))
2852   (replace-match "\n")
2853   (backward-char 1)
2854   (run-hooks 'message-send-mail-hook)
2855   ;; send the message
2856   (case
2857       (as-binary-process
2858        (apply
2859         'call-process-region 1 (point-max) message-qmail-inject-program
2860         nil nil nil
2861         ;; qmail-inject's default behaviour is to look for addresses on the
2862         ;; command line; if there're none, it scans the headers.
2863         ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2864         ;;
2865         ;; in general, ALL of qmail-inject's defaults are perfect for simply
2866         ;; reading a formatted (i. e., at least a To: or Resent-To header)
2867         ;; message from stdin.
2868         ;;
2869         ;; qmail also has the advantage of not having been raped by
2870         ;; various vendors, so we don't have to allow for that, either --
2871         ;; compare this with message-send-mail-with-sendmail and weep
2872         ;; for sendmail's lost innocence.
2873         ;;
2874         ;; all this is way cool coz it lets us keep the arguments entirely
2875         ;; free for -inject-arguments -- a big win for the user and for us
2876         ;; since we don't have to play that double-guessing game and the user
2877         ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2878         message-qmail-inject-args))
2879     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2880     ;; we have to look at the retval instead
2881     (0 nil)
2882     (1   (error "qmail-inject reported permanent failure"))
2883     (111 (error "qmail-inject reported transient failure"))
2884     ;; should never happen
2885     (t   (error "qmail-inject reported unknown failure"))))
2886
2887 (defun message-send-mail-with-mh ()
2888   "Send the prepared message buffer with mh."
2889   (let ((mh-previous-window-config nil)
2890         (name (mh-new-draft-name)))
2891     (setq buffer-file-name name)
2892     ;; MH wants to generate these headers itself.
2893     (when message-mh-deletable-headers
2894       (let ((headers message-mh-deletable-headers))
2895         (while headers
2896           (goto-char (point-min))
2897           (and (re-search-forward
2898                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2899                (message-delete-line))
2900           (pop headers))))
2901     (run-hooks 'message-send-mail-hook)
2902     ;; Pass it on to mh.
2903     (mh-send-letter)))
2904
2905 (defun message-send-mail-with-smtp ()
2906   "Send off the prepared buffer with SMTP."
2907   (require 'smtp) ; XXX
2908   (let ((case-fold-search t)
2909         recipients)
2910     (save-restriction
2911       (message-narrow-to-headers)
2912       (setq recipients
2913             ;; XXX: Should be replaced by better one.
2914             (smtp-deduce-address-list (current-buffer)
2915                                       (point-min) (point-max)))
2916       ;; Remove BCC lines.
2917       (message-remove-header "bcc"))
2918     ;; replace the header delimiter with a blank line.
2919     (goto-char (point-min))
2920     (re-search-forward
2921      (concat "^" (regexp-quote mail-header-separator) "\n"))
2922     (replace-match "\n")
2923     (backward-char 1)
2924     (run-hooks 'message-send-mail-hook)
2925     (if recipients
2926         (let ((result (smtp-via-smtp user-mail-address
2927                                      recipients
2928                                      (current-buffer))))
2929           (unless (eq result t)
2930             (error "Sending failed; " result)))
2931       (error "Sending failed; no recipients"))))
2932
2933 (defsubst message-maybe-split-and-send-news (method)
2934   "Split a message if necessary, and send it via news.
2935 Returns nil if sending succeeded, returns t if sending failed.
2936 This sub function is for exclusive use of `message-send-news'."
2937   (let ((mime-edit-split-ignored-field-regexp
2938          mime-edit-split-ignored-field-regexp)
2939         (case-fold-search t))
2940     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
2941       (setq mime-edit-split-ignored-field-regexp
2942             (concat (substring mime-edit-split-ignored-field-regexp
2943                                0 (match-beginning 0))
2944                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
2945                     "_so_don't_rape_it!"
2946                     (substring mime-edit-split-ignored-field-regexp
2947                                (match-end 0)))))
2948     (or
2949      (catch 'message-sending-news-failure
2950        (mime-edit-maybe-split-and-send
2951         (function
2952          (lambda ()
2953            (interactive)
2954            (save-restriction
2955              (std11-narrow-to-header mail-header-separator)
2956              (goto-char (point-min))
2957              (when (re-search-forward "^Message-ID:" nil t)
2958                (delete-region (match-end 0) (std11-field-end))
2959                (insert " " (message-make-message-id))))
2960            (unless (funcall message-send-news-function method)
2961              (throw 'message-sending-news-failure t)))))
2962        nil)
2963      (not (funcall message-send-news-function method)))))
2964
2965 (defun message-send-news (&optional arg)
2966   (let ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2967         (case-fold-search nil)
2968         (method (if (message-functionp message-post-method)
2969                     (funcall message-post-method arg)
2970                   message-post-method))
2971         (message-syntax-checks
2972          (if arg
2973              (cons '(existing-newsgroups . disabled)
2974                    message-syntax-checks)
2975            message-syntax-checks))
2976         result)
2977     (save-restriction
2978       (message-narrow-to-headers)
2979       ;; Insert some headers.
2980       (message-generate-headers message-required-news-headers)
2981       ;; Let the user do all of the above.
2982       (run-hooks 'message-header-hook))
2983     (message-cleanup-headers)
2984     (if (not (message-check-news-syntax))
2985         nil
2986       (unwind-protect
2987           (save-excursion
2988             (set-buffer tembuf)
2989             (buffer-disable-undo)
2990             (erase-buffer)
2991             (insert-buffer message-encoding-buffer)
2992             ;; Remove some headers.
2993             (save-restriction
2994               (message-narrow-to-headers)
2995 ;; We Semi-gnus people have no use for it.
2996 ;;            ;; We (re)generate the Lines header.
2997 ;;            (when (memq 'Lines message-required-mail-headers)
2998 ;;              (message-generate-headers '(Lines)))
2999               ;; Remove some headers.
3000               (message-remove-header message-ignored-news-headers t))
3001             (goto-char (point-max))
3002             ;; require one newline at the end.
3003             (or (= (preceding-char) ?\n)
3004                 (insert ?\n))
3005             (setq result (message-maybe-split-and-send-news method)))
3006         (kill-buffer tembuf))
3007       (set-buffer message-edit-buffer)
3008       (if result
3009           (progn
3010             (message "Couldn't send message via news: %s"
3011                      (nnheader-get-report (car method)))
3012             nil)
3013         (push 'news message-sent-message-via)))))
3014
3015 ;; 1997-09-29 by MORIOKA Tomohiko
3016 (defun message-send-news-with-gnus (method)
3017   (let ((case-fold-search t))
3018     ;; Remove the delimiter.
3019     (goto-char (point-min))
3020     (re-search-forward
3021      (concat "^" (regexp-quote mail-header-separator) "\n"))
3022     (replace-match "\n")
3023     (backward-char 1)
3024     (run-hooks 'message-send-news-hook)
3025     (gnus-open-server method)
3026     (gnus-request-post method)
3027     ))
3028
3029 ;;;
3030 ;;; Header generation & syntax checking.
3031 ;;;
3032
3033 (defun message-check-element (type)
3034   "Returns non-nil if this type is not to be checked."
3035   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
3036       t
3037     (let ((able (assq type message-syntax-checks)))
3038       (and (consp able)
3039            (eq (cdr able) 'disabled)))))
3040
3041 (defun message-check-news-syntax ()
3042   "Check the syntax of the message."
3043   (save-excursion
3044     (save-restriction
3045       (widen)
3046       (and
3047        ;; We narrow to the headers and check them first.
3048        (save-excursion
3049          (save-restriction
3050            (message-narrow-to-headers)
3051            (message-check-news-header-syntax)))
3052        ;; Check the body.
3053        (save-excursion
3054          (set-buffer message-edit-buffer)
3055          (message-check-news-body-syntax))))))
3056
3057 (defun message-check-news-header-syntax ()
3058   (and
3059    ;; Check Newsgroups header.
3060    (message-check 'newsgroyps
3061      (let ((group (message-fetch-field "newsgroups")))
3062        (or
3063         (and group
3064              (not (string-match "\\`[ \t]*\\'" group)))
3065         (ignore
3066          (message
3067           "The newsgroups field is empty or missing.  Posting is denied.")))))
3068    ;; Check the Subject header.
3069    (message-check 'subject
3070      (let* ((case-fold-search t)
3071             (subject (message-fetch-field "subject")))
3072        (or
3073         (and subject
3074              (not (string-match "\\`[ \t]*\\'" subject)))
3075         (ignore
3076          (message
3077           "The subject field is empty or missing.  Posting is denied.")))))
3078    ;; Check for commands in Subject.
3079    (message-check 'subject-cmsg
3080      (if (string-match "^cmsg " (message-fetch-field "subject"))
3081          (y-or-n-p
3082           "The control code \"cmsg\" is in the subject.  Really post? ")
3083        t))
3084    ;; Check for multiple identical headers.
3085    (message-check 'multiple-headers
3086      (let (found)
3087        (while (and (not found)
3088                    (re-search-forward "^[^ \t:]+: " nil t))
3089          (save-excursion
3090            (or (re-search-forward
3091                 (concat "^"
3092                         (regexp-quote
3093                          (setq found
3094                                (buffer-substring
3095                                 (match-beginning 0) (- (match-end 0) 2))))
3096                         ":")
3097                 nil t)
3098                (setq found nil))))
3099        (if found
3100            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
3101          t)))
3102    ;; Check for Version and Sendsys.
3103    (message-check 'sendsys
3104      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
3105          (y-or-n-p
3106           (format "The article contains a %s command.  Really post? "
3107                   (buffer-substring (match-beginning 0)
3108                                     (1- (match-end 0)))))
3109        t))
3110    ;; See whether we can shorten Followup-To.
3111    (message-check 'shorten-followup-to
3112      (let ((newsgroups (message-fetch-field "newsgroups"))
3113            (followup-to (message-fetch-field "followup-to"))
3114            to)
3115        (when (and newsgroups
3116                   (string-match "," newsgroups)
3117                   (not followup-to)
3118                   (not
3119                    (zerop
3120                     (length
3121                      (setq to (completing-read
3122                                "Followups to: (default all groups) "
3123                                (mapcar (lambda (g) (list g))
3124                                        (cons "poster"
3125                                              (message-tokenize-header
3126                                               newsgroups)))))))))
3127          (goto-char (point-min))
3128          (insert "Followup-To: " to "\n"))
3129        t))
3130    ;; Check "Shoot me".
3131    (message-check 'shoot
3132      (if (re-search-forward
3133           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
3134          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
3135        t))
3136    ;; Check for Approved.
3137    (message-check 'approved
3138      (if (re-search-forward "^Approved:" nil t)
3139          (y-or-n-p "The article contains an Approved header.  Really post? ")
3140        t))
3141    ;; Check the Message-ID header.
3142    (message-check 'message-id
3143      (let* ((case-fold-search t)
3144             (message-id (message-fetch-field "message-id" t)))
3145        (or (not message-id)
3146            ;; Is there an @ in the ID?
3147            (and (string-match "@" message-id)
3148                 ;; Is there a dot in the ID?
3149                 (string-match "@[^.]*\\." message-id)
3150                 ;; Does the ID end with a dot?
3151                 (not (string-match "\\.>" message-id)))
3152            (y-or-n-p
3153             (format "The Message-ID looks strange: \"%s\".  Really post? "
3154                     message-id)))))
3155    ;; Check the Newsgroups & Followup-To headers.
3156    (message-check 'existing-newsgroups
3157      (let* ((case-fold-search t)
3158             (newsgroups (message-fetch-field "newsgroups"))
3159             (followup-to (message-fetch-field "followup-to"))
3160             (groups (message-tokenize-header
3161                      (if followup-to
3162                          (concat newsgroups "," followup-to)
3163                        newsgroups)))
3164             (hashtb (and (boundp 'gnus-active-hashtb)
3165                          gnus-active-hashtb))
3166             errors)
3167        (if (or (not hashtb)
3168                (not (boundp 'gnus-read-active-file))
3169                (not gnus-read-active-file)
3170                (eq gnus-read-active-file 'some))
3171            t
3172          (while groups
3173            (when (and (not (boundp (intern (car groups) hashtb)))
3174                       (not (equal (car groups) "poster")))
3175              (push (car groups) errors))
3176            (pop groups))
3177          (if (not errors)
3178              t
3179            (y-or-n-p
3180             (format
3181              "Really post to %s unknown group%s: %s "
3182              (if (= (length errors) 1) "this" "these")
3183              (if (= (length errors) 1) "" "s")
3184              (mapconcat 'identity errors ", ")))))))
3185    ;; Check the Newsgroups & Followup-To headers for syntax errors.
3186    (message-check 'valid-newsgroups
3187      (let ((case-fold-search t)
3188            (headers '("Newsgroups" "Followup-To"))
3189            header error)
3190        (while (and headers (not error))
3191          (when (setq header (mail-fetch-field (car headers)))
3192            (if (or
3193                 (not
3194                  (string-match
3195                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
3196                   header))
3197                 (memq
3198                  nil (mapcar
3199                       (lambda (g)
3200                         (not (string-match "\\.\\'\\|\\.\\." g)))
3201                       (message-tokenize-header header ","))))
3202                (setq error t)))
3203          (unless error
3204            (pop headers)))
3205        (if (not error)
3206            t
3207          (y-or-n-p
3208           (format "The %s header looks odd: \"%s\".  Really post? "
3209                   (car headers) header)))))
3210    (message-check 'repeated-newsgroups
3211      (let ((case-fold-search t)
3212            (headers '("Newsgroups" "Followup-To"))
3213            header error groups group)
3214        (while (and headers
3215                    (not error))
3216          (when (setq header (mail-fetch-field (pop headers)))
3217            (setq groups (message-tokenize-header header ","))
3218            (while (setq group (pop groups))
3219              (when (member group groups)
3220                (setq error group
3221                      groups nil)))))
3222        (if (not error)
3223            t
3224          (y-or-n-p
3225           (format "Group %s is repeated in headers.  Really post? " error)))))
3226    ;; Check the From header.
3227    (message-check 'from
3228      (let* ((case-fold-search t)
3229             (from (message-fetch-field "from"))
3230             ad)
3231        (cond
3232         ((not from)
3233          (message "There is no From line.  Posting is denied.")
3234          nil)
3235         ((or (not (string-match
3236                    "@[^\\.]*\\."
3237                    (setq ad (nth 1 (mail-extract-address-components
3238                                     from))))) ;larsi@ifi
3239              (string-match "\\.\\." ad) ;larsi@ifi..uio
3240              (string-match "@\\." ad)   ;larsi@.ifi.uio
3241              (string-match "\\.$" ad)   ;larsi@ifi.uio.
3242              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
3243              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
3244          (message
3245           "Denied posting -- the From looks strange: \"%s\"." from)
3246          nil)
3247         (t t))))))
3248
3249 (defun message-check-news-body-syntax ()
3250   (and
3251    ;; Check for long lines.
3252    (message-check 'long-lines
3253      (goto-char (point-min))
3254      (re-search-forward
3255       (concat "^" (regexp-quote mail-header-separator) "$"))
3256      (while (and
3257              (progn
3258                (end-of-line)
3259                (< (current-column) 80))
3260              (zerop (forward-line 1))))
3261      (or (bolp)
3262          (eobp)
3263          (y-or-n-p
3264           "You have lines longer than 79 characters.  Really post? ")))
3265    ;; Check whether the article is empty.
3266    (message-check 'empty
3267      (goto-char (point-min))
3268      (re-search-forward
3269       (concat "^" (regexp-quote mail-header-separator) "$"))
3270      (forward-line 1)
3271      (let ((b (point)))
3272        (goto-char (point-max))
3273        (re-search-backward message-signature-separator nil t)
3274        (beginning-of-line)
3275        (or (re-search-backward "[^ \n\t]" b t)
3276            (y-or-n-p "Empty article.  Really post? "))))
3277    ;; Check for control characters.
3278    (message-check 'control-chars
3279      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
3280          (y-or-n-p
3281           "The article contains control characters.  Really post? ")
3282        t))
3283    ;; Check 8bit characters.
3284    (message-check '8bit
3285      (message-check-8bit))
3286    ;; Check excessive size.
3287    (message-check 'size
3288      (if (> (buffer-size) 60000)
3289          (y-or-n-p
3290           (format "The article is %d octets long.  Really post? "
3291                   (buffer-size)))
3292        t))
3293    ;; Check whether any new text has been added.
3294    (message-check 'new-text
3295      (or
3296       (not message-checksum)
3297       (not (eq (message-checksum) message-checksum))
3298       (y-or-n-p
3299        "It looks like no new text has been added.  Really post? ")))
3300    ;; Check the length of the signature.
3301    (message-check 'signature
3302      (goto-char (point-max))
3303      (if (> (count-lines (point) (point-max)) 5)
3304          (y-or-n-p
3305           (format
3306            "Your .sig is %d lines; it should be max 4.  Really post? "
3307            (1- (count-lines (point) (point-max)))))
3308        t))))
3309
3310 (defun message-check-mail-syntax ()
3311   "Check the syntax of the message."
3312   (save-excursion
3313     (save-restriction
3314       (widen)
3315       (and
3316        ;; We narrow to the headers and check them first.
3317        (save-excursion
3318          (save-restriction
3319            (message-narrow-to-headers)
3320            (message-check-mail-header-syntax)))
3321        ;; Check the body.
3322        (save-excursion
3323          (set-buffer message-edit-buffer)
3324          (message-check-mail-body-syntax))))))
3325
3326 (defun message-check-mail-header-syntax ()
3327   t)
3328
3329 (defun message-check-mail-body-syntax ()
3330   (and
3331    ;; Check 8bit characters.
3332    (message-check '8bit
3333      (message-check-8bit)
3334      )))
3335
3336 (defun message-check-8bit ()
3337   "Check the article contains 8bit characters."
3338   (save-excursion
3339     (set-buffer message-encoding-buffer)
3340     (message-narrow-to-headers)
3341     (let* ((case-fold-search t)
3342            (field-value (message-fetch-field "content-transfer-encoding")))
3343       (if (and field-value
3344                (member (downcase field-value) message-8bit-encoding-list))
3345           t
3346         (widen)
3347         (set-buffer (get-buffer-create " message syntax"))
3348         (erase-buffer)
3349         (goto-char (point-min))
3350         (set-buffer-multibyte nil)
3351         (insert-buffer message-encoding-buffer)
3352         (goto-char (point-min))
3353         (if (re-search-forward "[^\x00-\x7f]" nil t)
3354             (y-or-n-p
3355              "The article contains 8bit characters.  Really post? ")
3356           t)))))
3357
3358 (defun message-checksum ()
3359   "Return a \"checksum\" for the current buffer."
3360   (let ((sum 0))
3361     (save-excursion
3362       (goto-char (point-min))
3363       (re-search-forward
3364        (concat "^" (regexp-quote mail-header-separator) "$"))
3365       (while (not (eobp))
3366         (when (not (looking-at "[ \t\n]"))
3367           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
3368                             (char-after))))
3369         (forward-char 1)))
3370     sum))
3371
3372 (defun message-do-fcc ()
3373   "Process Fcc headers in the current buffer."
3374   (let ((case-fold-search t)
3375         (coding-system-for-write 'raw-text)
3376         (output-coding-system 'raw-text)
3377         list file)
3378     (save-excursion
3379       (set-buffer (get-buffer-create " *message temp*"))
3380       (erase-buffer)
3381       (insert-buffer-substring message-encoding-buffer)
3382       (save-restriction
3383         (message-narrow-to-headers)
3384         (while (setq file (message-fetch-field "fcc"))
3385           (push file list)
3386           (message-remove-header "fcc" nil t)))
3387       (goto-char (point-min))
3388       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
3389       (replace-match "" t t)
3390       ;; Process FCC operations.
3391       (while list
3392         (setq file (pop list))
3393         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
3394             ;; Pipe the article to the program in question.
3395             (call-process-region (point-min) (point-max) shell-file-name
3396                                  nil nil nil shell-command-switch
3397                                  (match-string 1 file))
3398           ;; Save the article.
3399           (setq file (expand-file-name file))
3400           (unless (file-exists-p (file-name-directory file))
3401             (make-directory (file-name-directory file) t))
3402           (if (and message-fcc-handler-function
3403                    (not (eq message-fcc-handler-function 'rmail-output)))
3404               (funcall message-fcc-handler-function file)
3405             (if (and (file-readable-p file) (mail-file-babyl-p file))
3406                 (rmail-output file 1 nil t)
3407               (let ((mail-use-rfc822 t))
3408                 (rmail-output file 1 t t))))))
3409       (kill-buffer (current-buffer)))))
3410
3411 (defun message-output (filename)
3412   "Append this article to Unix/babyl mail file.."
3413   (if (and (file-readable-p filename)
3414            (mail-file-babyl-p filename))
3415       (rmail-output-to-rmail-file filename t)
3416     (gnus-output-to-mail filename t)))
3417
3418 (defun message-cleanup-headers ()
3419   "Do various automatic cleanups of the headers."
3420   ;; Remove empty lines in the header.
3421   (save-restriction
3422     (message-narrow-to-headers)
3423     ;; Remove blank lines.
3424     (while (re-search-forward "^[ \t]*\n" nil t)
3425       (replace-match "" t t))
3426
3427     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
3428     ;; spaces to comma and eliminate spaces around commas.  Eliminate
3429     ;; embedded line breaks.
3430     (goto-char (point-min))
3431     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
3432       (save-restriction
3433         (narrow-to-region
3434          (point)
3435          (if (re-search-forward "^[^ \t]" nil t)
3436              (match-beginning 0)
3437            (forward-line 1)
3438            (point)))
3439         (goto-char (point-min))
3440         (while (re-search-forward "\n[ \t]+" nil t)
3441           (replace-match " " t t))      ;No line breaks (too confusing)
3442         (goto-char (point-min))
3443         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
3444           (replace-match "," t t))
3445         (goto-char (point-min))
3446         ;; Remove trailing commas.
3447         (when (re-search-forward ",+$" nil t)
3448           (replace-match "" t t))))))
3449
3450 (defun message-make-date (&optional now)
3451   "Make a valid data header.
3452 If NOW, use that time instead."
3453   (let* ((now (or now (current-time)))
3454          (zone (nth 8 (decode-time now)))
3455          (sign "+"))
3456     (when (< zone 0)
3457       (setq sign "-")
3458       (setq zone (- zone)))
3459     (concat
3460      (format-time-string "%d" now)
3461      ;; The month name of the %b spec is locale-specific.  Pfff.
3462      (format " %s "
3463              (capitalize (car (rassoc (nth 4 (decode-time now))
3464                                       parse-time-months))))
3465      (format-time-string "%Y %H:%M:%S " now)
3466      ;; We do all of this because XEmacs doesn't have the %z spec.
3467      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
3468
3469 (defun message-make-followup-subject (subject)
3470   "Make a followup Subject."
3471   (cond
3472    ((and (eq message-use-subject-re 'guess)
3473          (string-match message-subject-encoded-re-regexp subject))
3474     subject)
3475    (message-use-subject-re
3476     (concat "Re: " (message-strip-subject-re subject)))
3477    (t subject)))
3478
3479 (defun message-make-message-id ()
3480   "Make a unique Message-ID."
3481   (concat "<" (message-unique-id)
3482           (let ((psubject (save-excursion (message-fetch-field "subject")))
3483                 (psupersedes
3484                  (save-excursion (message-fetch-field "supersedes"))))
3485             (if (or
3486                  (and message-reply-headers
3487                       (mail-header-references message-reply-headers)
3488                       (mail-header-subject message-reply-headers)
3489                       psubject
3490                       (mail-header-subject message-reply-headers)
3491                       (not (string=
3492                             (message-strip-subject-re
3493                              (mail-header-subject message-reply-headers))
3494                             (message-strip-subject-re psubject))))
3495                  (and psupersedes
3496                       (string-match "_-_@" psupersedes)))
3497                 "_-_" ""))
3498           "@" (message-make-fqdn) ">"))
3499
3500 (defvar message-unique-id-char nil)
3501
3502 ;; If you ever change this function, make sure the new version
3503 ;; cannot generate IDs that the old version could.
3504 ;; You might for example insert a "." somewhere (not next to another dot
3505 ;; or string boundary), or modify the "fsf" string.
3506 (defun message-unique-id ()
3507   ;; Don't use microseconds from (current-time), they may be unsupported.
3508   ;; Instead we use this randomly inited counter.
3509   (setq message-unique-id-char
3510         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
3511            ;; (current-time) returns 16-bit ints,
3512            ;; and 2^16*25 just fits into 4 digits i base 36.
3513            (* 25 25)))
3514   (let ((tm (current-time)))
3515     (concat
3516      (if (memq system-type '(ms-dos emx vax-vms))
3517          (let ((user (downcase (user-login-name))))
3518            (while (string-match "[^a-z0-9_]" user)
3519              (aset user (match-beginning 0) ?_))
3520            user)
3521        (message-number-base36 (user-uid) -1))
3522      (message-number-base36 (+ (car   tm)
3523                                (lsh (% message-unique-id-char 25) 16)) 4)
3524      (message-number-base36 (+ (nth 1 tm)
3525                                (lsh (/ message-unique-id-char 25) 16)) 4)
3526      ;; Append the newsreader name, because while the generated
3527      ;; ID is unique to this newsreader, other newsreaders might
3528      ;; otherwise generate the same ID via another algorithm.
3529      ".fsf")))
3530
3531 (defun message-number-base36 (num len)
3532   (if (if (< len 0)
3533           (<= num 0)
3534         (= len 0))
3535       ""
3536     (concat (message-number-base36 (/ num 36) (1- len))
3537             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
3538                                   (% num 36))))))
3539
3540 (defun message-make-organization ()
3541   "Make an Organization header."
3542   (let* ((organization
3543           (when message-user-organization
3544                 (if (message-functionp message-user-organization)
3545                     (funcall message-user-organization)
3546                   message-user-organization))))
3547     (save-excursion
3548       (message-set-work-buffer)
3549       (cond ((stringp organization)
3550              (insert organization))
3551             ((and (eq t organization)
3552                   message-user-organization-file
3553                   (file-exists-p message-user-organization-file))
3554              (insert-file-contents message-user-organization-file)))
3555       (goto-char (point-min))
3556       (while (re-search-forward "[\t\n]+" nil t)
3557         (replace-match "" t t))
3558       (unless (zerop (buffer-size))
3559         (buffer-string)))))
3560
3561 (defun message-make-lines ()
3562   "Count the number of lines and return numeric string."
3563   (save-excursion
3564     (save-restriction
3565       (widen)
3566       (goto-char (point-min))
3567       (re-search-forward
3568        (concat "^" (regexp-quote mail-header-separator) "$"))
3569       (forward-line 1)
3570       (int-to-string (count-lines (point) (point-max))))))
3571
3572 (defun message-make-in-reply-to ()
3573   "Return the In-Reply-To header for this message."
3574   (when message-reply-headers
3575     (let ((mid (mail-header-message-id message-reply-headers))
3576           (from (mail-header-from message-reply-headers))
3577           (date (mail-header-date message-reply-headers)))
3578       (when mid
3579         (concat mid
3580                 (when from
3581                   (let ((pair (std11-extract-address-components from)))
3582                     (concat "\n ("
3583                             (or (car pair) (cadr pair))
3584                             "'s message of \""
3585                             (if (or (not date) (string= date ""))
3586                                 "(unknown date)" date)
3587                             "\")"))))))))
3588
3589 (defun message-make-distribution ()
3590   "Make a Distribution header."
3591   (let ((orig-distribution (message-fetch-reply-field "distribution")))
3592     (cond ((message-functionp message-distribution-function)
3593            (funcall message-distribution-function))
3594           (t orig-distribution))))
3595
3596 (defun message-make-expires ()
3597   "Return an Expires header based on `message-expires'."
3598   (let ((current (current-time))
3599         (future (* 1.0 message-expires 60 60 24)))
3600     ;; Add the future to current.
3601     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
3602     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
3603     (message-make-date current)))
3604
3605 (defun message-make-path ()
3606   "Return uucp path."
3607   (let ((login-name (user-login-name)))
3608     (cond ((null message-user-path)
3609            (concat (system-name) "!" login-name))
3610           ((stringp message-user-path)
3611            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
3612            (concat message-user-path "!" login-name))
3613           (t login-name))))
3614
3615 (defun message-make-from ()
3616   "Make a From header."
3617   (let* ((style message-from-style)
3618          (login (message-make-address))
3619          (fullname
3620           (or (and (boundp 'user-full-name)
3621                    user-full-name)
3622               (user-full-name))))
3623     (when (string= fullname "&")
3624       (setq fullname (user-login-name)))
3625     (save-excursion
3626       (message-set-work-buffer)
3627       (cond
3628        ((or (null style)
3629             (equal fullname ""))
3630         (insert login))
3631        ((or (eq style 'angles)
3632             (and (not (eq style 'parens))
3633                  ;; Use angles if no quoting is needed, or if parens would
3634                  ;; need quoting too.
3635                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
3636                      (let ((tmp (concat fullname nil)))
3637                        (while (string-match "([^()]*)" tmp)
3638                          (aset tmp (match-beginning 0) ?-)
3639                          (aset tmp (1- (match-end 0)) ?-))
3640                        (string-match "[\\()]" tmp)))))
3641         (insert fullname)
3642         (goto-char (point-min))
3643         ;; Look for a character that cannot appear unquoted
3644         ;; according to RFC 822.
3645         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
3646           ;; Quote fullname, escaping specials.
3647           (goto-char (point-min))
3648           (insert "\"")
3649           (while (re-search-forward "[\"\\]" nil 1)
3650             (replace-match "\\\\\\&" t))
3651           (insert "\""))
3652         (insert " <" login ">"))
3653        (t                               ; 'parens or default
3654         (insert login " (")
3655         (let ((fullname-start (point)))
3656           (insert fullname)
3657           (goto-char fullname-start)
3658           ;; RFC 822 says \ and nonmatching parentheses
3659           ;; must be escaped in comments.
3660           ;; Escape every instance of ()\ ...
3661           (while (re-search-forward "[()\\]" nil 1)
3662             (replace-match "\\\\\\&" t))
3663           ;; ... then undo escaping of matching parentheses,
3664           ;; including matching nested parentheses.
3665           (goto-char fullname-start)
3666           (while (re-search-forward
3667                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3668                   nil 1)
3669             (replace-match "\\1(\\3)" t)
3670             (goto-char fullname-start)))
3671         (insert ")")))
3672       (buffer-string))))
3673
3674 (defun message-make-sender ()
3675   "Return the \"real\" user address.
3676 This function tries to ignore all user modifications, and
3677 give as trustworthy answer as possible."
3678   (concat (user-login-name) "@" (system-name)))
3679
3680 (defun message-make-address ()
3681   "Make the address of the user."
3682   (or (message-user-mail-address)
3683       (concat (user-login-name) "@" (message-make-domain))))
3684
3685 (defun message-user-mail-address ()
3686   "Return the pertinent part of `user-mail-address'."
3687   (when user-mail-address
3688     (if (string-match " " user-mail-address)
3689         (nth 1 (std11-extract-address-components user-mail-address))
3690       user-mail-address)))
3691
3692 (defun message-make-fqdn ()
3693   "Return user's fully qualified domain name."
3694   (let ((system-name (system-name))
3695         (user-mail (message-user-mail-address)))
3696     (cond
3697      ((string-match "[^.]\\.[^.]" system-name)
3698       ;; `system-name' returned the right result.
3699       system-name)
3700      ;; Try `mail-host-address'.
3701      ((and (boundp 'mail-host-address)
3702            (stringp mail-host-address)
3703            (string-match "\\." mail-host-address))
3704       mail-host-address)
3705      ;; We try `user-mail-address' as a backup.
3706      ((and user-mail
3707            (string-match "\\." user-mail)
3708            (string-match "@\\(.*\\)\\'" user-mail))
3709       (match-string 1 user-mail))
3710      ;; Default to this bogus thing.
3711      (t
3712       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
3713
3714 (defun message-make-host-name ()
3715   "Return the name of the host."
3716   (let ((fqdn (message-make-fqdn)))
3717     (string-match "^[^.]+\\." fqdn)
3718     (substring fqdn 0 (1- (match-end 0)))))
3719
3720 (defun message-make-domain ()
3721   "Return the domain name."
3722   (or mail-host-address
3723       (message-make-fqdn)))
3724
3725 ;; Dummy to avoid byte-compile warning.
3726 (defvar mule-version)
3727 (defvar emacs-beta-version)
3728 (defvar xemacs-codename)
3729 (defvar gnus-inviolable-extended-version)
3730
3731 (defun message-make-user-agent ()
3732   "Return user-agent info if the value `message-user-agent' is non-nil. If the
3733 \"User-Agent\" field has already exist, it's value will be added in the return
3734 string."
3735   (when message-user-agent
3736     (save-excursion
3737       (goto-char (point-min))
3738       (let ((case-fold-search t)
3739             user-agent start p end)
3740         (if (re-search-forward "^User-Agent:[\t ]*" nil t)
3741             (progn
3742               (setq start (match-beginning 0)
3743                     p (match-end 0)
3744                     end (std11-field-end)
3745                     user-agent (buffer-substring-no-properties p end))
3746               (delete-region start (1+ end))
3747               (concat message-user-agent " " user-agent))
3748           message-user-agent)))))
3749
3750 (defun message-generate-headers (headers)
3751   "Prepare article HEADERS.
3752 Headers already prepared in the buffer are not modified."
3753   (save-restriction
3754     (message-narrow-to-headers)
3755     (let* ((Date (message-make-date))
3756            (Message-ID (message-make-message-id))
3757            (Organization (message-make-organization))
3758            (From (message-make-from))
3759            (Path (message-make-path))
3760            (Subject nil)
3761            (Newsgroups nil)
3762            (In-Reply-To (message-make-in-reply-to))
3763            (To nil)
3764            (Distribution (message-make-distribution))
3765            (Lines (message-make-lines))
3766            (User-Agent (message-make-user-agent))
3767            (Expires (message-make-expires))
3768            (case-fold-search t)
3769            header value elem)
3770       ;; First we remove any old generated headers.
3771       (let ((headers message-deletable-headers))
3772         (unless (buffer-modified-p)
3773           (setq headers (delq 'Message-ID (copy-sequence headers))))
3774         (while headers
3775           (goto-char (point-min))
3776           (and (re-search-forward
3777                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3778                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3779                (message-delete-line))
3780           (pop headers)))
3781       ;; Go through all the required headers and see if they are in the
3782       ;; articles already.  If they are not, or are empty, they are
3783       ;; inserted automatically - except for Subject, Newsgroups and
3784       ;; Distribution.
3785       (while headers
3786         (goto-char (point-min))
3787         (setq elem (pop headers))
3788         (if (consp elem)
3789             (if (eq (car elem) 'optional)
3790                 (setq header (cdr elem))
3791               (setq header (car elem)))
3792           (setq header elem))
3793         (when (or (not (re-search-forward
3794                         (concat "^"
3795                                 (regexp-quote
3796                                  (downcase
3797                                   (if (stringp header)
3798                                       header
3799                                     (symbol-name header))))
3800                                 ":")
3801                         nil t))
3802                   (progn
3803                     ;; The header was found.  We insert a space after the
3804                     ;; colon, if there is none.
3805                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
3806                     ;; Find out whether the header is empty...
3807                     (looking-at "[ \t]*\n[^ \t]")))
3808           ;; So we find out what value we should insert.
3809           (setq value
3810                 (cond
3811                  ((and (consp elem) (eq (car elem) 'optional))
3812                   ;; This is an optional header.  If the cdr of this
3813                   ;; is something that is nil, then we do not insert
3814                   ;; this header.
3815                   (setq header (cdr elem))
3816                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3817                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3818                  ((consp elem)
3819                   ;; The element is a cons.  Either the cdr is a
3820                   ;; string to be inserted verbatim, or it is a
3821                   ;; function, and we insert the value returned from
3822                   ;; this function.
3823                   (or (and (stringp (cdr elem)) (cdr elem))
3824                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3825                  ((and (boundp header) (symbol-value header))
3826                   ;; The element is a symbol.  We insert the value
3827                   ;; of this symbol, if any.
3828                   (symbol-value header))
3829                  (t
3830                   ;; We couldn't generate a value for this header,
3831                   ;; so we just ask the user.
3832                   (read-from-minibuffer
3833                    (format "Empty header for %s; enter value: " header)))))
3834           ;; Finally insert the header.
3835           (when (and value
3836                      (not (equal value "")))
3837             (save-excursion
3838               (if (bolp)
3839                   (progn
3840                     ;; This header didn't exist, so we insert it.
3841                     (goto-char (point-max))
3842                     (insert (if (stringp header) header (symbol-name header))
3843                             ": " value)
3844                     (unless (bolp)
3845                       (insert "\n"))
3846                     (forward-line -1))
3847                 ;; The value of this header was empty, so we clear
3848                 ;; totally and insert the new value.
3849                 (delete-region (point) (gnus-point-at-eol))
3850                 (insert value)
3851                 (when (bolp)
3852                   (delete-char -1)))
3853               ;; Add the deletable property to the headers that require it.
3854               (and (memq header message-deletable-headers)
3855                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3856                    (add-text-properties
3857                     (point) (match-end 0)
3858                     '(message-deletable t face italic) (current-buffer)))))))
3859       ;; Insert new Sender if the From is strange.
3860       (let ((from (message-fetch-field "from"))
3861             (sender (message-fetch-field "sender"))
3862             (secure-sender (message-make-sender)))
3863         (when (and from
3864                    (not (message-check-element 'sender))
3865                    (not (string=
3866                          (downcase
3867                           (cadr (std11-extract-address-components from)))
3868                          (downcase secure-sender)))
3869                    (or (null sender)
3870                        (not
3871                         (string=
3872                          (downcase
3873                           (cadr (std11-extract-address-components sender)))
3874                          (downcase secure-sender)))))
3875           (goto-char (point-min))
3876           ;; Rename any old Sender headers to Original-Sender.
3877           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3878             (beginning-of-line)
3879             (insert "Original-")
3880             (beginning-of-line))
3881           (when (or (message-news-p)
3882                     (string-match "@.+\\.." secure-sender))
3883             (insert "Sender: " secure-sender "\n")))))))
3884
3885 (defun message-insert-courtesy-copy ()
3886   "Insert a courtesy message in mail copies of combined messages."
3887   (let (newsgroups)
3888     (save-excursion
3889       (save-restriction
3890         (message-narrow-to-headers)
3891         (when (setq newsgroups (message-fetch-field "newsgroups"))
3892           (goto-char (point-max))
3893           (insert "Posted-To: " newsgroups "\n")))
3894       (forward-line 1)
3895       (when message-courtesy-message
3896         (cond
3897          ((string-match "%s" message-courtesy-message)
3898           (insert (format message-courtesy-message newsgroups)))
3899          (t
3900           (insert message-courtesy-message)))))))
3901
3902 ;;;
3903 ;;; Setting up a message buffer
3904 ;;;
3905
3906 (defun message-fill-address (header value)
3907   (save-restriction
3908     (narrow-to-region (point) (point))
3909     (insert (capitalize (symbol-name header))
3910             ": "
3911             (if (consp value) (car value) value)
3912             "\n")
3913     (narrow-to-region (point-min) (1- (point-max)))
3914     (let (quoted last)
3915       (goto-char (point-min))
3916       (while (not (eobp))
3917         (skip-chars-forward "^,\"" (point-max))
3918         (if (or (eq (char-after) ?,)
3919                 (eobp))
3920             (when (not quoted)
3921               (if (and (> (current-column) 78)
3922                        last)
3923                   (save-excursion
3924                     (goto-char last)
3925                     (looking-at "[ \t]*")
3926                     (replace-match "\n " t t)))
3927               (setq last (1+ (point))))
3928           (setq quoted (not quoted)))
3929         (unless (eobp)
3930           (forward-char 1))))
3931     (goto-char (point-max))
3932     (widen)
3933     (forward-line 1)))
3934
3935 (defun message-fill-references (header value)
3936   (insert (capitalize (symbol-name header))
3937           ": "
3938           (std11-fill-msg-id-list-string
3939           (if (consp value) (car value) value))
3940           "\n"))
3941
3942 (defun message-fill-header (header value)
3943   (let ((begin (point))
3944         (fill-column 78)
3945         (fill-prefix " "))
3946     (insert (capitalize (symbol-name header))
3947             ": "
3948             (if (consp value) (car value) value)
3949             "\n")
3950     (save-restriction
3951       (narrow-to-region begin (point))
3952       (fill-region-as-paragraph begin (point))
3953       ;; Tapdance around looong Message-IDs.
3954       (forward-line -1)
3955       (when (looking-at "[ \t]*$")
3956         (message-delete-line))
3957       (goto-char begin)
3958       (re-search-forward ":" nil t)
3959       (when (looking-at "\n[ \t]+")
3960         (replace-match " " t t))
3961       (goto-char (point-max)))))
3962
3963 (defun message-shorten-1 (list cut surplus)
3964   ;; Cut SURPLUS elements out of LIST, beginning with CUTth one.
3965   (setcdr (nthcdr (- cut 2) list)
3966           (nthcdr (+ (- cut 2) surplus 1) list)))
3967
3968 (defun message-shorten-references (header references)
3969   "Trim REFERENCES to be less than 31 Message-ID long, and fold them.
3970 If folding is disallowed, also check that the REFERENCES are less
3971 than 988 characters long, and if they are not, trim them until they are."
3972   (let ((maxcount 31)
3973         (count 0)
3974         (cut 6)
3975         refs)
3976     (with-temp-buffer
3977       (insert references)
3978       (goto-char (point-min))
3979       ;; Cons a list of valid references.
3980       (while (re-search-forward "<[^>]+>" nil t)
3981         (push (match-string 0) refs))
3982       (setq refs (nreverse refs)
3983             count (length refs)))
3984
3985     ;; If the list has more than MAXCOUNT elements, trim it by
3986     ;; removing the CUTth element and the required number of
3987     ;; elements that follow.
3988     (when (> count maxcount)
3989       (let ((surplus (- count maxcount)))
3990         (message-shorten-1 refs cut surplus)
3991         (decf count surplus)))
3992
3993     ;; If folding is disallowed, make sure the total length (including
3994     ;; the spaces between) will be less than MAXSIZE characters.
3995     (when message-cater-to-broken-inn
3996       (let ((maxsize 988)
3997             (totalsize (+ (apply #'+ (mapcar #'length refs))
3998                           (1- count)))
3999             (surplus 0)
4000             (ptr (nthcdr (1- cut) refs)))
4001         ;; Decide how many elements to cut off...
4002         (while (> totalsize maxsize)
4003           (decf totalsize (1+ (length (car ptr))))
4004           (incf surplus)
4005           (setq ptr (cdr ptr)))
4006         ;; ...and do it.
4007         (when (> surplus 0)
4008           (message-shorten-1 refs cut surplus))))
4009
4010     ;; Finally, collect the references back into a string and insert
4011     ;; it into the buffer.
4012     (let ((refstring (mapconcat #'identity refs " ")))
4013       (if message-cater-to-broken-inn
4014           (insert (capitalize (symbol-name header)) ": "
4015                   refstring "\n")
4016         (message-fill-header header refstring)))))
4017
4018 (defun message-position-point ()
4019   "Move point to where the user probably wants to find it."
4020   (message-narrow-to-headers)
4021   (cond
4022    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
4023     (search-backward ":" )
4024     (widen)
4025     (forward-char 1)
4026     (if (eq (char-after) ? )
4027         (forward-char 1)
4028       (insert " ")))
4029    (t
4030     (goto-char (point-max))
4031     (widen)
4032     (forward-line 1)
4033     (unless (looking-at "$")
4034       (forward-line 2)))
4035    (sit-for 0)))
4036
4037 (defun message-buffer-name (type &optional to group)
4038   "Return a new (unique) buffer name based on TYPE and TO."
4039   (cond
4040    ;; Generate a new buffer name The Message Way.
4041    ((eq message-generate-new-buffers 'unique)
4042     (generate-new-buffer-name
4043      (concat "*" type
4044              (if to
4045                  (concat " to "
4046                          (or (car (std11-extract-address-components to))
4047                              to) "")
4048                "")
4049              (if (and group (not (string= group ""))) (concat " on " group) "")
4050              "*")))
4051    ;; Check whether `message-generate-new-buffers' is a function,
4052    ;; and if so, call it.
4053    ((message-functionp message-generate-new-buffers)
4054     (funcall message-generate-new-buffers type to group))
4055    ((eq message-generate-new-buffers 'unsent)
4056     (generate-new-buffer-name
4057      (concat "*unsent " type
4058              (if to
4059                  (concat " to "
4060                          (or (car (mail-extract-address-components to))
4061                              to) "")
4062                "")
4063              (if (and group (not (string= group ""))) (concat " on " group) "")
4064              "*")))
4065    ;; Use standard name.
4066    (t
4067     (format "*%s message*" type))))
4068
4069 (defmacro message-pop-to-buffer-1 (buffer)
4070   `(if pop-up-frames
4071        (let (special-display-buffer-names
4072              special-display-regexps
4073              same-window-buffer-names
4074              same-window-regexps)
4075          (pop-to-buffer ,buffer))
4076      (pop-to-buffer ,buffer)))
4077
4078 (defun message-pop-to-buffer (name)
4079   "Pop to buffer NAME, and warn if it already exists and is modified."
4080   (let ((buffer (get-buffer name))
4081         (pop-up-frames (and (or (static-if (featurep 'xemacs)
4082                                     (device-on-window-system-p)
4083                                   window-system)
4084                                 (>= emacs-major-version 20))
4085                             message-use-multi-frames)))
4086     (if (and buffer
4087              (buffer-name buffer))
4088         (progn
4089           (message-pop-to-buffer-1 buffer)
4090           (when (and (buffer-modified-p)
4091                      (not (y-or-n-p
4092                            "Message already being composed; erase? ")))
4093             (error "Message being composed")))
4094       (message-pop-to-buffer-1 name))
4095     (erase-buffer)
4096     (message-mode)
4097     (when pop-up-frames
4098       (set (make-local-variable 'message-original-frame) (selected-frame)))))
4099
4100 (defun message-do-send-housekeeping ()
4101   "Kill old message buffers."
4102   ;; We might have sent this buffer already.  Delete it from the
4103   ;; list of buffers.
4104   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
4105   (while (and message-max-buffers
4106               message-buffer-list
4107               (>= (length message-buffer-list) message-max-buffers))
4108     ;; Kill the oldest buffer -- unless it has been changed.
4109     (let ((buffer (pop message-buffer-list)))
4110       (when (and (buffer-name buffer)
4111                  (not (buffer-modified-p buffer)))
4112         (kill-buffer buffer))))
4113   ;; Rename the buffer.
4114   (if message-send-rename-function
4115       (funcall message-send-rename-function)
4116     (when (string-match "\\`\\*\\(unsent \\)?" (buffer-name))
4117       (rename-buffer
4118        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
4119   ;; Push the current buffer onto the list.
4120   (when message-max-buffers
4121     (setq message-buffer-list
4122           (nconc message-buffer-list (list (current-buffer))))))
4123
4124 (defvar mc-modes-alist)
4125 (defun message-setup (headers &optional replybuffer actions)
4126   (when (and (boundp 'mc-modes-alist)
4127              (not (assq 'message-mode mc-modes-alist)))
4128     (push '(message-mode (encrypt . mc-encrypt-message)
4129                          (sign . mc-sign-message))
4130           mc-modes-alist))
4131   (when actions
4132     (setq message-send-actions actions))
4133   (setq message-reply-buffer
4134         (or (message-get-parameter 'reply-buffer)
4135             replybuffer))
4136   (goto-char (point-min))
4137   ;; Insert all the headers.
4138   (mail-header-format
4139    (let ((h headers)
4140          (alist message-header-format-alist))
4141      (while h
4142        (unless (assq (caar h) message-header-format-alist)
4143          (push (list (caar h)) alist))
4144        (pop h))
4145      alist)
4146    headers)
4147   (delete-region (point) (progn (forward-line -1) (point)))
4148   (when message-default-headers
4149     (insert message-default-headers)
4150     (or (bolp) (insert ?\n)))
4151   (put-text-property
4152    (point)
4153    (progn
4154      (insert mail-header-separator "\n")
4155      (1- (point)))
4156    'read-only nil)
4157   (forward-line -1)
4158   (when (message-news-p)
4159     (when message-default-news-headers
4160       (insert message-default-news-headers)
4161       (or (bolp) (insert ?\n)))
4162     (when message-generate-headers-first
4163       (message-generate-headers
4164        (delq 'Lines
4165              (delq 'Subject
4166                    (copy-sequence message-required-news-headers))))))
4167   (when (message-mail-p)
4168     (when message-default-mail-headers
4169       (insert message-default-mail-headers)
4170       (or (bolp) (insert ?\n)))
4171     (when message-generate-headers-first
4172       (message-generate-headers
4173        (delq 'Lines
4174              (delq 'Subject
4175                    (copy-sequence message-required-mail-headers))))))
4176   (run-hooks 'message-signature-setup-hook)
4177   (message-insert-signature)
4178   (save-restriction
4179     (message-narrow-to-headers)
4180     (run-hooks 'message-header-setup-hook))
4181   (set-buffer-modified-p nil)
4182   (setq buffer-undo-list nil)
4183   (run-hooks 'message-setup-hook)
4184   (message-position-point)
4185   (undo-boundary))
4186
4187 (defun message-set-auto-save-file-name ()
4188   "Associate the message buffer with a file in the drafts directory."
4189   (when message-auto-save-directory
4190     (if (gnus-alive-p)
4191         (setq message-draft-article
4192               (nndraft-request-associate-buffer "drafts"))
4193       (setq buffer-file-name (expand-file-name "*message*"
4194                                                message-auto-save-directory))
4195       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
4196     (clear-visited-file-modtime)
4197     (static-if (boundp 'MULE)
4198         (set-file-coding-system message-draft-coding-system)
4199       (setq buffer-file-coding-system message-draft-coding-system))))
4200
4201 (defun message-disassociate-draft ()
4202   "Disassociate the message buffer from the drafts directory."
4203   (when message-draft-article
4204     (nndraft-request-expire-articles
4205      (list message-draft-article) "drafts" nil t)))
4206
4207 (defun message-insert-headers ()
4208   "Generate the headers for the article."
4209   (interactive)
4210   (save-excursion
4211     (save-restriction
4212       (message-narrow-to-headers)
4213       (when (message-news-p)
4214         (message-generate-headers
4215          (delq 'Lines
4216                (delq 'Subject
4217                      (copy-sequence message-required-news-headers)))))
4218       (when (message-mail-p)
4219         (message-generate-headers
4220          (delq 'Lines
4221                (delq 'Subject
4222                      (copy-sequence message-required-mail-headers))))))))
4223
4224 \f
4225
4226 ;;;
4227 ;;; Commands for interfacing with message
4228 ;;;
4229
4230 ;;;###autoload
4231 (defun message-mail (&optional to subject
4232                                other-headers continue switch-function
4233                                yank-action send-actions)
4234   "Start editing a mail message to be sent.
4235 OTHER-HEADERS is an alist of header/value pairs."
4236   (interactive)
4237   (let ((message-this-is-mail t))
4238     (message-pop-to-buffer (message-buffer-name "mail" to))
4239     (message-setup
4240      (nconc
4241       `((To . ,(or to "")) (Subject . ,(or subject "")))
4242       (when other-headers other-headers)))))
4243
4244 ;;;###autoload
4245 (defun message-news (&optional newsgroups subject)
4246   "Start editing a news article to be sent."
4247   (interactive)
4248   (let ((message-this-is-news t))
4249     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
4250     (message-setup `((Newsgroups . ,(or newsgroups ""))
4251                      (Subject . ,(or subject ""))))))
4252
4253 ;;;###autoload
4254 (defun message-reply (&optional to-address wide)
4255   "Start editing a reply to the article in the current buffer."
4256   (interactive)
4257   (let ((cur (current-buffer))
4258         from subject date to cc
4259         references message-id follow-to
4260         (inhibit-point-motion-hooks t)
4261         (message-this-is-mail t)
4262         mct never-mct mft mrt gnus-warning in-reply-to)
4263     (save-restriction
4264       (message-narrow-to-head)
4265       ;; Allow customizations to have their say.
4266       (if (not wide)
4267           ;; This is a regular reply.
4268           (if (message-functionp message-reply-to-function)
4269               (setq follow-to (funcall message-reply-to-function)))
4270         ;; This is a followup.
4271         (if (message-functionp message-wide-reply-to-function)
4272             (save-excursion
4273               (setq follow-to
4274                     (funcall message-wide-reply-to-function)))))
4275       ;; Find all relevant headers we need.
4276       (setq from (message-fetch-field "from")
4277             date (message-fetch-field "date" t)
4278             subject (or (message-fetch-field "subject") "none")
4279             references (message-fetch-field "references")
4280             message-id (message-fetch-field "message-id" t)
4281             to (message-fetch-field "to")
4282             cc (message-fetch-field "cc")
4283             mct (when (and wide message-use-mail-copies-to)
4284                   (message-fetch-field "mail-copies-to"))
4285             mft (when (and wide message-use-mail-followup-to)
4286                   (message-fetch-field "mail-followup-to"))
4287             mrt (when message-use-mail-reply-to
4288                   (or (message-fetch-field "mail-reply-to")
4289                       (message-fetch-field "reply-to")))
4290             gnus-warning (message-fetch-field "gnus-warning"))
4291       (when (and gnus-warning (string-match "<[^>]+>" gnus-warning))
4292         (setq message-id (match-string 0 gnus-warning)))
4293       ;; Get the references from "In-Reply-To" field if there were
4294       ;; no references and "In-Reply-To" field looks promising.
4295       (unless references
4296         (when (and (setq in-reply-to (message-fetch-field "in-reply-to"))
4297                    (string-match "<[^>]+>" in-reply-to))
4298           (setq references (match-string 0 in-reply-to))))
4299       ;; Remove any (buggy) Re:'s that are present and make a
4300       ;; proper one.
4301       (setq subject (message-make-followup-subject subject))
4302       (widen))
4303
4304     ;; Handle special values of Mail-Copies-To.
4305     (when mct
4306       (cond
4307        ((and (or (equal (downcase mct) "never")
4308                  (equal (downcase mct) "nobody"))
4309              (or (not (eq message-use-mail-copies-to 'ask))
4310                  (message-y-or-n-p
4311                   (concat "Obey Mail-Copies-To: never? ") t "\
4312 You should normally obey the Mail-Copies-To: header.
4313
4314         `Mail-Copies-To: never'
4315 directs you not to send your response to the author.")))
4316         (setq never-mct t)
4317         (setq mct nil))
4318        ((and (or (equal (downcase mct) "always")
4319                  (equal (downcase mct) "poster"))
4320              (or (not (eq message-use-mail-copies-to 'ask))
4321                  (message-y-or-n-p
4322                   (concat "Obey Mail-Copies-To: always? ") t "\
4323 You should normally obey the Mail-Copies-To: header.
4324
4325         `Mail-Copies-To: always'
4326 sends a copy of your response to the author.")))
4327         (setq mct (or mrt from)))
4328        ((and (eq message-use-mail-copies-to 'ask)
4329              (not
4330               (message-y-or-n-p
4331                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
4332 You should normally obey the Mail-Copies-To: header.
4333
4334         `Mail-Copies-To: " mct "'
4335 sends a copy of your response to " (if (string-match "," mct)
4336                                        "the specified addresses"
4337                                      "that address") ".")))
4338         (setq mct nil))
4339        ))
4340
4341     (unless follow-to
4342       (cond
4343        (to-address (setq follow-to (list (cons 'To to-address))))
4344        ((not wide) (setq follow-to (list (cons 'To (or mrt from)))))
4345        ;; Handle Mail-Followup-To.
4346        ((and mft
4347              (or (not (eq message-use-mail-followup-to 'ask))
4348                  (message-y-or-n-p
4349                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
4350 You should normally obey the Mail-Followup-To: header.
4351
4352         `Mail-Followup-To: " mft "'
4353 directs your response to " (if (string-match "," mft)
4354                                "the specified addresses"
4355                              "that address only") ".
4356
4357 A typical situation where Mail-Followup-To is used is when the author thinks
4358 that further discussion should take place only in "
4359                              (if (string-match "," mft)
4360                                  "the specified mailing lists"
4361                                "that mailing list") ".")))
4362         (setq follow-to (list (cons 'To mft)))
4363         (when mct
4364           (push (cons 'Cc mct) follow-to)))
4365        (t
4366         (let (ccalist)
4367           (save-excursion
4368             (message-set-work-buffer)
4369             (unless never-mct
4370               (insert (or mrt from "")))
4371             (insert (if to (concat (if (bolp) "" ", ") to "") ""))
4372             (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
4373             (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
4374             (goto-char (point-min))
4375             (while (re-search-forward "[ \t]+" nil t)
4376               (replace-match " " t t))
4377             ;; Remove addresses that match `rmail-dont-reply-to-names'.
4378             (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
4379               (insert (prog1 (rmail-dont-reply-to (buffer-string))
4380                         (erase-buffer))))
4381             (goto-char (point-min))
4382             ;; Perhaps Mail-Copies-To: never removed the only address?
4383             (when (eobp)
4384               (insert (or mrt from "")))
4385             (setq ccalist
4386                   (mapcar
4387                    (lambda (addr)
4388                      (cons (mail-strip-quoted-names addr) addr))
4389                    (message-tokenize-header (buffer-string))))
4390             (let ((s ccalist))
4391               (while s
4392                 (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
4393           (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
4394           (when ccalist
4395             (let ((ccs (cons 'Cc (mapconcat
4396                                   (lambda (addr) (cdr addr)) ccalist ", "))))
4397               (when (string-match "^ +" (cdr ccs))
4398                 (setcdr ccs (substring (cdr ccs) (match-end 0))))
4399               (push ccs follow-to)))))))
4400
4401     (message-pop-to-buffer (message-buffer-name
4402                             (if wide "wide reply" "reply") from
4403                             (if wide to-address nil)))
4404
4405     (setq message-reply-headers
4406           (make-full-mail-header-from-decoded-header
4407            0 subject from date message-id references 0 0 ""))
4408
4409     (message-setup
4410      `((Subject . ,subject)
4411        ,@follow-to
4412        ,@(if (or references message-id)
4413              `((References . ,(concat (or references "") (and references " ")
4414                                       (or message-id ""))))))
4415      cur)))
4416
4417 ;;;###autoload
4418 (defun message-wide-reply (&optional to-address)
4419   "Make a \"wide\" reply to the message in the current buffer."
4420   (interactive)
4421   (message-reply to-address t))
4422
4423 ;;;###autoload
4424 (defun message-followup (&optional to-newsgroups)
4425   "Follow up to the message in the current buffer.
4426 If TO-NEWSGROUPS, use that as the new Newsgroups line."
4427   (interactive)
4428   (let ((cur (current-buffer))
4429         from subject date mct
4430         references message-id follow-to
4431         (inhibit-point-motion-hooks t)
4432         (message-this-is-news t)
4433         followup-to distribution newsgroups gnus-warning posted-to mft mrt)
4434     (save-restriction
4435       (message-narrow-to-head)
4436       (when (message-functionp message-followup-to-function)
4437         (setq follow-to
4438               (funcall message-followup-to-function)))
4439       (setq from (message-fetch-field "from")
4440             date (message-fetch-field "date" t)
4441             subject (or (message-fetch-field "subject") "none")
4442             references (message-fetch-field "references")
4443             message-id (message-fetch-field "message-id" t)
4444             followup-to (when message-use-followup-to
4445                           (message-fetch-field "followup-to"))
4446             distribution (message-fetch-field "distribution")
4447             newsgroups (message-fetch-field "newsgroups")
4448             posted-to (message-fetch-field "posted-to")
4449             mct (when message-use-mail-copies-to
4450                   (message-fetch-field "mail-copies-to"))
4451             mft (when message-use-mail-followup-to
4452                   (message-fetch-field "mail-followup-to"))
4453             mrt (when message-use-mail-reply-to
4454                   (or (message-fetch-field "mail-reply-to")
4455                       (message-fetch-field "reply-to")))
4456             gnus-warning (message-fetch-field "gnus-warning"))
4457       (when (and gnus-warning (string-match "<[^>]+>" gnus-warning))
4458         (setq message-id (match-string 0 gnus-warning)))
4459       ;; Remove bogus distribution.
4460       (when (and (stringp distribution)
4461                  (let ((case-fold-search t))
4462                    (string-match "world" distribution)))
4463         (setq distribution nil))
4464       ;; Remove any (buggy) Re:'s that are present and make a
4465       ;; proper one.
4466       (setq subject (message-make-followup-subject subject))
4467       (widen))
4468
4469     ;; Handle special values of Mail-Copies-To.
4470     (when mct
4471       (cond
4472        ((and (or (equal (downcase mct) "never")
4473                  (equal (downcase mct) "nobody"))
4474              (or (not (eq message-use-mail-copies-to 'ask))
4475                  (message-y-or-n-p
4476                   (concat "Obey Mail-Copies-To: never? ") t "\
4477 You should normally obey the Mail-Copies-To: header.
4478
4479         `Mail-Copies-To: never'
4480 directs you not to send your response to the author.")))
4481         (setq mct nil))
4482        ((and (or (equal (downcase mct) "always")
4483                  (equal (downcase mct) "poster"))
4484              (or (not (eq message-use-mail-copies-to 'ask))
4485                  (message-y-or-n-p
4486                   (concat "Obey Mail-Copies-To: always? ") t "\
4487 You should normally obey the Mail-Copies-To: header.
4488
4489         `Mail-Copies-To: always'
4490 sends a copy of your response to the author.")))
4491         (setq mct (or mrt from)))
4492        ((and (eq message-use-mail-copies-to 'ask)
4493              (not
4494               (message-y-or-n-p
4495                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
4496 You should normally obey the Mail-Copies-To: header.
4497
4498         `Mail-Copies-To: " mct "'
4499 sends a copy of your response to " (if (string-match "," mct)
4500                                        "the specified addresses"
4501                                      "that address") ".")))
4502         (setq mct nil))
4503        ))
4504
4505     (unless follow-to
4506       (cond
4507        (to-newsgroups (setq follow-to (list (cons 'Newsgroups to-newsgroups))))
4508        ;; Handle Followup-To.
4509        (followup-to
4510         (cond
4511          ((equal (downcase followup-to) "poster")
4512           (if (or (eq message-use-followup-to 'use)
4513                   (message-y-or-n-p "Obey Followup-To: poster? " t "\
4514 You should normally obey the Followup-To: header.
4515
4516         `Followup-To: poster'
4517 sends your response via e-mail instead of news.
4518
4519 A typical situation where `Followup-To: poster' is used is when the author
4520 does not read the newsgroup, so he wouldn't see any replies sent to it."))
4521               (setq message-this-is-news nil
4522                     distribution nil
4523                     follow-to (list (cons 'To (or mrt from ""))))
4524             (setq follow-to (list (cons 'Newsgroups newsgroups)))))
4525          (t
4526           (if (or (equal followup-to newsgroups)
4527                   (not (eq message-use-followup-to 'ask))
4528                   (message-y-or-n-p
4529                    (concat "Obey Followup-To: " followup-to "? ") t "\
4530 You should normally obey the Followup-To: header.
4531
4532         `Followup-To: " followup-to "'
4533 directs your response to " (if (string-match "," followup-to)
4534                                "the specified newsgroups"
4535                              "that newsgroup only") ".
4536
4537 If a message is posted to several newsgroups, Followup-To is often
4538 used to direct the following discussion to one newsgroup only,
4539 because discussions that are spread over several newsgroup tend to
4540 be fragmented and very difficult to follow.
4541
4542 Also, some source/announcement newsgroups are not indented for discussion;
4543 responses here are directed to other newsgroups."))
4544               (setq follow-to (list (cons 'Newsgroups followup-to)))
4545             (setq follow-to (list (cons 'Newsgroups newsgroups)))))))
4546        ;; Handle Mail-Followup-To, followup via e-mail.
4547        ((and mft
4548              (or (not (eq message-use-mail-followup-to 'ask))
4549                  (message-y-or-n-p
4550                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
4551 You should normally obey the Mail-Followup-To: header.
4552
4553         `Mail-Followup-To: " mft "'
4554 directs your response to " (if (string-match "," mft)
4555                                "the specified addresses"
4556                              "that address only") " instead of news.
4557
4558 A typical situation where Mail-Followup-To is used is when the author thinks
4559 that further discussion should take place only in "
4560                              (if (string-match "," mft)
4561                                  "the specified mailing lists"
4562                                "that mailing list") ".")))
4563         (setq message-this-is-news nil
4564               distribution nil
4565               follow-to (list (cons 'To mft))))
4566        (posted-to (setq follow-to (list (cons 'Newsgroups posted-to))))
4567        (t
4568         (setq follow-to (list (cons 'Newsgroups newsgroups))))))
4569
4570     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
4571
4572     (setq message-reply-headers
4573           (make-full-mail-header-from-decoded-header
4574            0 subject from date message-id references 0 0 ""))
4575
4576     (message-setup
4577      `((Subject . ,subject)
4578        ,@follow-to
4579        ,@(and mct (list (cons 'Cc mct)))
4580        ,@(and distribution (list (cons 'Distribution distribution)))
4581        ,@(if (or references message-id)
4582              `((References . ,(concat (or references "") (and references " ")
4583                                       (or message-id ""))))))
4584      cur)))
4585
4586 ;;;###autoload
4587 (defun message-cancel-news ()
4588   "Cancel an article you posted."
4589   (interactive)
4590   (unless (message-news-p)
4591     (error "This is not a news article; canceling is impossible"))
4592   (when (yes-or-no-p "Do you really want to cancel this article? ")
4593     (let (from newsgroups message-id distribution buf sender)
4594       (save-excursion
4595         ;; Get header info. from original article.
4596         (save-restriction
4597           (message-narrow-to-head)
4598           (setq from (message-fetch-field "from")
4599                 sender (message-fetch-field "sender")
4600                 newsgroups (message-fetch-field "newsgroups")
4601                 message-id (message-fetch-field "message-id" t)
4602                 distribution (message-fetch-field "distribution")))
4603         ;; Make sure that this article was written by the user.
4604         (unless (or (and sender
4605                          (string-equal
4606                           (downcase sender)
4607                           (downcase (message-make-sender))))
4608                     (string-equal
4609                      (downcase (cadr (std11-extract-address-components
4610                                       from)))
4611                      (downcase (cadr (std11-extract-address-components
4612                                       (message-make-from))))))
4613           (error "This article is not yours"))
4614         ;; Make control message.
4615         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
4616         (erase-buffer)
4617         (insert "Newsgroups: " newsgroups "\n"
4618                 "From: " (message-make-from) "\n"
4619                 "Subject: cmsg cancel " message-id "\n"
4620                 "Control: cancel " message-id "\n"
4621                 (if distribution
4622                     (concat "Distribution: " distribution "\n")
4623                   "")
4624                 mail-header-separator "\n"
4625                 message-cancel-message)
4626         (run-hooks 'message-cancel-hook)
4627         (message "Canceling your article...")
4628         (if (let ((message-syntax-checks
4629                    'dont-check-for-anything-just-trust-me)
4630                   (message-encoding-buffer (current-buffer))
4631                   (message-edit-buffer (current-buffer)))
4632               (message-send-news))
4633             (message "Canceling your article...done"))
4634         (kill-buffer buf)))))
4635
4636 (defun message-supersede-setup-for-mime-edit ()
4637   (set (make-local-variable 'message-setup-hook) nil)
4638   (mime-edit-again))
4639
4640 ;;;###autoload
4641 (defun message-supersede ()
4642   "Start composing a message to supersede the current message.
4643 This is done simply by taking the old article and adding a Supersedes
4644 header line with the old Message-ID."
4645   (interactive)
4646   (let ((cur (current-buffer))
4647         (sender (message-fetch-field "sender"))
4648         (from (message-fetch-field "from")))
4649     ;; Check whether the user owns the article that is to be superseded.
4650     (unless (or (and sender
4651                      (string-equal
4652                       (downcase sender)
4653                       (downcase (message-make-sender))))
4654                 (string-equal
4655                  (downcase (cadr (std11-extract-address-components from)))
4656                  (downcase (cadr (std11-extract-address-components
4657                                   (message-make-from))))))
4658       (error "This article is not yours"))
4659     ;; Get a normal message buffer.
4660     (message-pop-to-buffer (message-buffer-name "supersede"))
4661     (insert-buffer-substring cur)
4662     (message-narrow-to-head)
4663     ;; Remove unwanted headers.
4664     (when message-ignored-supersedes-headers
4665       (message-remove-header message-ignored-supersedes-headers t))
4666     (goto-char (point-min))
4667     (if (not (re-search-forward "^Message-ID: " nil t))
4668         (error "No Message-ID in this article")
4669       (replace-match "Supersedes: " t t))
4670     (goto-char (point-max))
4671     (insert mail-header-separator)
4672     (widen)
4673     (when message-supersede-setup-function
4674       (funcall message-supersede-setup-function))
4675     (run-hooks 'message-supersede-setup-hook)
4676     (goto-char (point-min))
4677     (search-forward (concat "\n" mail-header-separator "\n") nil t)))
4678
4679 ;;;###autoload
4680 (defun message-recover ()
4681   "Reread contents of current buffer from its last auto-save file."
4682   (interactive)
4683   (let ((file-name (make-auto-save-file-name)))
4684     (cond ((save-window-excursion
4685              (if (not (eq system-type 'vax-vms))
4686                  (with-output-to-temp-buffer "*Directory*"
4687                    (buffer-disable-undo standard-output)
4688                    (let ((default-directory "/"))
4689                      (call-process
4690                       "ls" nil standard-output nil "-l" file-name))))
4691              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
4692            (let ((buffer-read-only nil))
4693              (erase-buffer)
4694              (insert-file-contents file-name nil)))
4695           (t (error "message-recover cancelled")))))
4696
4697 ;;; Washing Subject:
4698
4699 (defun message-wash-subject (subject)
4700   "Remove junk like \"Re:\", \"(fwd)\", etc. that was added to the subject by previous forwarders, replyers, etc."
4701   (with-temp-buffer
4702     (insert-string subject)
4703     (goto-char (point-min))
4704     ;; strip Re/Fwd stuff off the beginning
4705     (while (re-search-forward
4706             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
4707       (replace-match ""))
4708
4709     ;; and gnus-style forwards [foo@bar.com] subject
4710     (goto-char (point-min))
4711     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
4712       (replace-match ""))
4713
4714     ;; and off the end
4715     (goto-char (point-max))
4716     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
4717       (replace-match ""))
4718
4719     ;; and finally, any whitespace that was left-over
4720     (goto-char (point-min))
4721     (while (re-search-forward "^[ \t]+" nil t)
4722       (replace-match ""))
4723     (goto-char (point-max))
4724     (while (re-search-backward "[ \t]+$" nil t)
4725       (replace-match ""))
4726
4727     (buffer-string)))
4728
4729 ;;; Forwarding messages.
4730
4731 (defun message-forward-subject-author-subject (subject)
4732   "Generate a subject for a forwarded message.
4733 The form is: [Source] Subject, where if the original message was mail,
4734 Source is the sender, and if the original message was news, Source is
4735 the list of newsgroups is was posted to."
4736   (concat "["
4737           (or (message-fetch-field
4738                (if (message-news-p) "newsgroups" "from"))
4739               "(nowhere)")
4740           "] " subject))
4741
4742 (defun message-forward-subject-fwd (subject)
4743   "Generate a subject for a forwarded message.
4744 The form is: Fwd: Subject, where Subject is the original subject of
4745 the message."
4746   (concat "Fwd: " subject))
4747
4748 (defun message-make-forward-subject ()
4749   "Return a Subject header suitable for the message in the current buffer."
4750   (save-excursion
4751     (save-restriction
4752       (current-buffer)
4753       (message-narrow-to-head)
4754       (let ((funcs message-make-forward-subject-function)
4755             (subject (message-fetch-field "Subject")))
4756         (setq subject
4757               (if subject
4758                   (if message-wash-forwarded-subjects
4759                       (message-wash-subject
4760                        (nnheader-decode-subject subject))
4761                     (nnheader-decode-subject subject))
4762                 "(none)"))
4763         ;; Make sure funcs is a list.
4764         (and funcs
4765              (not (listp funcs))
4766              (setq funcs (list funcs)))
4767         ;; Apply funcs in order, passing subject generated by previous
4768         ;; func to the next one.
4769         (while funcs
4770           (when (message-functionp (car funcs))
4771             (setq subject (funcall (car funcs) subject)))
4772           (setq funcs (cdr funcs)))
4773         subject))))
4774
4775 ;;;###autoload
4776 (defun message-forward (&optional news)
4777   "Forward the current message via mail.
4778 Optional NEWS will use news to forward instead of mail."
4779   (interactive "P")
4780   (let ((cur (current-buffer))
4781         (subject (message-make-forward-subject))
4782         art-beg)
4783     (if news
4784         (message-news nil subject)
4785       (message-mail nil subject))
4786     ;; Put point where we want it before inserting the forwarded
4787     ;; message.
4788     (if message-signature-before-forwarded-message
4789         (goto-char (point-max))
4790       (message-goto-body))
4791     ;; Make sure we're at the start of the line.
4792     (unless (eolp)
4793       (insert "\n"))
4794     ;; Narrow to the area we are to insert.
4795     (narrow-to-region (point) (point))
4796     ;; Insert the separators and the forwarded buffer.
4797     (insert message-forward-start-separator)
4798     (setq art-beg (point))
4799     (insert-buffer-substring cur)
4800     (goto-char (point-max))
4801     (insert message-forward-end-separator)
4802     (set-text-properties (point-min) (point-max) nil)
4803     ;; Remove all unwanted headers.
4804     (goto-char art-beg)
4805     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
4806                                   (1- (point))
4807                                 (point)))
4808     (goto-char (point-min))
4809     (message-remove-header message-included-forward-headers t nil t)
4810     (widen)
4811     (message-position-point)))
4812
4813 ;;;###autoload
4814 (defun message-resend (address)
4815   "Resend the current article to ADDRESS."
4816   (interactive
4817    (list (message-read-from-minibuffer "Resend message to: ")))
4818   (message "Resending message to %s..." address)
4819   (save-excursion
4820     (let ((cur (current-buffer))
4821           beg)
4822       ;; We first set up a normal mail buffer.
4823       (set-buffer (get-buffer-create " *message resend*"))
4824       (erase-buffer)
4825       ;; avoid to turn-on-mime-edit
4826       (let (message-setup-hook)
4827         (message-setup `((To . ,address)))
4828         )
4829       ;; Insert our usual headers.
4830       (message-generate-headers '(From Date To))
4831       (message-narrow-to-headers)
4832       ;; Rename them all to "Resent-*".
4833       (while (re-search-forward "^[A-Za-z]" nil t)
4834         (forward-char -1)
4835         (insert "Resent-"))
4836       (widen)
4837       (forward-line)
4838       (delete-region (point) (point-max))
4839       (setq beg (point))
4840       ;; Insert the message to be resent.
4841       (insert-buffer-substring cur)
4842       (goto-char (point-min))
4843       (search-forward "\n\n")
4844       (forward-char -1)
4845       (save-restriction
4846         (narrow-to-region beg (point))
4847         (message-remove-header message-ignored-resent-headers t)
4848         (goto-char (point-max)))
4849       (insert mail-header-separator)
4850       ;; Rename all old ("Also-")Resent headers.
4851       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
4852         (beginning-of-line)
4853         (insert "Also-"))
4854       ;; Quote any "From " lines at the beginning.
4855       (goto-char beg)
4856       (when (looking-at "From ")
4857         (replace-match "X-From-Line: "))
4858       ;; Send it.
4859       (let ((message-encoding-buffer (current-buffer))
4860             (message-edit-buffer (current-buffer)))
4861         (let (message-required-mail-headers)
4862           (message-send-mail)))
4863       (kill-buffer (current-buffer)))
4864     (message "Resending message to %s...done" address)))
4865
4866 (defun message-bounce-setup-for-mime-edit ()
4867   (set (make-local-variable 'message-setup-hook) nil)
4868   (mime-edit-again))
4869
4870 ;;;###autoload
4871 (defun message-bounce ()
4872   "Re-mail the current message.
4873 This only makes sense if the current message is a bounce message than
4874 contains some mail you have written which has been bounced back to
4875 you."
4876   (interactive)
4877   (let ((cur (current-buffer))
4878         boundary)
4879     (message-pop-to-buffer (message-buffer-name "bounce"))
4880     (insert-buffer-substring cur)
4881     (undo-boundary)
4882     (message-narrow-to-head)
4883     (if (and (message-fetch-field "MIME-Version")
4884              (setq boundary (message-fetch-field "Content-Type")))
4885         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
4886             (setq boundary (concat (match-string 1 boundary) " *\n"
4887                                    "Content-Type: message/rfc822"))
4888           (setq boundary nil)))
4889     (widen)
4890     (goto-char (point-min))
4891     (search-forward "\n\n" nil t)
4892     (or (and boundary
4893              (re-search-forward boundary nil t)
4894              (forward-line 2))
4895         (and (re-search-forward message-unsent-separator nil t)
4896              (forward-line 1))
4897         (re-search-forward "^Return-Path:.*\n" nil t))
4898     ;; We remove everything before the bounced mail.
4899     (delete-region
4900      (point-min)
4901      (if (re-search-forward "^[^ \n\t]+:" nil t)
4902          (match-beginning 0)
4903        (point)))
4904     (save-restriction
4905       (message-narrow-to-head)
4906       (message-remove-header message-ignored-bounced-headers t)
4907       (goto-char (point-max))
4908       (insert mail-header-separator))
4909     (when message-bounce-setup-function
4910       (funcall message-bounce-setup-function))
4911     (run-hooks 'message-bounce-setup-hook)
4912     (message-position-point)))
4913
4914 ;;;
4915 ;;; Interactive entry points for new message buffers.
4916 ;;;
4917
4918 ;;;###autoload
4919 (defun message-mail-other-window (&optional to subject)
4920   "Like `message-mail' command, but display mail buffer in another window."
4921   (interactive)
4922   (let ((pop-up-windows t)
4923         (special-display-buffer-names nil)
4924         (special-display-regexps nil)
4925         (same-window-buffer-names nil)
4926         (same-window-regexps nil))
4927     (message-pop-to-buffer (message-buffer-name "mail" to)))
4928   (let ((message-this-is-mail t))
4929     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4930
4931 ;;;###autoload
4932 (defun message-mail-other-frame (&optional to subject)
4933   "Like `message-mail' command, but display mail buffer in another frame."
4934   (interactive)
4935   (let ((pop-up-frames t)
4936         (special-display-buffer-names nil)
4937         (special-display-regexps nil)
4938         (same-window-buffer-names nil)
4939         (same-window-regexps nil))
4940     (message-pop-to-buffer (message-buffer-name "mail" to)))
4941   (let ((message-this-is-mail t))
4942     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4943
4944 ;;;###autoload
4945 (defun message-news-other-window (&optional newsgroups subject)
4946   "Start editing a news article to be sent."
4947   (interactive)
4948   (let ((pop-up-windows t)
4949         (special-display-buffer-names nil)
4950         (special-display-regexps nil)
4951         (same-window-buffer-names nil)
4952         (same-window-regexps nil))
4953     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4954   (let ((message-this-is-news t))
4955     (message-setup `((Newsgroups . ,(or newsgroups ""))
4956                      (Subject . ,(or subject ""))))))
4957
4958 ;;;###autoload
4959 (defun message-news-other-frame (&optional newsgroups subject)
4960   "Start editing a news article to be sent."
4961   (interactive)
4962   (let ((pop-up-frames t)
4963         (special-display-buffer-names nil)
4964         (special-display-regexps nil)
4965         (same-window-buffer-names nil)
4966         (same-window-regexps nil))
4967     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4968   (let ((message-this-is-news t))
4969     (message-setup `((Newsgroups . ,(or newsgroups ""))
4970                      (Subject . ,(or subject ""))))))
4971
4972 ;;; underline.el
4973
4974 ;; This code should be moved to underline.el (from which it is stolen).
4975
4976 ;;;###autoload
4977 (defun bold-region (start end)
4978   "Bold all nonblank characters in the region.
4979 Works by overstriking characters.
4980 Called from program, takes two arguments START and END
4981 which specify the range to operate on."
4982   (interactive "r")
4983   (save-excursion
4984     (let ((end1 (make-marker)))
4985       (move-marker end1 (max start end))
4986       (goto-char (min start end))
4987       (while (< (point) end1)
4988         (or (looking-at "[_\^@- ]")
4989             (insert (char-after) "\b"))
4990         (forward-char 1)))))
4991
4992 ;;;###autoload
4993 (defun unbold-region (start end)
4994   "Remove all boldness (overstruck characters) in the region.
4995 Called from program, takes two arguments START and END
4996 which specify the range to operate on."
4997   (interactive "r")
4998   (save-excursion
4999     (let ((end1 (make-marker)))
5000       (move-marker end1 (max start end))
5001       (goto-char (min start end))
5002       (while (re-search-forward "\b" end1 t)
5003         (if (eq (char-after) (char-after (- (point) 2)))
5004             (delete-char -2))))))
5005
5006 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
5007
5008 ;; Support for toolbar
5009 (when (string-match "XEmacs\\|Lucid" emacs-version)
5010   (require 'messagexmas))
5011
5012 ;;; Group name completion.
5013
5014 (defvar message-newgroups-header-regexp
5015   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
5016   "Regexp that match headers that lists groups.")
5017
5018 (defun message-tab ()
5019   "Expand group names in Newsgroups and Followup-To headers.
5020 Do a `tab-to-tab-stop' if not in those headers."
5021   (interactive)
5022   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
5023         (mail-abbrev-in-expansion-header-p))
5024       (message-expand-group)
5025     (tab-to-tab-stop)))
5026
5027 (defvar gnus-active-hashtb)
5028 (defun message-expand-group ()
5029   "Expand the group name under point."
5030   (let* ((b (save-excursion
5031               (save-restriction
5032                 (narrow-to-region
5033                  (save-excursion
5034                    (beginning-of-line)
5035                    (skip-chars-forward "^:")
5036                    (1+ (point)))
5037                  (point))
5038                 (skip-chars-backward "^, \t\n") (point))))
5039          (completion-ignore-case t)
5040          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
5041                                             (point))))
5042          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
5043          (completions (all-completions string hashtb))
5044          comp)
5045     (delete-region b (point))
5046     (cond
5047      ((= (length completions) 1)
5048       (if (string= (car completions) string)
5049           (progn
5050             (insert string)
5051             (message "Only matching group"))
5052         (insert (car completions))))
5053      ((and (setq comp (try-completion string hashtb))
5054            (not (string= comp string)))
5055       (insert comp))
5056      (t
5057       (insert string)
5058       (if (not comp)
5059           (message "No matching groups")
5060         (save-selected-window
5061           (pop-to-buffer "*Completions*")
5062           (buffer-disable-undo)
5063           (let ((buffer-read-only nil))
5064             (erase-buffer)
5065             (let ((standard-output (current-buffer)))
5066               (display-completion-list (sort completions 'string<)))
5067             (goto-char (point-min))
5068             (delete-region (point) (progn (forward-line 3) (point))))))))))
5069
5070 ;;; Help stuff.
5071
5072 (defun message-talkative-question (ask question show &rest text)
5073   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
5074 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
5075 The following arguments may contain lists of values."
5076   (if (and show
5077            (setq text (message-flatten-list text)))
5078       (save-window-excursion
5079         (save-excursion
5080           (with-output-to-temp-buffer " *MESSAGE information message*"
5081             (set-buffer " *MESSAGE information message*")
5082             (mapcar 'princ text)
5083             (goto-char (point-min))))
5084         (funcall ask question))
5085     (funcall ask question)))
5086
5087 (defun message-flatten-list (list)
5088   "Return a new, flat list that contains all elements of LIST.
5089
5090 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
5091 => (1 2 3 4 5 6 7)"
5092   (cond ((consp list)
5093          (apply 'append (mapcar 'message-flatten-list list)))
5094         (list
5095          (list list))))
5096
5097 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
5098   "Create and return a buffer with a name based on NAME using generate-new-buffer.
5099 Then clone the local variables and values from the old buffer to the
5100 new one, cloning only the locals having a substring matching the
5101 regexp varstr."
5102   (let ((oldbuf (current-buffer)))
5103     (save-excursion
5104       (set-buffer (generate-new-buffer name))
5105       (message-clone-locals oldbuf varstr)
5106       (current-buffer))))
5107
5108 (defun message-clone-locals (buffer &optional varstr)
5109   "Clone the local variables from BUFFER to the current buffer."
5110   (let ((locals (save-excursion
5111                   (set-buffer buffer)
5112                   (buffer-local-variables)))
5113         (regexp
5114          "^\\(gnus\\|nn\\|message\\|user-\\(mail-address\\|full-name\\)\\)"))
5115     (mapcar
5116      (lambda (local)
5117        (when (and (consp local)
5118                   (car local)
5119                   (string-match regexp (symbol-name (car local)))
5120                   (or (null varstr)
5121                       (string-match varstr (symbol-name (car local)))))
5122          (ignore-errors
5123            (set (make-local-variable (car local))
5124                 (cdr local)))))
5125      locals)))
5126
5127
5128 ;;; @ for MIME Edit mode
5129 ;;;
5130
5131 (defun message-maybe-encode ()
5132   (when message-mime-mode
5133     ;; Inherit the buffer local variable `mime-edit-pgp-processing'.
5134     (let ((pgp-processing (with-current-buffer message-edit-buffer
5135                             mime-edit-pgp-processing)))
5136       (setq mime-edit-pgp-processing pgp-processing))
5137     (run-hooks 'mime-edit-translate-hook)
5138     (if (catch 'mime-edit-error
5139           (save-excursion
5140             (mime-edit-pgp-enclose-buffer)
5141             (mime-edit-translate-body)
5142             ))
5143         (error "Translation error!")
5144       )
5145     (end-of-invisible)
5146     (run-hooks 'mime-edit-exit-hook)
5147     ))
5148
5149 (defun message-mime-insert-article (&optional full-headers)
5150   (interactive "P")
5151   (let ((message-cite-function 'mime-edit-inserted-message-filter)
5152         (message-reply-buffer
5153          (message-get-parameter-with-eval 'original-buffer))
5154         (start (point)))
5155     (message-yank-original nil)
5156     (save-excursion
5157       (narrow-to-region (goto-char start)
5158                         (if (search-forward "\n\n" nil t)
5159                             (1- (point))
5160                           (point-max)))
5161       (goto-char (point-min))
5162       (let ((message-included-forward-headers
5163              (if full-headers "" message-included-forward-headers)))
5164         (message-remove-header message-included-forward-headers t nil t))
5165       (widen))))
5166
5167 (set-alist 'mime-edit-message-inserter-alist
5168            'message-mode (function message-mime-insert-article))
5169
5170 ;;; Miscellaneous functions
5171
5172 ;; stolen (and renamed) from nnheader.el
5173 (defun message-replace-chars-in-string (string from to)
5174   "Replace characters in STRING from FROM to TO."
5175   (let ((string (substring string 0))   ;Copy string.
5176         (len (length string))
5177         (idx 0))
5178     ;; Replace all occurrences of FROM with TO.
5179     (while (< idx len)
5180       (when (= (aref string idx) from)
5181         (aset string idx to))
5182       (setq idx (1+ idx)))
5183     string))
5184
5185 ;;;
5186 ;;; MIME functions
5187 ;;;
5188
5189 (defvar message-inhibit-body-encoding t)
5190
5191 (defun message-encode-message-body ()
5192   (unless message-inhibit-body-encoding
5193     (let ((mail-parse-charset (or mail-parse-charset
5194                                   message-default-charset
5195                                   message-posting-charset))
5196           (case-fold-search t)
5197           lines content-type-p)
5198       (message-goto-body)
5199       (save-restriction
5200         (narrow-to-region (point) (point-max))
5201         (let ((new (mml-generate-mime)))
5202           (when new
5203             (delete-region (point-min) (point-max))
5204             (insert new)
5205             (goto-char (point-min))
5206             (if (eq (aref new 0) ?\n)
5207                 (delete-char 1)
5208               (search-forward "\n\n")
5209               (setq lines (buffer-substring (point-min) (1- (point))))
5210               (delete-region (point-min) (point))))))
5211       (save-restriction
5212         (message-narrow-to-headers-or-head)
5213         (message-remove-header "Mime-Version")
5214         (goto-char (point-max))
5215         (insert "MIME-Version: 1.0\n")
5216         (when lines
5217           (insert lines))
5218         (setq content-type-p
5219               (re-search-backward "^Content-Type:" nil t)))
5220       (save-restriction
5221         (message-narrow-to-headers-or-head)
5222         (message-remove-first-header "Content-Type")
5223         (message-remove-first-header "Content-Transfer-Encoding"))
5224       ;; We always make sure that the message has a Content-Type header.
5225       ;; This is because some broken MTAs and MUAs get awfully confused
5226       ;; when confronted with a message with a MIME-Version header and
5227       ;; without a Content-Type header.  For instance, Solaris'
5228       ;; /usr/bin/mail.
5229       (unless content-type-p
5230         (goto-char (point-min))
5231         (re-search-forward "^MIME-Version:")
5232         (forward-line 1)
5233         (insert "Content-Type: text/plain; charset=us-ascii\n")))))
5234
5235 (defun message-read-from-minibuffer (prompt)
5236   "Read from the minibuffer while providing abbrev expansion."
5237   (if (fboundp 'mail-abbrevs-setup)
5238       (let ((mail-abbrev-mode-regexp "")
5239             (minibuffer-setup-hook 'mail-abbrevs-setup))
5240         (read-from-minibuffer prompt)))
5241   (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook))
5242     (read-string prompt)))
5243
5244 (defvar message-save-buffer " *encoding")
5245 (defun message-save-drafts ()
5246   (interactive)
5247   (if (not (get-buffer message-save-buffer))
5248       (get-buffer-create message-save-buffer))
5249   (let ((filename buffer-file-name)
5250         (buffer (current-buffer))
5251         (reply-headers message-reply-headers))
5252     (set-buffer message-save-buffer)
5253     (erase-buffer)
5254     (insert-buffer buffer)
5255     (setq message-reply-headers reply-headers)
5256     (message-generate-headers  '((optional . In-Reply-To)))
5257     (mime-edit-translate-buffer)
5258     (write-region (point-min) (point-max) filename)
5259     (set-buffer buffer)
5260     (set-buffer-modified-p nil)))
5261
5262 (provide 'message)
5263
5264 (run-hooks 'message-load-hook)
5265
5266 ;;; message.el ends here