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