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