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