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