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