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