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