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