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