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