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