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