e6b2662f947b0514639bec402b1ac5f9ee061c90
[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     :help "Spellcheck this message"]
1428    ["Attach file as MIME" mml-attach-file
1429     :help "Attach a file at point"]
1430    "----"
1431    ["Send Message" message-send-and-exit
1432     :help "Send this message"]
1433    ["Abort Message" message-dont-send
1434     :help "File this draft message and exit"]
1435    ["Kill Message" message-kill-buffer
1436     :help "Delete this message without sending"]))
1437
1438 (easy-menu-define
1439  message-mode-field-menu message-mode-map ""
1440  '("Field"
1441    ["Fetch To" message-insert-to t]
1442    ["Fetch Newsgroups" message-insert-newsgroups t]
1443    "----"
1444    ["To" message-goto-to t]
1445    ["Subject" message-goto-subject t]
1446    ["Cc" message-goto-cc t]
1447    ["Reply-To" message-goto-reply-to t]
1448    ["Summary" message-goto-summary t]
1449    ["Keywords" message-goto-keywords t]
1450    ["Newsgroups" message-goto-newsgroups t]
1451    ["Followup-To" message-goto-followup-to t]
1452    ["Distribution" message-goto-distribution t]
1453    ["Body" message-goto-body t]
1454    ["Signature" message-goto-signature t]))
1455
1456 (eval-when-compile
1457   (defvar facemenu-add-face-function)
1458   (defvar facemenu-remove-face-function)
1459   (defvar message-tool-bar-map))
1460
1461 ;;;###autoload
1462 (defun message-mode ()
1463   "Major mode for editing mail and news to be sent.
1464 Like Text Mode but with these additional commands:
1465 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
1466 C-c C-d  Postpone sending the message        C-c C-k  Kill the message
1467 C-c C-f  move to a header field (and create it if there isn't):
1468          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1469          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1470          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1471          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1472          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1473          C-c C-f C-f  move to Followup-To
1474 C-c C-t  message-insert-to (add a To header to a news followup)
1475 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
1476 C-c C-b  message-goto-body (move to beginning of message text).
1477 C-c C-i  message-goto-signature (move to the beginning of the signature).
1478 C-c C-w  message-insert-signature (insert `message-signature-file' file).
1479 C-c C-y  message-yank-original (insert current message, if any).
1480 C-c C-q  message-fill-yanked-message (fill what was yanked).
1481 C-c C-e  message-elide-region (elide the text between point and mark).
1482 C-c C-v  message-delete-not-region (remove the text outside the region).
1483 C-c C-z  message-kill-to-signature (kill the text up to the signature).
1484 C-c C-r  message-caesar-buffer-body (rot13 the message body).
1485 C-c C-a  mml-attach-file (attach a file as MIME).
1486 M-RET    message-newline-and-reformat (break the line and reformat)."
1487   (interactive)
1488   (if (local-variable-p 'mml-buffer-list (current-buffer))
1489       (mml-destroy-buffers))
1490   (kill-all-local-variables)
1491   (set (make-local-variable 'message-reply-buffer) nil)
1492   (make-local-variable 'message-send-actions)
1493   (make-local-variable 'message-exit-actions)
1494   (make-local-variable 'message-kill-actions)
1495   (make-local-variable 'message-postpone-actions)
1496   (make-local-variable 'message-draft-article)
1497   (make-local-hook 'kill-buffer-hook)
1498   (set-syntax-table message-mode-syntax-table)
1499   (use-local-map message-mode-map)
1500   (setq local-abbrev-table message-mode-abbrev-table)
1501   (setq major-mode 'message-mode)
1502   (setq mode-name "Message")
1503   (setq buffer-offer-save t)
1504   (make-local-variable 'facemenu-add-face-function)
1505   (make-local-variable 'facemenu-remove-face-function)
1506   (setq facemenu-add-face-function
1507         (lambda (face end)
1508           (let ((face-fun (cdr (assq face message-face-alist))))
1509             (if face-fun
1510                 (funcall face-fun (point) end)
1511               (error "Face %s not configured for %s mode" face mode-name)))
1512           "")
1513         facemenu-remove-face-function t)
1514   (make-local-variable 'message-reply-headers)
1515   (setq message-reply-headers nil)
1516   (make-local-variable 'message-newsreader)
1517   (make-local-variable 'message-mailer)
1518   (make-local-variable 'message-post-method)
1519   (set (make-local-variable 'message-sent-message-via) nil)
1520   (set (make-local-variable 'message-checksum) nil)
1521   (set (make-local-variable 'message-mime-part) 0)
1522   (message-setup-fill-variables)
1523   ;;(when (fboundp 'mail-hist-define-keys)
1524   ;;  (mail-hist-define-keys))
1525   (if (featurep 'xemacs)
1526       (message-setup-toolbar)
1527     (set (make-local-variable 'font-lock-defaults)
1528          '(message-font-lock-keywords t))
1529     (if (boundp 'tool-bar-map)
1530         (set (make-local-variable 'tool-bar-map) message-tool-bar-map)))
1531   (easy-menu-add message-mode-menu message-mode-map)
1532   (easy-menu-add message-mode-field-menu message-mode-map)
1533   ;; Allow mail alias things.
1534   (when (eq message-mail-alias-type 'abbrev)
1535     (if (fboundp 'mail-abbrevs-setup)
1536         (mail-abbrevs-setup)
1537       (mail-aliases-setup)))
1538   (message-set-auto-save-file-name)
1539   (mm-enable-multibyte)
1540   (make-local-variable 'indent-tabs-mode) ;Turn off tabs for indentation.
1541   (setq indent-tabs-mode nil)
1542   (mml-mode)
1543   (run-hooks 'text-mode-hook 'message-mode-hook))
1544
1545 (defun message-setup-fill-variables ()
1546   "Setup message fill variables."
1547   (make-local-variable 'paragraph-separate)
1548   (make-local-variable 'paragraph-start)
1549   (make-local-variable 'adaptive-fill-regexp)
1550   (unless (boundp 'adaptive-fill-first-line-regexp)
1551     (setq adaptive-fill-first-line-regexp nil))
1552   (make-local-variable 'adaptive-fill-first-line-regexp)
1553   (make-local-variable 'auto-fill-inhibit-regexp)
1554   (let ((quote-prefix-regexp
1555          ;; User should change message-cite-prefix-regexp if
1556          ;; message-yank-prefix is set to an abnormal value.
1557          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))      
1558     (setq paragraph-start
1559           (concat
1560            (regexp-quote mail-header-separator) "$\\|"
1561            "[ \t]*$\\|"                 ; blank lines
1562            "-- $\\|"                    ; signature delimiter
1563            "---+$\\|"                   ; delimiters for forwarded messages
1564            page-delimiter "$\\|"        ; spoiler warnings
1565            ".*wrote:$\\|"               ; attribution lines
1566            quote-prefix-regexp "$"))    ; empty lines in quoted text
1567     (setq paragraph-separate paragraph-start)
1568     (setq adaptive-fill-regexp
1569           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
1570     (setq adaptive-fill-first-line-regexp
1571           (concat quote-prefix-regexp "\\|"
1572                   adaptive-fill-first-line-regexp))
1573     (setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")))
1574
1575 \f
1576
1577 ;;;
1578 ;;; Message mode commands
1579 ;;;
1580
1581 ;;; Movement commands
1582
1583 (defun message-goto-to ()
1584   "Move point to the To header."
1585   (interactive)
1586   (message-position-on-field "To"))
1587
1588 (defun message-goto-subject ()
1589   "Move point to the Subject header."
1590   (interactive)
1591   (message-position-on-field "Subject"))
1592
1593 (defun message-goto-cc ()
1594   "Move point to the Cc header."
1595   (interactive)
1596   (message-position-on-field "Cc" "To"))
1597
1598 (defun message-goto-bcc ()
1599   "Move point to the Bcc  header."
1600   (interactive)
1601   (message-position-on-field "Bcc" "Cc" "To"))
1602
1603 (defun message-goto-fcc ()
1604   "Move point to the Fcc header."
1605   (interactive)
1606   (message-position-on-field "Fcc" "To" "Newsgroups"))
1607
1608 (defun message-goto-reply-to ()
1609   "Move point to the Reply-To header."
1610   (interactive)
1611   (message-position-on-field "Reply-To" "Subject"))
1612
1613 (defun message-goto-newsgroups ()
1614   "Move point to the Newsgroups header."
1615   (interactive)
1616   (message-position-on-field "Newsgroups"))
1617
1618 (defun message-goto-distribution ()
1619   "Move point to the Distribution header."
1620   (interactive)
1621   (message-position-on-field "Distribution"))
1622
1623 (defun message-goto-followup-to ()
1624   "Move point to the Followup-To header."
1625   (interactive)
1626   (message-position-on-field "Followup-To" "Newsgroups"))
1627
1628 (defun message-goto-keywords ()
1629   "Move point to the Keywords header."
1630   (interactive)
1631   (message-position-on-field "Keywords" "Subject"))
1632
1633 (defun message-goto-summary ()
1634   "Move point to the Summary header."
1635   (interactive)
1636   (message-position-on-field "Summary" "Subject"))
1637
1638 (defun message-goto-body ()
1639   "Move point to the beginning of the message body."
1640   (interactive)
1641   (if (looking-at "[ \t]*\n") (expand-abbrev))
1642   (goto-char (point-min))
1643   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
1644       (search-forward "\n\n" nil t)))
1645
1646 (defun message-goto-eoh ()
1647   "Move point to the end of the headers."
1648   (interactive)
1649   (message-goto-body)
1650   (forward-line -1))
1651
1652 (defun message-goto-signature ()
1653   "Move point to the beginning of the message signature.
1654 If there is no signature in the article, go to the end and
1655 return nil."
1656   (interactive)
1657   (goto-char (point-min))
1658   (if (re-search-forward message-signature-separator nil t)
1659       (forward-line 1)
1660     (goto-char (point-max))
1661     nil))
1662
1663 \f
1664
1665 (defun message-insert-to (&optional force)
1666   "Insert a To header that points to the author of the article being replied to.
1667 If the original author requested not to be sent mail, the function signals
1668 an error.
1669 With the prefix argument FORCE, insert the header anyway."
1670   (interactive "P")
1671   (let ((co (message-fetch-reply-field "mail-copies-to")))
1672     (when (and (null force)
1673                co
1674                (or (equal (downcase co) "never")
1675                    (equal (downcase co) "nobody")))
1676       (error "The user has requested not to have copies sent via mail")))
1677   (when (and (message-position-on-field "To")
1678              (mail-fetch-field "to")
1679              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1680     (insert ", "))
1681   (insert (or (message-fetch-reply-field "mail-reply-to")
1682               (message-fetch-reply-field "reply-to")
1683               (message-fetch-reply-field "from") "")))
1684
1685 (defun message-widen-reply ()
1686   "Widen the reply to include maximum recipients."
1687   (interactive)
1688   (let ((follow-to
1689          (and message-reply-buffer
1690               (buffer-name message-reply-buffer)
1691               (save-excursion
1692                 (set-buffer message-reply-buffer)
1693                 (message-get-reply-headers t)))))
1694     (save-excursion
1695       (save-restriction
1696         (message-narrow-to-headers)
1697         (dolist (elem follow-to)
1698           (message-remove-header (symbol-name (car elem)))
1699           (goto-char (point-min))
1700           (insert (symbol-name (car elem)) ": "
1701                   (cdr elem) "\n"))))))
1702
1703 (defun message-insert-newsgroups ()
1704   "Insert the Newsgroups header from the article being replied to."
1705   (interactive)
1706   (when (and (message-position-on-field "Newsgroups")
1707              (mail-fetch-field "newsgroups")
1708              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1709     (insert ","))
1710   (insert (or (message-fetch-reply-field "newsgroups") "")))
1711
1712 \f
1713
1714 ;;; Various commands
1715
1716 (defun message-delete-not-region (beg end)
1717   "Delete everything in the body of the current message that is outside of the region."
1718   (interactive "r")
1719   (save-excursion
1720     (goto-char end)
1721     (delete-region (point) (if (not (message-goto-signature))
1722                                (point)
1723                              (forward-line -2)
1724                              (point)))
1725     (insert "\n")
1726     (goto-char beg)
1727     (delete-region beg (progn (message-goto-body)
1728                               (forward-line 2)
1729                               (point))))
1730   (when (message-goto-signature)
1731     (forward-line -2)))
1732
1733 (defun message-kill-to-signature ()
1734   "Deletes all text up to the signature."
1735   (interactive)
1736   (let ((point (point)))
1737     (message-goto-signature)
1738     (unless (eobp)
1739       (forward-line -2))
1740     (kill-region point (point))
1741     (unless (bolp)
1742       (insert "\n"))))
1743
1744 (defun message-newline-and-reformat (&optional not-break)
1745   "Insert four newlines, and then reformat if inside quoted text."
1746   (interactive)
1747   (let (quoted point beg end leading-space)
1748     (setq point (point))
1749     (beginning-of-line)
1750     (setq beg (point))
1751     ;; Find first line of the paragraph.
1752     (if not-break
1753         (while (and (not (eobp)) 
1754                     (not (looking-at message-cite-prefix-regexp))
1755                 (looking-at paragraph-start))
1756           (forward-line 1)))
1757     ;; Find the prefix
1758     (when (looking-at message-cite-prefix-regexp)
1759       (setq quoted (match-string 0))
1760       (goto-char (match-end 0))
1761       (looking-at "[ \t]*")
1762       (setq leading-space (match-string 0)))
1763     (if (and quoted
1764              (not not-break)
1765              (< (- point beg) (length quoted)))
1766         ;; break in the cite prefix.
1767         (setq quoted nil
1768               end nil))
1769     (if quoted
1770         (progn
1771           (forward-line 1)
1772           (while (and (not (eobp))
1773                       (not (looking-at paragraph-separate))
1774                       (looking-at message-cite-prefix-regexp)
1775                       (equal quoted (match-string 0)))
1776             (goto-char (match-end 0))
1777             (looking-at "[ \t]*")
1778             (if (> (length leading-space) (length (match-string 0)))
1779                 (setq leading-space (match-string 0)))
1780             (forward-line 1))
1781           (setq end (point))
1782           (goto-char beg)
1783           (while (and (if (bobp) nil (forward-line -1) t)
1784                       (not (looking-at paragraph-start))
1785                       (looking-at message-cite-prefix-regexp)
1786                       (equal quoted (match-string 0)))
1787             (setq beg (point))
1788             (goto-char (match-end 0))
1789             (looking-at "[ \t]*")
1790             (if (> (length leading-space) (length (match-string 0)))
1791                 (setq leading-space (match-string 0)))))
1792       (while (and (not (eobp))
1793                   (not (looking-at paragraph-separate))
1794                   (not (looking-at message-cite-prefix-regexp)))
1795         (forward-line 1))
1796       (setq end (point))
1797       (goto-char beg)
1798       (while (and (if (bobp) nil (forward-line -1) t)
1799                   (not (looking-at paragraph-start))
1800                   (not (looking-at message-cite-prefix-regexp)))
1801         (setq beg (point))))
1802     (goto-char point)
1803     (save-restriction
1804       (narrow-to-region beg end)
1805       (if not-break
1806           (setq point nil)
1807         (insert "\n\n")
1808         (setq point (point))
1809         (insert "\n\n")
1810         (delete-region (point) (re-search-forward "[ \t]*"))
1811         (when quoted
1812           (insert quoted leading-space)))
1813       (if quoted
1814           (let* ((adaptive-fill-regexp 
1815                  (regexp-quote (concat quoted leading-space)))
1816                  (adaptive-fill-first-line-regexp 
1817                   adaptive-fill-regexp ))
1818             (fill-paragraph nil))
1819         (fill-paragraph nil))
1820       (if point (goto-char point)))))
1821
1822 (defun message-fill-paragraph ()
1823   "Like `fill-paragraph'."
1824   (interactive)
1825   (message-newline-and-reformat t))
1826
1827 (defun message-insert-signature (&optional force)
1828   "Insert a signature.  See documentation for the `message-signature' variable."
1829   (interactive (list 0))
1830   (let* ((signature
1831           (cond
1832            ((and (null message-signature)
1833                  (eq force 0))
1834             (save-excursion
1835               (goto-char (point-max))
1836               (not (re-search-backward message-signature-separator nil t))))
1837            ((and (null message-signature)
1838                  force)
1839             t)
1840            ((message-functionp message-signature)
1841             (funcall message-signature))
1842            ((listp message-signature)
1843             (eval message-signature))
1844            (t message-signature)))
1845          (signature
1846           (cond ((stringp signature)
1847                  signature)
1848                 ((and (eq t signature)
1849                       message-signature-file
1850                       (file-exists-p message-signature-file))
1851                  signature))))
1852     (when signature
1853       (goto-char (point-max))
1854       ;; Insert the signature.
1855       (unless (bolp)
1856         (insert "\n"))
1857       (insert "\n-- \n")
1858       (if (eq signature t)
1859           (insert-file-contents message-signature-file)
1860         (insert signature))
1861       (goto-char (point-max))
1862       (or (bolp) (insert "\n")))))
1863
1864 (defun message-elide-region (b e)
1865   "Elide the text between point and mark.
1866 An ellipsis (from `message-elide-ellipsis') will be inserted where the
1867 text was killed."
1868   (interactive "r")
1869   (kill-region b e)
1870   (insert message-elide-ellipsis))
1871
1872 (defvar message-caesar-translation-table nil)
1873
1874 (defun message-caesar-region (b e &optional n)
1875   "Caesar rotation of region by N, default 13, for decrypting netnews."
1876   (interactive
1877    (list
1878     (min (point) (or (mark t) (point)))
1879     (max (point) (or (mark t) (point)))
1880     (when current-prefix-arg
1881       (prefix-numeric-value current-prefix-arg))))
1882
1883   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1884   (unless (or (zerop n)                 ; no action needed for a rot of 0
1885               (= b e))                  ; no region to rotate
1886     ;; We build the table, if necessary.
1887     (when (or (not message-caesar-translation-table)
1888               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1889       (setq message-caesar-translation-table
1890             (message-make-caesar-translation-table n)))
1891     (translate-region b e message-caesar-translation-table)))
1892
1893 (defun message-make-caesar-translation-table (n)
1894   "Create a rot table with offset N."
1895   (let ((i -1)
1896         (table (make-string 256 0)))
1897     (while (< (incf i) 256)
1898       (aset table i i))
1899     (concat
1900      (substring table 0 ?A)
1901      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1902      (substring table ?A (+ ?A n))
1903      (substring table (+ ?A 26) ?a)
1904      (substring table (+ ?a n) (+ ?a n (- 26 n)))
1905      (substring table ?a (+ ?a n))
1906      (substring table (+ ?a 26) 255))))
1907
1908 (defun message-caesar-buffer-body (&optional rotnum)
1909   "Caesar rotates all letters in the current buffer by 13 places.
1910 Used to encode/decode possiblyun offensive messages (commonly in net.jokes).
1911 With prefix arg, specifies the number of places to rotate each letter forward.
1912 Mail and USENET news headers are not rotated."
1913   (interactive (if current-prefix-arg
1914                    (list (prefix-numeric-value current-prefix-arg))
1915                  (list nil)))
1916   (save-excursion
1917     (save-restriction
1918       (when (message-goto-body)
1919         (narrow-to-region (point) (point-max)))
1920       (message-caesar-region (point-min) (point-max) rotnum))))
1921
1922 (defun message-pipe-buffer-body (program)
1923   "Pipe the message body in the current buffer through PROGRAM."
1924   (save-excursion
1925     (save-restriction
1926       (when (message-goto-body)
1927         (narrow-to-region (point) (point-max)))
1928       (shell-command-on-region
1929        (point-min) (point-max) program nil t))))
1930
1931 (defun message-rename-buffer (&optional enter-string)
1932   "Rename the *message* buffer to \"*message* RECIPIENT\".
1933 If the function is run with a prefix, it will ask for a new buffer
1934 name, rather than giving an automatic name."
1935   (interactive "Pbuffer name: ")
1936   (save-excursion
1937     (save-restriction
1938       (goto-char (point-min))
1939       (narrow-to-region (point)
1940                         (search-forward mail-header-separator nil 'end))
1941       (let* ((mail-to (or
1942                        (if (message-news-p) (message-fetch-field "Newsgroups")
1943                          (message-fetch-field "To"))
1944                        ""))
1945              (mail-trimmed-to
1946               (if (string-match "," mail-to)
1947                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1948                 mail-to))
1949              (name-default (concat "*message* " mail-trimmed-to))
1950              (name (if enter-string
1951                        (read-string "New buffer name: " name-default)
1952                      name-default)))
1953         (rename-buffer name t)))))
1954
1955 (defun message-fill-yanked-message (&optional justifyp)
1956   "Fill the paragraphs of a message yanked into this one.
1957 Numeric argument means justify as well."
1958   (interactive "P")
1959   (save-excursion
1960     (goto-char (point-min))
1961     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1962     (let ((fill-prefix message-yank-prefix))
1963       (fill-individual-paragraphs (point) (point-max) justifyp))))
1964
1965 (defun message-indent-citation ()
1966   "Modify text just inserted from a message to be cited.
1967 The inserted text should be the region.
1968 When this function returns, the region is again around the modified text.
1969
1970 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1971 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1972   (let ((start (point)))
1973     ;; Remove unwanted headers.
1974     (when message-ignored-cited-headers
1975       (let (all-removed)
1976         (save-restriction
1977           (narrow-to-region
1978            (goto-char start)
1979            (if (search-forward "\n\n" nil t)
1980                (1- (point))
1981              (point)))
1982           (message-remove-header message-ignored-cited-headers t)
1983           (when (= (point-min) (point-max))
1984             (setq all-removed t))
1985           (goto-char (point-max)))
1986         (if all-removed
1987             (goto-char start)
1988           (forward-line 1))))
1989     ;; Delete blank lines at the start of the buffer.
1990     (while (and (point-min)
1991                 (eolp)
1992                 (not (eobp)))
1993       (message-delete-line))
1994     ;; Delete blank lines at the end of the buffer.
1995     (goto-char (point-max))
1996     (unless (eolp)
1997       (insert "\n"))
1998     (while (and (zerop (forward-line -1))
1999                 (looking-at "$"))
2000       (message-delete-line))
2001     ;; Do the indentation.
2002     (if (null message-yank-prefix)
2003         (indent-rigidly start (mark t) message-indentation-spaces)
2004       (save-excursion
2005         (goto-char start)
2006         (while (< (point) (mark t))
2007           (insert message-yank-prefix)
2008           (forward-line 1))))
2009     (goto-char start)))
2010
2011 (defun message-yank-original (&optional arg)
2012   "Insert the message being replied to, if any.
2013 Puts point before the text and mark after.
2014 Normally indents each nonblank line ARG spaces (default 3).  However,
2015 if `message-yank-prefix' is non-nil, insert that prefix on each line.
2016
2017 This function uses `message-cite-function' to do the actual citing.
2018
2019 Just \\[universal-argument] as argument means don't indent, insert no
2020 prefix, and don't delete any headers."
2021   (interactive "P")
2022   (let ((modified (buffer-modified-p)))
2023     (when (and message-reply-buffer
2024                message-cite-function)
2025       (delete-windows-on message-reply-buffer t)
2026       (insert-buffer message-reply-buffer)
2027       (funcall message-cite-function)
2028       (message-exchange-point-and-mark)
2029       (unless (bolp)
2030         (insert ?\n))
2031       (unless modified
2032         (setq message-checksum (message-checksum))))))
2033
2034 (defun message-yank-buffer (buffer)
2035   "Insert BUFFER into the current buffer and quote it."
2036   (interactive "bYank buffer: ")
2037   (let ((message-reply-buffer buffer))
2038     (save-window-excursion
2039       (message-yank-original))))
2040
2041 (defun message-buffers ()
2042   "Return a list of active message buffers."
2043   (let (buffers)
2044     (save-excursion
2045       (dolist (buffer (buffer-list t))
2046         (set-buffer buffer)
2047         (when (and (eq major-mode 'message-mode)
2048                    (null message-sent-message-via))
2049           (push (buffer-name buffer) buffers))))
2050     (nreverse buffers)))
2051
2052 (defun message-cite-original-without-signature ()
2053   "Cite function in the standard Message manner."
2054   (let ((start (point))
2055         (end (mark t))
2056         (functions
2057          (when message-indent-citation-function
2058            (if (listp message-indent-citation-function)
2059                message-indent-citation-function
2060              (list message-indent-citation-function)))))
2061     (mml-quote-region start end)
2062     ;; Allow undoing.
2063     (undo-boundary)
2064     (goto-char end)
2065     (when (re-search-backward message-signature-separator start t)
2066       ;; Also peel off any blank lines before the signature.
2067       (forward-line -1)
2068       (while (looking-at "^[ \t]*$")
2069         (forward-line -1))
2070       (forward-line 1)
2071       (delete-region (point) end))
2072     (goto-char start)
2073     (while functions
2074       (funcall (pop functions)))
2075     (when message-citation-line-function
2076       (unless (bolp)
2077         (insert "\n"))
2078       (funcall message-citation-line-function))))
2079
2080 (eval-when-compile (defvar mail-citation-hook))         ;Compiler directive
2081 (defun message-cite-original ()
2082   "Cite function in the standard Message manner."
2083   (if (and (boundp 'mail-citation-hook)
2084            mail-citation-hook)
2085       (run-hooks 'mail-citation-hook)
2086     (let ((start (point))
2087           (end (mark t))
2088           (functions
2089            (when message-indent-citation-function
2090              (if (listp message-indent-citation-function)
2091                  message-indent-citation-function
2092                (list message-indent-citation-function)))))
2093       (mml-quote-region start end)
2094       (goto-char start)
2095       (while functions
2096         (funcall (pop functions)))
2097       (when message-citation-line-function
2098         (unless (bolp)
2099           (insert "\n"))
2100         (funcall message-citation-line-function)))))
2101
2102 (defun message-insert-citation-line ()
2103   "Function that inserts a simple citation line."
2104   (when message-reply-headers
2105     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
2106
2107 (defun message-position-on-field (header &rest afters)
2108   (let ((case-fold-search t))
2109     (save-restriction
2110       (narrow-to-region
2111        (goto-char (point-min))
2112        (progn
2113          (re-search-forward
2114           (concat "^" (regexp-quote mail-header-separator) "$"))
2115          (match-beginning 0)))
2116       (goto-char (point-min))
2117       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
2118           (progn
2119             (re-search-forward "^[^ \t]" nil 'move)
2120             (beginning-of-line)
2121             (skip-chars-backward "\n")
2122             t)
2123         (while (and afters
2124                     (not (re-search-forward
2125                           (concat "^" (regexp-quote (car afters)) ":")
2126                           nil t)))
2127           (pop afters))
2128         (when afters
2129           (re-search-forward "^[^ \t]" nil 'move)
2130           (beginning-of-line))
2131         (insert header ": \n")
2132         (forward-char -1)
2133         nil))))
2134
2135 (defun message-remove-signature ()
2136   "Remove the signature from the text between point and mark.
2137 The text will also be indented the normal way."
2138   (save-excursion
2139     (let ((start (point))
2140           mark)
2141       (if (not (re-search-forward message-signature-separator (mark t) t))
2142           ;; No signature here, so we just indent the cited text.
2143           (message-indent-citation)
2144         ;; Find the last non-empty line.
2145         (forward-line -1)
2146         (while (looking-at "[ \t]*$")
2147           (forward-line -1))
2148         (forward-line 1)
2149         (setq mark (set-marker (make-marker) (point)))
2150         (goto-char start)
2151         (message-indent-citation)
2152         ;; Enable undoing the deletion.
2153         (undo-boundary)
2154         (delete-region mark (mark t))
2155         (set-marker mark nil)))))
2156
2157 \f
2158
2159 ;;;
2160 ;;; Sending messages
2161 ;;;
2162
2163 (defun message-send-and-exit (&optional arg)
2164   "Send message like `message-send', then, if no errors, exit from mail buffer."
2165   (interactive "P")
2166   (let ((buf (current-buffer))
2167         (actions message-exit-actions))
2168     (when (and (message-send arg)
2169                (buffer-name buf))
2170       (if message-kill-buffer-on-exit
2171           (kill-buffer buf)
2172         (bury-buffer buf)
2173         (when (eq buf (current-buffer))
2174           (message-bury buf)))
2175       (message-do-actions actions)
2176       t)))
2177
2178 (defun message-dont-send ()
2179   "Don't send the message you have been editing."
2180   (interactive)
2181   (set-buffer-modified-p t)
2182   (save-buffer)
2183   (let ((actions message-postpone-actions))
2184     (message-bury (current-buffer))
2185     (message-do-actions actions)))
2186
2187 (defun message-kill-buffer ()
2188   "Kill the current buffer."
2189   (interactive)
2190   (when (or (not (buffer-modified-p))
2191             (yes-or-no-p "Message modified; kill anyway? "))
2192     (let ((actions message-kill-actions))
2193       (setq buffer-file-name nil)
2194       (kill-buffer (current-buffer))
2195       (message-do-actions actions))))
2196
2197 (defun message-bury (buffer)
2198   "Bury this mail buffer."
2199   (let ((newbuf (other-buffer buffer)))
2200     (bury-buffer buffer)
2201     (if (and (fboundp 'frame-parameters)
2202              (cdr (assq 'dedicated (frame-parameters)))
2203              (not (null (delq (selected-frame) (visible-frame-list)))))
2204         (delete-frame (selected-frame))
2205       (switch-to-buffer newbuf))))
2206
2207 (defun message-send (&optional arg)
2208   "Send the message in the current buffer.
2209 If `message-interactive' is non-nil, wait for success indication or
2210 error messages, and inform user.
2211 Otherwise any failure is reported in a message back to the user from
2212 the mailer.
2213 The usage of ARG is defined by the instance that called Message.
2214 It should typically alter the sending method in some way or other."
2215   (interactive "P")
2216   ;; Make it possible to undo the coming changes.
2217   (undo-boundary)
2218   (let ((inhibit-read-only t))
2219     (put-text-property (point-min) (point-max) 'read-only nil))
2220   (message-fix-before-sending)
2221   (run-hooks 'message-send-hook)
2222   (message message-sending-message)
2223   (let ((alist message-send-method-alist)
2224         (success t)
2225         elem sent
2226         (message-options message-options))
2227     (message-options-set-recipient)
2228     (while (and success
2229                 (setq elem (pop alist)))
2230       (when (funcall (cadr elem))
2231         (when (and (or (not (memq (car elem)
2232                                   message-sent-message-via))
2233                        (if (or (message-gnksa-enable-p 'multiple-copies)
2234                                (not (eq (car elem) 'news)))
2235                            (y-or-n-p
2236                             (format
2237                              "Already sent message via %s; resend? "
2238                              (car elem)))
2239                          (error "Denied posting -- multiple copies.")))
2240                    (setq success (funcall (caddr elem) arg)))
2241           (setq sent t))))
2242     (unless (or sent (not success))
2243       (error "No methods specified to send by"))
2244     (when (and success sent)
2245       (message-do-fcc)
2246       (save-excursion
2247         (run-hooks 'message-sent-hook))
2248       (message "Sending...done")
2249       ;; Mark the buffer as unmodified and delete auto-save.
2250       (set-buffer-modified-p nil)
2251       (delete-auto-save-file-if-necessary t)
2252       (message-disassociate-draft)
2253       ;; Delete other mail buffers and stuff.
2254       (message-do-send-housekeeping)
2255       (message-do-actions message-send-actions)
2256       ;; Return success.
2257       t)))
2258
2259 (defun message-send-via-mail (arg)
2260   "Send the current message via mail."
2261   (message-send-mail arg))
2262
2263 (defun message-send-via-news (arg)
2264   "Send the current message via news."
2265   (funcall message-send-news-function arg))
2266
2267 (defmacro message-check (type &rest forms)
2268   "Eval FORMS if TYPE is to be checked."
2269   `(or (message-check-element ,type)
2270        (save-excursion
2271          ,@forms)))
2272
2273 (put 'message-check 'lisp-indent-function 1)
2274 (put 'message-check 'edebug-form-spec '(form body))
2275
2276 (defun message-fix-before-sending ()
2277   "Do various things to make the message nice before sending it."
2278   ;; Make sure there's a newline at the end of the message.
2279   (goto-char (point-max))
2280   (unless (bolp)
2281     (insert "\n"))
2282   ;; Delete all invisible text.
2283   (message-check 'invisible-text
2284     (when (text-property-any (point-min) (point-max) 'invisible t)
2285       (put-text-property (point-min) (point-max) 'invisible nil)
2286       (unless (yes-or-no-p
2287                "Invisible text found and made visible; continue posting? ")
2288         (error "Invisible text found and made visible")))))
2289
2290 (defun message-add-action (action &rest types)
2291   "Add ACTION to be performed when doing an exit of type TYPES."
2292   (let (var)
2293     (while types
2294       (set (setq var (intern (format "message-%s-actions" (pop types))))
2295            (nconc (symbol-value var) (list action))))))
2296
2297 (defun message-do-actions (actions)
2298   "Perform all actions in ACTIONS."
2299   ;; Now perform actions on successful sending.
2300   (while actions
2301     (ignore-errors
2302       (cond
2303        ;; A simple function.
2304        ((message-functionp (car actions))
2305         (funcall (car actions)))
2306        ;; Something to be evaled.
2307        (t
2308         (eval (car actions)))))
2309     (pop actions)))
2310
2311 (defun message-send-mail-partially ()
2312   "Sendmail as message/partial."
2313   ;; replace the header delimiter with a blank line
2314   (goto-char (point-min))
2315   (re-search-forward
2316    (concat "^" (regexp-quote mail-header-separator) "\n"))
2317   (replace-match "\n")
2318   (run-hooks 'message-send-mail-hook)
2319   (let ((p (goto-char (point-min)))
2320         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
2321         (curbuf (current-buffer))
2322         (id (message-make-message-id)) (n 1)
2323         plist total  header required-mail-headers)
2324     (while (not (eobp))
2325       (if (< (point-max) (+ p message-send-mail-partially-limit))
2326           (goto-char (point-max))
2327         (goto-char (+ p message-send-mail-partially-limit))
2328         (beginning-of-line)
2329         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
2330       (push p plist)
2331       (setq p (point)))
2332     (setq total (length plist))
2333     (push (point-max) plist)
2334     (setq plist (nreverse plist))
2335     (unwind-protect
2336         (save-excursion
2337           (setq p (pop plist))
2338           (while plist
2339             (set-buffer curbuf)
2340             (copy-to-buffer tembuf p (car plist))
2341             (set-buffer tembuf)
2342             (goto-char (point-min))
2343             (if header
2344                 (progn
2345                   (goto-char (point-min))
2346                   (narrow-to-region (point) (point))
2347                   (insert header))
2348               (message-goto-eoh)
2349               (setq header (buffer-substring (point-min) (point)))
2350               (goto-char (point-min))
2351               (narrow-to-region (point) (point))
2352               (insert header)
2353               (message-remove-header "Mime-Version")
2354               (message-remove-header "Content-Type")
2355               (message-remove-header "Content-Transfer-Encoding")
2356               (message-remove-header "Message-ID")
2357               (message-remove-header "Lines")
2358               (goto-char (point-max))
2359               (insert "Mime-Version: 1.0\n")
2360               (setq header (buffer-substring (point-min) (point-max))))
2361             (goto-char (point-max))
2362             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n"
2363                             id n total))
2364             (let ((mail-header-separator ""))
2365               (when (memq 'Message-ID message-required-mail-headers)
2366                 (insert "Message-ID: " (message-make-message-id) "\n"))
2367               (when (memq 'Lines message-required-mail-headers)
2368                 (let ((mail-header-separator ""))
2369                   (insert "Lines: " (message-make-lines) "\n")))
2370               (message-goto-subject)
2371               (end-of-line)
2372               (insert (format " (%d/%d)" n total))
2373               (goto-char (point-max))
2374               (insert "\n")
2375               (widen)
2376               (mm-with-unibyte-current-buffer
2377                 (funcall message-send-mail-function)))
2378             (setq n (+ n 1))
2379             (setq p (pop plist))
2380             (erase-buffer)))
2381       (kill-buffer tembuf))))
2382
2383 (defun message-send-mail (&optional arg)
2384   (require 'mail-utils)
2385   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2386          (case-fold-search nil)
2387          (news (message-news-p))
2388          (mailbuf (current-buffer))
2389          (message-this-is-mail t)
2390          (message-posting-charset
2391           (if (fboundp 'gnus-setup-posting-charset)
2392               (gnus-setup-posting-charset nil)
2393             message-posting-charset)))
2394     (save-restriction
2395       (message-narrow-to-headers)
2396       ;; Insert some headers.
2397       (let ((message-deletable-headers
2398              (if news nil message-deletable-headers)))
2399         (message-generate-headers message-required-mail-headers))
2400       ;; Let the user do all of the above.
2401       (run-hooks 'message-header-hook))
2402     (unwind-protect
2403         (save-excursion
2404           (set-buffer tembuf)
2405           (erase-buffer)
2406           ;; Avoid copying text props.
2407           (insert (with-current-buffer mailbuf
2408                     (buffer-substring-no-properties (point-min) (point-max))))
2409           ;; Remove some headers.
2410           (message-encode-message-body)
2411           (save-restriction
2412             (message-narrow-to-headers)
2413             ;; We (re)generate the Lines header.
2414             (when (memq 'Lines message-required-mail-headers)
2415               (message-generate-headers '(Lines)))
2416             ;; Remove some headers.
2417             (message-remove-header message-ignored-mail-headers t)
2418             (let ((mail-parse-charset message-default-charset))
2419               (mail-encode-encoded-word-buffer)))
2420           (goto-char (point-max))
2421           ;; require one newline at the end.
2422           (or (= (preceding-char) ?\n)
2423               (insert ?\n))
2424           (when 
2425               (save-restriction
2426                 (message-narrow-to-headers)
2427                 (and news
2428                      (or (message-fetch-field "cc")
2429                          (message-fetch-field "to"))
2430                      (string= "text/plain"
2431                               (car
2432                                (mail-header-parse-content-type
2433                                 (message-fetch-field "content-type"))))))
2434             (message-insert-courtesy-copy))
2435           (if (or (not message-send-mail-partially-limit)
2436                   (< (point-max) message-send-mail-partially-limit)
2437                   (not (y-or-n-p "The message size is too large, should it be sent partially?")))
2438               (mm-with-unibyte-current-buffer
2439                 (funcall message-send-mail-function))
2440             (message-send-mail-partially)))
2441       (kill-buffer tembuf))
2442     (set-buffer mailbuf)
2443     (push 'mail message-sent-message-via)))
2444
2445 (defun message-send-mail-with-sendmail ()
2446   "Send off the prepared buffer with sendmail."
2447   (let ((errbuf (if message-interactive
2448                     (message-generate-new-buffer-clone-locals
2449                      " sendmail errors")
2450                   0))
2451         resend-to-addresses delimline)
2452     (let ((case-fold-search t))
2453       (save-restriction
2454         (message-narrow-to-headers)
2455         (setq resend-to-addresses (message-fetch-field "resent-to")))
2456       ;; Change header-delimiter to be what sendmail expects.
2457       (goto-char (point-min))
2458       (re-search-forward
2459        (concat "^" (regexp-quote mail-header-separator) "\n"))
2460       (replace-match "\n")
2461       (backward-char 1)
2462       (setq delimline (point-marker))
2463       (run-hooks 'message-send-mail-hook)
2464       ;; Insert an extra newline if we need it to work around
2465       ;; Sun's bug that swallows newlines.
2466       (goto-char (1+ delimline))
2467       (when (eval message-mailer-swallows-blank-line)
2468         (newline))
2469       (when message-interactive
2470         (save-excursion
2471           (set-buffer errbuf)
2472           (erase-buffer))))
2473     (let ((default-directory "/")
2474           (coding-system-for-write message-send-coding-system))
2475       (apply 'call-process-region
2476              (append (list (point-min) (point-max)
2477                            (if (boundp 'sendmail-program)
2478                                sendmail-program
2479                              "/usr/lib/sendmail")
2480                            nil errbuf nil "-oi")
2481                      ;; Always specify who from,
2482                      ;; since some systems have broken sendmails.
2483                      ;; But some systems are more broken with -f, so
2484                      ;; we'll let users override this.
2485                      (if (null message-sendmail-f-is-evil)
2486                          (list "-f" (message-make-address)))
2487                      ;; These mean "report errors by mail"
2488                      ;; and "deliver in background".
2489                      (if (null message-interactive) '("-oem" "-odb"))
2490                      ;; Get the addresses from the message
2491                      ;; unless this is a resend.
2492                      ;; We must not do that for a resend
2493                      ;; because we would find the original addresses.
2494                      ;; For a resend, include the specific addresses.
2495                      (if resend-to-addresses
2496                          (list resend-to-addresses)
2497                        '("-t")))))
2498     (when message-interactive
2499       (save-excursion
2500         (set-buffer errbuf)
2501         (goto-char (point-min))
2502         (while (re-search-forward "\n\n* *" nil t)
2503           (replace-match "; "))
2504         (if (not (zerop (buffer-size)))
2505             (error "Sending...failed to %s"
2506                    (buffer-substring (point-min) (point-max)))))
2507       (when (bufferp errbuf)
2508         (kill-buffer errbuf)))))
2509
2510 (defun message-send-mail-with-qmail ()
2511   "Pass the prepared message buffer to qmail-inject.
2512 Refer to the documentation for the variable `message-send-mail-function'
2513 to find out how to use this."
2514   ;; replace the header delimiter with a blank line
2515   (goto-char (point-min))
2516   (re-search-forward
2517    (concat "^" (regexp-quote mail-header-separator) "\n"))
2518   (replace-match "\n")
2519   (run-hooks 'message-send-mail-hook)
2520   ;; send the message
2521   (case
2522       (let ((coding-system-for-write message-send-coding-system))
2523         (apply
2524          'call-process-region 1 (point-max) message-qmail-inject-program
2525          nil nil nil
2526          ;; qmail-inject's default behaviour is to look for addresses on the
2527          ;; command line; if there're none, it scans the headers.
2528          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2529          ;;
2530          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2531          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2532          ;; message from stdin.
2533          ;;
2534          ;; qmail also has the advantage of not having been raped by
2535          ;; various vendors, so we don't have to allow for that, either --
2536          ;; compare this with message-send-mail-with-sendmail and weep
2537          ;; for sendmail's lost innocence.
2538          ;;
2539          ;; all this is way cool coz it lets us keep the arguments entirely
2540          ;; free for -inject-arguments -- a big win for the user and for us
2541          ;; since we don't have to play that double-guessing game and the user
2542          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2543          message-qmail-inject-args))
2544     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2545     ;; we have to look at the retval instead
2546     (0 nil)
2547     (1   (error "qmail-inject reported permanent failure"))
2548     (111 (error "qmail-inject reported transient failure"))
2549     ;; should never happen
2550     (t   (error "qmail-inject reported unknown failure"))))
2551
2552 (defun message-send-mail-with-mh ()
2553   "Send the prepared message buffer with mh."
2554   (let ((mh-previous-window-config nil)
2555         (name (mh-new-draft-name)))
2556     (setq buffer-file-name name)
2557     ;; MH wants to generate these headers itself.
2558     (when message-mh-deletable-headers
2559       (let ((headers message-mh-deletable-headers))
2560         (while headers
2561           (goto-char (point-min))
2562           (and (re-search-forward
2563                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2564                (message-delete-line))
2565           (pop headers))))
2566     (run-hooks 'message-send-mail-hook)
2567     ;; Pass it on to mh.
2568     (mh-send-letter)))
2569
2570 (defun message-send-news (&optional arg)
2571   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2572          (case-fold-search nil)
2573          (method (if (message-functionp message-post-method)
2574                      (funcall message-post-method arg)
2575                    message-post-method))
2576          (group-name-charset (gnus-group-name-charset method ""))
2577          (rfc2047-header-encoding-alist
2578           (if group-name-charset
2579               (cons (cons "Newsgroups" group-name-charset)
2580                     rfc2047-header-encoding-alist)
2581             rfc2047-header-encoding-alist))
2582          (messbuf (current-buffer))
2583          (message-syntax-checks
2584           (if arg
2585               (cons '(existing-newsgroups . disabled)
2586                     message-syntax-checks)
2587             message-syntax-checks))
2588          (message-this-is-news t)
2589          (message-posting-charset (gnus-setup-posting-charset 
2590                                    (save-restriction
2591                                      (message-narrow-to-headers-or-head)
2592                                      (message-fetch-field "Newsgroups"))))
2593          result)
2594     (if (not (message-check-news-body-syntax))
2595         nil
2596       (save-restriction
2597         (message-narrow-to-headers)
2598         ;; Insert some headers.
2599         (message-generate-headers message-required-news-headers)
2600         ;; Let the user do all of the above.
2601         (run-hooks 'message-header-hook))
2602       (if group-name-charset
2603           (setq message-syntax-checks
2604               (cons '(valid-newsgroups . disabled)
2605                     message-syntax-checks)))
2606       (message-cleanup-headers)
2607       (if (not (message-check-news-syntax))
2608           nil
2609         (unwind-protect
2610             (save-excursion
2611               (set-buffer tembuf)
2612               (buffer-disable-undo)
2613               (erase-buffer)
2614               ;; Avoid copying text props.
2615               (insert (with-current-buffer messbuf
2616                         (buffer-substring-no-properties 
2617                          (point-min) (point-max))))
2618               (message-encode-message-body)
2619               ;; Remove some headers.
2620               (save-restriction
2621                 (message-narrow-to-headers)
2622                 ;; We (re)generate the Lines header.
2623                 (when (memq 'Lines message-required-mail-headers)
2624                   (message-generate-headers '(Lines)))
2625                 ;; Remove some headers.
2626                 (message-remove-header message-ignored-news-headers t)
2627                 (let ((mail-parse-charset message-default-charset))
2628                   (mail-encode-encoded-word-buffer)))
2629               (goto-char (point-max))
2630               ;; require one newline at the end.
2631               (or (= (preceding-char) ?\n)
2632                   (insert ?\n))
2633               (let ((case-fold-search t))
2634                 ;; Remove the delimiter.
2635                 (goto-char (point-min))
2636                 (re-search-forward
2637                  (concat "^" (regexp-quote mail-header-separator) "\n"))
2638                 (replace-match "\n")
2639                 (backward-char 1))
2640               (run-hooks 'message-send-news-hook)
2641               (gnus-open-server method)
2642               (setq result (let ((mail-header-separator ""))
2643                              (gnus-request-post method))))
2644           (kill-buffer tembuf))
2645         (set-buffer messbuf)
2646         (if result
2647             (push 'news message-sent-message-via)
2648           (message "Couldn't send message via news: %s"
2649                    (nnheader-get-report (car method)))
2650           nil)))))
2651
2652 ;;;
2653 ;;; Header generation & syntax checking.
2654 ;;;
2655
2656 (defun message-check-element (type)
2657   "Returns non-nil if this type is not to be checked."
2658   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2659       t
2660     (let ((able (assq type message-syntax-checks)))
2661       (and (consp able)
2662            (eq (cdr able) 'disabled)))))
2663
2664 (defun message-check-news-syntax ()
2665   "Check the syntax of the message."
2666   (save-excursion
2667     (save-restriction
2668       (widen)
2669       ;; We narrow to the headers and check them first.
2670       (save-excursion
2671         (save-restriction
2672           (message-narrow-to-headers)
2673           (message-check-news-header-syntax))))))
2674
2675 (defun message-check-news-header-syntax ()
2676   (and
2677    ;; Check Newsgroups header.
2678    (message-check 'newsgroups
2679      (let ((group (message-fetch-field "newsgroups")))
2680        (or
2681         (and group
2682              (not (string-match "\\`[ \t]*\\'" group)))
2683         (ignore
2684          (message
2685           "The newsgroups field is empty or missing.  Posting is denied.")))))
2686    ;; Check the Subject header.
2687    (message-check 'subject
2688      (let* ((case-fold-search t)
2689             (subject (message-fetch-field "subject")))
2690        (or
2691         (and subject
2692              (not (string-match "\\`[ \t]*\\'" subject)))
2693         (ignore
2694          (message
2695           "The subject field is empty or missing.  Posting is denied.")))))
2696    ;; Check for commands in Subject.
2697    (message-check 'subject-cmsg
2698      (if (string-match "^cmsg " (message-fetch-field "subject"))
2699          (y-or-n-p
2700           "The control code \"cmsg\" is in the subject.  Really post? ")
2701        t))
2702    ;; Check for multiple identical headers.
2703    (message-check 'multiple-headers
2704      (let (found)
2705        (while (and (not found)
2706                    (re-search-forward "^[^ \t:]+: " nil t))
2707          (save-excursion
2708            (or (re-search-forward
2709                 (concat "^"
2710                         (regexp-quote
2711                          (setq found
2712                                (buffer-substring
2713                                 (match-beginning 0) (- (match-end 0) 2))))
2714                         ":")
2715                 nil t)
2716                (setq found nil))))
2717        (if found
2718            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2719          t)))
2720    ;; Check for Version and Sendsys.
2721    (message-check 'sendsys
2722      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2723          (y-or-n-p
2724           (format "The article contains a %s command.  Really post? "
2725                   (buffer-substring (match-beginning 0)
2726                                     (1- (match-end 0)))))
2727        t))
2728    ;; See whether we can shorten Followup-To.
2729    (message-check 'shorten-followup-to
2730      (let ((newsgroups (message-fetch-field "newsgroups"))
2731            (followup-to (message-fetch-field "followup-to"))
2732            to)
2733        (when (and newsgroups
2734                   (string-match "," newsgroups)
2735                   (not followup-to)
2736                   (not
2737                    (zerop
2738                     (length
2739                      (setq to (completing-read
2740                                "Followups to: (default all groups) "
2741                                (mapcar (lambda (g) (list g))
2742                                        (cons "poster"
2743                                              (message-tokenize-header
2744                                               newsgroups)))))))))
2745          (goto-char (point-min))
2746          (insert "Followup-To: " to "\n"))
2747        t))
2748    ;; Check "Shoot me".
2749    (message-check 'shoot
2750      (if (re-search-forward
2751           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2752          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2753        t))
2754    ;; Check for Approved.
2755    (message-check 'approved
2756      (if (re-search-forward "^Approved:" nil t)
2757          (y-or-n-p "The article contains an Approved header.  Really post? ")
2758        t))
2759    ;; Check the Message-ID header.
2760    (message-check 'message-id
2761      (let* ((case-fold-search t)
2762             (message-id (message-fetch-field "message-id" t)))
2763        (or (not message-id)
2764            ;; Is there an @ in the ID?
2765            (and (string-match "@" message-id)
2766                 ;; Is there a dot in the ID?
2767                 (string-match "@[^.]*\\." message-id)
2768                 ;; Does the ID end with a dot?
2769                 (not (string-match "\\.>" message-id)))
2770            (y-or-n-p
2771             (format "The Message-ID looks strange: \"%s\".  Really post? "
2772                     message-id)))))
2773    ;; Check the Newsgroups & Followup-To headers.
2774    (message-check 'existing-newsgroups
2775      (let* ((case-fold-search t)
2776             (newsgroups (message-fetch-field "newsgroups"))
2777             (followup-to (message-fetch-field "followup-to"))
2778             (groups (message-tokenize-header
2779                      (if followup-to
2780                          (concat newsgroups "," followup-to)
2781                        newsgroups)))
2782             (hashtb (and (boundp 'gnus-active-hashtb)
2783                          gnus-active-hashtb))
2784             errors)
2785        (if (or (not hashtb)
2786                (not (boundp 'gnus-read-active-file))
2787                (not gnus-read-active-file)
2788                (eq gnus-read-active-file 'some))
2789            t
2790          (while groups
2791            (when (and (not (boundp (intern (car groups) hashtb)))
2792                       (not (equal (car groups) "poster")))
2793              (push (car groups) errors))
2794            (pop groups))
2795          (if (not errors)
2796              t
2797            (y-or-n-p
2798             (format
2799              "Really post to %s unknown group%s: %s "
2800              (if (= (length errors) 1) "this" "these")
2801              (if (= (length errors) 1) "" "s")
2802              (mapconcat 'identity errors ", ")))))))
2803    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2804    (message-check 'valid-newsgroups
2805      (let ((case-fold-search t)
2806            (headers '("Newsgroups" "Followup-To"))
2807            header error)
2808        (while (and headers (not error))
2809          (when (setq header (mail-fetch-field (car headers)))
2810            (if (or
2811                 (not
2812                  (string-match
2813                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2814                   header))
2815                 (memq
2816                  nil (mapcar
2817                       (lambda (g)
2818                         (not (string-match "\\.\\'\\|\\.\\." g)))
2819                       (message-tokenize-header header ","))))
2820                (setq error t)))
2821          (unless error
2822            (pop headers)))
2823        (if (not error)
2824            t
2825          (y-or-n-p
2826           (format "The %s header looks odd: \"%s\".  Really post? "
2827                   (car headers) header)))))
2828    (message-check 'repeated-newsgroups
2829      (let ((case-fold-search t)
2830            (headers '("Newsgroups" "Followup-To"))
2831            header error groups group)
2832        (while (and headers
2833                    (not error))
2834          (when (setq header (mail-fetch-field (pop headers)))
2835            (setq groups (message-tokenize-header header ","))
2836            (while (setq group (pop groups))
2837              (when (member group groups)
2838                (setq error group
2839                      groups nil)))))
2840        (if (not error)
2841            t
2842          (y-or-n-p
2843           (format "Group %s is repeated in headers.  Really post? " error)))))
2844    ;; Check the From header.
2845    (message-check 'from
2846      (let* ((case-fold-search t)
2847             (from (message-fetch-field "from"))
2848             ad)
2849        (cond
2850         ((not from)
2851          (message "There is no From line.  Posting is denied.")
2852          nil)
2853         ((or (not (string-match
2854                    "@[^\\.]*\\."
2855                    (setq ad (nth 1 (mail-extract-address-components
2856                                     from))))) ;larsi@ifi
2857              (string-match "\\.\\." ad) ;larsi@ifi..uio
2858              (string-match "@\\." ad)   ;larsi@.ifi.uio
2859              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2860              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2861              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2862          (message
2863           "Denied posting -- the From looks strange: \"%s\"." from)
2864          nil)
2865         (t t))))))
2866
2867 (defun message-check-news-body-syntax ()
2868   (and
2869    ;; Check for long lines.
2870    (message-check 'long-lines
2871      (goto-char (point-min))
2872      (re-search-forward
2873       (concat "^" (regexp-quote mail-header-separator) "$"))
2874      (while (and
2875              (progn
2876                (end-of-line)
2877                (< (current-column) 80))
2878              (zerop (forward-line 1))))
2879      (or (bolp)
2880          (eobp)
2881          (y-or-n-p
2882           "You have lines longer than 79 characters.  Really post? ")))
2883    ;; Check whether the article is empty.
2884    (message-check 'empty
2885      (goto-char (point-min))
2886      (re-search-forward
2887       (concat "^" (regexp-quote mail-header-separator) "$"))
2888      (forward-line 1)
2889      (let ((b (point)))
2890        (goto-char (point-max))
2891        (re-search-backward message-signature-separator nil t)
2892        (beginning-of-line)
2893        (or (re-search-backward "[^ \n\t]" b t)
2894            (if (message-gnksa-enable-p 'empty-article)
2895                (y-or-n-p "Empty article.  Really post? ")
2896              (message "Denied posting -- Empty article.")
2897              nil))))
2898    ;; Check for control characters.
2899    (message-check 'control-chars
2900      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
2901          (y-or-n-p
2902           "The article contains control characters.  Really post? ")
2903        t))
2904    ;; Check excessive size.
2905    (message-check 'size
2906      (if (> (buffer-size) 60000)
2907          (y-or-n-p
2908           (format "The article is %d octets long.  Really post? "
2909                   (buffer-size)))
2910        t))
2911    ;; Check whether any new text has been added.
2912    (message-check 'new-text
2913      (or
2914       (not message-checksum)
2915       (not (eq (message-checksum) message-checksum))
2916       (if (message-gnksa-enable-p 'quoted-text-only)
2917           (y-or-n-p
2918            "It looks like no new text has been added.  Really post? ")
2919         (message "Denied posting -- no new text has been added.")
2920         nil)))
2921    ;; Check the length of the signature.
2922    (message-check 'signature
2923      (goto-char (point-max))
2924      (if (> (count-lines (point) (point-max)) 5)
2925          (y-or-n-p
2926           (format
2927            "Your .sig is %d lines; it should be max 4.  Really post? "
2928            (1- (count-lines (point) (point-max)))))
2929        t))
2930    ;; Ensure that text follows last quoted portion.
2931    (message-check 'quoting-style
2932      (goto-char (point-max))
2933      (let ((no-problem t))
2934        (when (search-backward-regexp "^>[^\n]*\n" nil t)
2935          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
2936        (if no-problem
2937            t
2938          (if (message-gnksa-enable-p 'quoted-text-only)
2939              (y-or-n-p "Your text should follow quoted text.  Really post? ")
2940            ;; Ensure that
2941            (goto-char (point-min))
2942            (re-search-forward
2943             (concat "^" (regexp-quote mail-header-separator) "$"))
2944            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
2945                (y-or-n-p "Your text should follow quoted text.  Really post? ")
2946              (message "Denied posting -- only quoted text.")
2947              nil)))))))
2948
2949 (defun message-checksum ()
2950   "Return a \"checksum\" for the current buffer."
2951   (let ((sum 0))
2952     (save-excursion
2953       (goto-char (point-min))
2954       (re-search-forward
2955        (concat "^" (regexp-quote mail-header-separator) "$"))
2956       (while (not (eobp))
2957         (when (not (looking-at "[ \t\n]"))
2958           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
2959                             (char-after))))
2960         (forward-char 1)))
2961     sum))
2962
2963 (defun message-do-fcc ()
2964   "Process Fcc headers in the current buffer."
2965   (let ((case-fold-search t)
2966         (buf (current-buffer))
2967         list file)
2968     (save-excursion
2969       (set-buffer (get-buffer-create " *message temp*"))
2970       (erase-buffer)
2971       (insert-buffer-substring buf)
2972       (save-restriction
2973         (message-narrow-to-headers)
2974         (while (setq file (message-fetch-field "fcc"))
2975           (push file list)
2976           (message-remove-header "fcc" nil t)))
2977       (message-encode-message-body)
2978       (save-restriction
2979         (message-narrow-to-headers)
2980         (let ((mail-parse-charset message-default-charset)
2981               (rfc2047-header-encoding-alist
2982                (cons '("Newsgroups" . default)
2983                      rfc2047-header-encoding-alist)))
2984           (mail-encode-encoded-word-buffer)))
2985       (goto-char (point-min))
2986       (when (re-search-forward
2987              (concat "^" (regexp-quote mail-header-separator) "$")
2988              nil t)
2989         (replace-match "" t t ))
2990       ;; Process FCC operations.
2991       (while list
2992         (setq file (pop list))
2993         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
2994             ;; Pipe the article to the program in question.
2995             (call-process-region (point-min) (point-max) shell-file-name
2996                                  nil nil nil shell-command-switch
2997                                  (match-string 1 file))
2998           ;; Save the article.
2999           (setq file (expand-file-name file))
3000           (unless (file-exists-p (file-name-directory file))
3001             (make-directory (file-name-directory file) t))
3002           (if (and message-fcc-handler-function
3003                    (not (eq message-fcc-handler-function 'rmail-output)))
3004               (funcall message-fcc-handler-function file)
3005             (if (and (file-readable-p file) (mail-file-babyl-p file))
3006                 (rmail-output file 1 nil t)
3007               (let ((mail-use-rfc822 t))
3008                 (rmail-output file 1 t t))))))
3009       (kill-buffer (current-buffer)))))
3010
3011 (defun message-output (filename)
3012   "Append this article to Unix/babyl mail file.."
3013   (if (and (file-readable-p filename)
3014            (mail-file-babyl-p filename))
3015       (gnus-output-to-rmail filename t)
3016     (gnus-output-to-mail filename t)))
3017
3018 (defun message-cleanup-headers ()
3019   "Do various automatic cleanups of the headers."
3020   ;; Remove empty lines in the header.
3021   (save-restriction
3022     (message-narrow-to-headers)
3023     ;; Remove blank lines.
3024     (while (re-search-forward "^[ \t]*\n" nil t)
3025       (replace-match "" t t))
3026
3027     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
3028     ;; spaces to comma and eliminate spaces around commas.  Eliminate
3029     ;; embedded line breaks.
3030     (goto-char (point-min))
3031     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
3032       (save-restriction
3033         (narrow-to-region
3034          (point)
3035          (if (re-search-forward "^[^ \t]" nil t)
3036              (match-beginning 0)
3037            (forward-line 1)
3038            (point)))
3039         (goto-char (point-min))
3040         (while (re-search-forward "\n[ \t]+" nil t)
3041           (replace-match " " t t))      ;No line breaks (too confusing)
3042         (goto-char (point-min))
3043         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
3044           (replace-match "," t t))
3045         (goto-char (point-min))
3046         ;; Remove trailing commas.
3047         (when (re-search-forward ",+$" nil t)
3048           (replace-match "" t t))))))
3049
3050 (defun message-make-date (&optional now)
3051   "Make a valid data header.
3052 If NOW, use that time instead."
3053   (let* ((now (or now (current-time)))
3054          (zone (nth 8 (decode-time now)))
3055          (sign "+"))
3056     (when (< zone 0)
3057       (setq sign "-")
3058       (setq zone (- zone)))
3059     (concat
3060      (format-time-string "%d" now)
3061      ;; The month name of the %b spec is locale-specific.  Pfff.
3062      (format " %s "
3063              (capitalize (car (rassoc (nth 4 (decode-time now))
3064                                       parse-time-months))))
3065      (format-time-string "%Y %H:%M:%S " now)
3066      ;; We do all of this because XEmacs doesn't have the %z spec.
3067      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
3068
3069 (defun message-make-message-id ()
3070   "Make a unique Message-ID."
3071   (concat "<" (message-unique-id)
3072           (let ((psubject (save-excursion (message-fetch-field "subject")))
3073                 (psupersedes
3074                  (save-excursion (message-fetch-field "supersedes"))))
3075             (if (or
3076                  (and message-reply-headers
3077                       (mail-header-references message-reply-headers)
3078                       (mail-header-subject message-reply-headers)
3079                       psubject
3080                       (not (string=
3081                             (message-strip-subject-re
3082                              (mail-header-subject message-reply-headers))
3083                             (message-strip-subject-re psubject))))
3084                  (and psupersedes
3085                       (string-match "_-_@" psupersedes)))
3086                 "_-_" ""))
3087           "@" (message-make-fqdn) ">"))
3088
3089 (defvar message-unique-id-char nil)
3090
3091 ;; If you ever change this function, make sure the new version
3092 ;; cannot generate IDs that the old version could.
3093 ;; You might for example insert a "." somewhere (not next to another dot
3094 ;; or string boundary), or modify the "fsf" string.
3095 (defun message-unique-id ()
3096   ;; Don't use microseconds from (current-time), they may be unsupported.
3097   ;; Instead we use this randomly inited counter.
3098   (setq message-unique-id-char
3099         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
3100            ;; (current-time) returns 16-bit ints,
3101            ;; and 2^16*25 just fits into 4 digits i base 36.
3102            (* 25 25)))
3103   (let ((tm (current-time)))
3104     (concat
3105      (if (memq system-type '(ms-dos emx vax-vms))
3106          (let ((user (downcase (user-login-name))))
3107            (while (string-match "[^a-z0-9_]" user)
3108              (aset user (match-beginning 0) ?_))
3109            user)
3110        (message-number-base36 (user-uid) -1))
3111      (message-number-base36 (+ (car   tm)
3112                                (lsh (% message-unique-id-char 25) 16)) 4)
3113      (message-number-base36 (+ (nth 1 tm)
3114                                (lsh (/ message-unique-id-char 25) 16)) 4)
3115      ;; Append the newsreader name, because while the generated
3116      ;; ID is unique to this newsreader, other newsreaders might
3117      ;; otherwise generate the same ID via another algorithm.
3118      ".fsf")))
3119
3120 (defun message-number-base36 (num len)
3121   (if (if (< len 0)
3122           (<= num 0)
3123         (= len 0))
3124       ""
3125     (concat (message-number-base36 (/ num 36) (1- len))
3126             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
3127                                   (% num 36))))))
3128
3129 (defun message-make-organization ()
3130   "Make an Organization header."
3131   (let* ((organization
3132           (when message-user-organization
3133             (if (message-functionp message-user-organization)
3134                 (funcall message-user-organization)
3135               message-user-organization))))
3136     (save-excursion
3137       (message-set-work-buffer)
3138       (cond ((stringp organization)
3139              (insert organization))
3140             ((and (eq t organization)
3141                   message-user-organization-file
3142                   (file-exists-p message-user-organization-file))
3143              (insert-file-contents message-user-organization-file)))
3144       (goto-char (point-min))
3145       (while (re-search-forward "[\t\n]+" nil t)
3146         (replace-match "" t t))
3147       (unless (zerop (buffer-size))
3148         (buffer-string)))))
3149
3150 (defun message-make-lines ()
3151   "Count the number of lines and return numeric string."
3152   (save-excursion
3153     (save-restriction
3154       (widen)
3155       (goto-char (point-min))
3156       (re-search-forward
3157        (concat "^" (regexp-quote mail-header-separator) "$"))
3158       (forward-line 1)
3159       (int-to-string (count-lines (point) (point-max))))))
3160
3161 (defun message-make-in-reply-to ()
3162   "Return the In-Reply-To header for this message."
3163   (when message-reply-headers
3164     (mail-header-message-id message-reply-headers)))
3165
3166 (defun message-make-distribution ()
3167   "Make a Distribution header."
3168   (let ((orig-distribution (message-fetch-reply-field "distribution")))
3169     (cond ((message-functionp message-distribution-function)
3170            (funcall message-distribution-function))
3171           (t orig-distribution))))
3172
3173 (defun message-make-expires ()
3174   "Return an Expires header based on `message-expires'."
3175   (let ((current (current-time))
3176         (future (* 1.0 message-expires 60 60 24)))
3177     ;; Add the future to current.
3178     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
3179     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
3180     (message-make-date current)))
3181
3182 (defun message-make-path ()
3183   "Return uucp path."
3184   (let ((login-name (user-login-name)))
3185     (cond ((null message-user-path)
3186            (concat (system-name) "!" login-name))
3187           ((stringp message-user-path)
3188            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
3189            (concat message-user-path "!" login-name))
3190           (t login-name))))
3191
3192 (defun message-make-from ()
3193   "Make a From header."
3194   (let* ((style message-from-style)
3195          (login (message-make-address))
3196          (fullname
3197           (or (and (boundp 'user-full-name)
3198                    user-full-name)
3199               (user-full-name))))
3200     (when (string= fullname "&")
3201       (setq fullname (user-login-name)))
3202     (save-excursion
3203       (message-set-work-buffer)
3204       (cond
3205        ((or (null style)
3206             (equal fullname ""))
3207         (insert login))
3208        ((or (eq style 'angles)
3209             (and (not (eq style 'parens))
3210                  ;; Use angles if no quoting is needed, or if parens would
3211                  ;; need quoting too.
3212                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
3213                      (let ((tmp (concat fullname nil)))
3214                        (while (string-match "([^()]*)" tmp)
3215                          (aset tmp (match-beginning 0) ?-)
3216                          (aset tmp (1- (match-end 0)) ?-))
3217                        (string-match "[\\()]" tmp)))))
3218         (insert fullname)
3219         (goto-char (point-min))
3220         ;; Look for a character that cannot appear unquoted
3221         ;; according to RFC 822.
3222         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
3223           ;; Quote fullname, escaping specials.
3224           (goto-char (point-min))
3225           (insert "\"")
3226           (while (re-search-forward "[\"\\]" nil 1)
3227             (replace-match "\\\\\\&" t))
3228           (insert "\""))
3229         (insert " <" login ">"))
3230        (t                               ; 'parens or default
3231         (insert login " (")
3232         (let ((fullname-start (point)))
3233           (insert fullname)
3234           (goto-char fullname-start)
3235           ;; RFC 822 says \ and nonmatching parentheses
3236           ;; must be escaped in comments.
3237           ;; Escape every instance of ()\ ...
3238           (while (re-search-forward "[()\\]" nil 1)
3239             (replace-match "\\\\\\&" t))
3240           ;; ... then undo escaping of matching parentheses,
3241           ;; including matching nested parentheses.
3242           (goto-char fullname-start)
3243           (while (re-search-forward
3244                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3245                   nil 1)
3246             (replace-match "\\1(\\3)" t)
3247             (goto-char fullname-start)))
3248         (insert ")")))
3249       (buffer-string))))
3250
3251 (defun message-make-sender ()
3252   "Return the \"real\" user address.
3253 This function tries to ignore all user modifications, and
3254 give as trustworthy answer as possible."
3255   (concat (user-login-name) "@" (system-name)))
3256
3257 (defun message-make-address ()
3258   "Make the address of the user."
3259   (or (message-user-mail-address)
3260       (concat (user-login-name) "@" (message-make-domain))))
3261
3262 (defun message-user-mail-address ()
3263   "Return the pertinent part of `user-mail-address'."
3264   (when user-mail-address
3265     (if (string-match " " user-mail-address)
3266         (nth 1 (mail-extract-address-components user-mail-address))
3267       user-mail-address)))
3268
3269 (defun message-make-fqdn ()
3270   "Return user's fully qualified domain name."
3271   (let ((system-name (system-name))
3272         (user-mail (message-user-mail-address)))
3273     (cond
3274      ((string-match "[^.]\\.[^.]" system-name)
3275       ;; `system-name' returned the right result.
3276       system-name)
3277      ;; Try `mail-host-address'.
3278      ((and (boundp 'mail-host-address)
3279            (stringp mail-host-address)
3280            (string-match "\\." mail-host-address))
3281       mail-host-address)
3282      ;; We try `user-mail-address' as a backup.
3283      ((and user-mail
3284            (string-match "\\." user-mail)
3285            (string-match "@\\(.*\\)\\'" user-mail))
3286       (match-string 1 user-mail))
3287      ;; Default to this bogus thing.
3288      (t
3289       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
3290
3291 (defun message-make-host-name ()
3292   "Return the name of the host."
3293   (let ((fqdn (message-make-fqdn)))
3294     (string-match "^[^.]+\\." fqdn)
3295     (substring fqdn 0 (1- (match-end 0)))))
3296
3297 (defun message-make-domain ()
3298   "Return the domain name."
3299   (or mail-host-address
3300       (message-make-fqdn)))
3301
3302 (defun message-generate-headers (headers)
3303   "Prepare article HEADERS.
3304 Headers already prepared in the buffer are not modified."
3305   (save-restriction
3306     (message-narrow-to-headers)
3307     (let* ((Date (message-make-date))
3308            (Message-ID (message-make-message-id))
3309            (Organization (message-make-organization))
3310            (From (message-make-from))
3311            (Path (message-make-path))
3312            (Subject nil)
3313            (Newsgroups nil)
3314            (In-Reply-To (message-make-in-reply-to))
3315            (To nil)
3316            (Distribution (message-make-distribution))
3317            (Lines (message-make-lines))
3318            (User-Agent message-newsreader)
3319            (Expires (message-make-expires))
3320            (case-fold-search t)
3321            header value elem)
3322       ;; First we remove any old generated headers.
3323       (let ((headers message-deletable-headers))
3324         (unless (buffer-modified-p)
3325           (setq headers (delq 'Message-ID (copy-sequence headers))))
3326         (while headers
3327           (goto-char (point-min))
3328           (and (re-search-forward
3329                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3330                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3331                (message-delete-line))
3332           (pop headers)))
3333       ;; Go through all the required headers and see if they are in the
3334       ;; articles already.  If they are not, or are empty, they are
3335       ;; inserted automatically - except for Subject, Newsgroups and
3336       ;; Distribution.
3337       (while headers
3338         (goto-char (point-min))
3339         (setq elem (pop headers))
3340         (if (consp elem)
3341             (if (eq (car elem) 'optional)
3342                 (setq header (cdr elem))
3343               (setq header (car elem)))
3344           (setq header elem))
3345         (when (or (not (re-search-forward
3346                         (concat "^"
3347                                 (regexp-quote
3348                                  (downcase
3349                                   (if (stringp header)
3350                                       header
3351                                     (symbol-name header))))
3352                                 ":")
3353                         nil t))
3354                   (progn
3355                     ;; The header was found.  We insert a space after the
3356                     ;; colon, if there is none.
3357                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
3358                     ;; Find out whether the header is empty...
3359                     (looking-at "[ \t]*\n[^ \t]")))
3360           ;; So we find out what value we should insert.
3361           (setq value
3362                 (cond
3363                  ((and (consp elem) (eq (car elem) 'optional))
3364                   ;; This is an optional header.  If the cdr of this
3365                   ;; is something that is nil, then we do not insert
3366                   ;; this header.
3367                   (setq header (cdr elem))
3368                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3369                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3370                  ((consp elem)
3371                   ;; The element is a cons.  Either the cdr is a
3372                   ;; string to be inserted verbatim, or it is a
3373                   ;; function, and we insert the value returned from
3374                   ;; this function.
3375                   (or (and (stringp (cdr elem)) (cdr elem))
3376                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3377                  ((and (boundp header) (symbol-value header))
3378                   ;; The element is a symbol.  We insert the value
3379                   ;; of this symbol, if any.
3380                   (symbol-value header))
3381                  ((not (message-check-element header))
3382                   ;; We couldn't generate a value for this header,
3383                   ;; so we just ask the user.
3384                   (read-from-minibuffer
3385                    (format "Empty header for %s; enter value: " header)))))
3386           ;; Finally insert the header.
3387           (when (and value
3388                      (not (equal value "")))
3389             (save-excursion
3390               (if (bolp)
3391                   (progn
3392                     ;; This header didn't exist, so we insert it.
3393                     (goto-char (point-max))
3394                     (insert (if (stringp header) header (symbol-name header))
3395                             ": " value "\n")
3396                     (forward-line -1))
3397                 ;; The value of this header was empty, so we clear
3398                 ;; totally and insert the new value.
3399                 (delete-region (point) (gnus-point-at-eol))
3400                 (insert value))
3401               ;; Add the deletable property to the headers that require it.
3402               (and (memq header message-deletable-headers)
3403                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3404                    (add-text-properties
3405                     (point) (match-end 0)
3406                     '(message-deletable t face italic) (current-buffer)))))))
3407       ;; Insert new Sender if the From is strange.
3408       (let ((from (message-fetch-field "from"))
3409             (sender (message-fetch-field "sender"))
3410             (secure-sender (message-make-sender)))
3411         (when (and from
3412                    (not (message-check-element 'sender))
3413                    (not (string=
3414                          (downcase
3415                           (cadr (mail-extract-address-components from)))
3416                          (downcase secure-sender)))
3417                    (or (null sender)
3418                        (not
3419                         (string=
3420                          (downcase
3421                           (cadr (mail-extract-address-components sender)))
3422                          (downcase secure-sender)))))
3423           (goto-char (point-min))
3424           ;; Rename any old Sender headers to Original-Sender.
3425           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3426             (beginning-of-line)
3427             (insert "Original-")
3428             (beginning-of-line))
3429           (when (or (message-news-p)
3430                     (string-match "@.+\\.." secure-sender))
3431             (insert "Sender: " secure-sender "\n")))))))
3432
3433 (defun message-insert-courtesy-copy ()
3434   "Insert a courtesy message in mail copies of combined messages."
3435   (let (newsgroups)
3436     (save-excursion
3437       (save-restriction
3438         (message-narrow-to-headers)
3439         (when (setq newsgroups (message-fetch-field "newsgroups"))
3440           (goto-char (point-max))
3441           (insert "Posted-To: " newsgroups "\n")))
3442       (forward-line 1)
3443       (when message-courtesy-message
3444         (cond
3445          ((string-match "%s" message-courtesy-message)
3446           (insert (format message-courtesy-message newsgroups)))
3447          (t
3448           (insert message-courtesy-message)))))))
3449
3450 ;;;
3451 ;;; Setting up a message buffer
3452 ;;;
3453
3454 (defun message-fill-address (header value)
3455   (save-restriction
3456     (narrow-to-region (point) (point))
3457     (insert (capitalize (symbol-name header))
3458             ": "
3459             (if (consp value) (car value) value)
3460             "\n")
3461     (narrow-to-region (point-min) (1- (point-max)))
3462     (let (quoted last)
3463       (goto-char (point-min))
3464       (while (not (eobp))
3465         (skip-chars-forward "^,\"" (point-max))
3466         (if (or (eq (char-after) ?,)
3467                 (eobp))
3468             (when (not quoted)
3469               (if (and (> (current-column) 78)
3470                        last)
3471                   (progn
3472                     (save-excursion
3473                       (goto-char last)
3474                       (insert "\n\t"))
3475                     (setq last (1+ (point))))
3476                 (setq last (1+ (point)))))
3477           (setq quoted (not quoted)))
3478         (unless (eobp)
3479           (forward-char 1))))
3480     (goto-char (point-max))
3481     (widen)
3482     (forward-line 1)))
3483
3484 (defun message-fill-header (header value)
3485   (let ((begin (point))
3486         (fill-column 78)
3487         (fill-prefix "\t"))
3488     (insert (capitalize (symbol-name header))
3489             ": "
3490             (if (consp value) (car value) value)
3491             "\n")
3492     (save-restriction
3493       (narrow-to-region begin (point))
3494       (fill-region-as-paragraph begin (point))
3495       ;; Tapdance around looong Message-IDs.
3496       (forward-line -1)
3497       (when (looking-at "[ \t]*$")
3498         (message-delete-line))
3499       (goto-char begin)
3500       (re-search-forward ":" nil t)
3501       (when (looking-at "\n[ \t]+")
3502         (replace-match " " t t))
3503       (goto-char (point-max)))))
3504
3505 (defun message-shorten-1 (list cut surplus)
3506   ;; Cut SURPLUS elements out of LIST, beginning with CUTth one.
3507   (setcdr (nthcdr (- cut 2) list)
3508           (nthcdr (+ (- cut 2) surplus 1) list)))
3509
3510 (defun message-shorten-references (header references)
3511   "Trim REFERENCES to be less than 31 Message-ID long, and fold them.
3512 If folding is disallowed, also check that the REFERENCES are less
3513 than 988 characters long, and if they are not, trim them until they are."
3514   (let ((maxcount 31)
3515         (count 0)
3516         (cut 6)
3517         refs)
3518     (with-temp-buffer
3519       (insert references)
3520       (goto-char (point-min))
3521       ;; Cons a list of valid references.
3522       (while (re-search-forward "<[^>]+>" nil t)
3523         (push (match-string 0) refs))
3524       (setq refs (nreverse refs)
3525             count (length refs)))
3526
3527     ;; If the list has more than MAXCOUNT elements, trim it by
3528     ;; removing the CUTth element and the required number of
3529     ;; elements that follow.
3530     (when (> count maxcount)
3531       (let ((surplus (- count maxcount)))
3532         (message-shorten-1 refs cut surplus)
3533         (decf count surplus)))
3534
3535     ;; If folding is disallowed, make sure the total length (including
3536     ;; the spaces between) will be less than MAXSIZE characters.
3537     ;;
3538     ;; Only disallow folding for News messages. At this point the headers
3539     ;; have not been generated, thus we use message-this-is-news directly.
3540     (when (and message-this-is-news message-cater-to-broken-inn)
3541       (let ((maxsize 988)
3542             (totalsize (+ (apply #'+ (mapcar #'length refs))
3543                           (1- count)))
3544             (surplus 0)
3545             (ptr (nthcdr (1- cut) refs)))
3546         ;; Decide how many elements to cut off...
3547         (while (> totalsize maxsize)
3548           (decf totalsize (1+ (length (car ptr))))
3549           (incf surplus)
3550           (setq ptr (cdr ptr)))
3551         ;; ...and do it.
3552         (when (> surplus 0)
3553           (message-shorten-1 refs cut surplus))))
3554
3555     ;; Finally, collect the references back into a string and insert
3556     ;; it into the buffer.
3557     (let ((refstring (mapconcat #'identity refs " ")))
3558       (if (and message-this-is-news message-cater-to-broken-inn)
3559           (insert (capitalize (symbol-name header)) ": "
3560                   refstring "\n")
3561         (message-fill-header header refstring)))))
3562
3563 (defun message-position-point ()
3564   "Move point to where the user probably wants to find it."
3565   (message-narrow-to-headers)
3566   (cond
3567    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3568     (search-backward ":" )
3569     (widen)
3570     (forward-char 1)
3571     (if (eq (char-after) ? )
3572         (forward-char 1)
3573       (insert " ")))
3574    (t
3575     (goto-char (point-max))
3576     (widen)
3577     (forward-line 1)
3578     (unless (looking-at "$")
3579       (forward-line 2)))
3580    (sit-for 0)))
3581
3582 (defun message-buffer-name (type &optional to group)
3583   "Return a new (unique) buffer name based on TYPE and TO."
3584   (cond
3585    ;; Generate a new buffer name The Message Way.
3586    ((eq message-generate-new-buffers 'unique)
3587     (generate-new-buffer-name
3588      (concat "*" type
3589              (if to
3590                  (concat " to "
3591                          (or (car (mail-extract-address-components to))
3592                              to) "")
3593                "")
3594              (if (and group (not (string= group ""))) (concat " on " group) "")
3595              "*")))
3596    ;; Check whether `message-generate-new-buffers' is a function,
3597    ;; and if so, call it.
3598    ((message-functionp message-generate-new-buffers)
3599     (funcall message-generate-new-buffers type to group))
3600    ((eq message-generate-new-buffers 'unsent)
3601     (generate-new-buffer-name
3602      (concat "*unsent " type
3603              (if to
3604                  (concat " to "
3605                          (or (car (mail-extract-address-components to))
3606                              to) "")
3607                "")
3608              (if (and group (not (string= group ""))) (concat " on " group) "")
3609              "*")))
3610    ;; Use standard name.
3611    (t
3612     (format "*%s message*" type))))
3613
3614 (defun message-pop-to-buffer (name)
3615   "Pop to buffer NAME, and warn if it already exists and is modified."
3616   (let ((buffer (get-buffer name)))
3617     (if (and buffer
3618              (buffer-name buffer))
3619         (progn
3620           (set-buffer (pop-to-buffer buffer))
3621           (when (and (buffer-modified-p)
3622                      (not (y-or-n-p
3623                            "Message already being composed; erase? ")))
3624             (error "Message being composed")))
3625       (set-buffer (pop-to-buffer name)))
3626     (erase-buffer)
3627     (message-mode)))
3628
3629 (defun message-do-send-housekeeping ()
3630   "Kill old message buffers."
3631   ;; We might have sent this buffer already.  Delete it from the
3632   ;; list of buffers.
3633   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3634   (while (and message-max-buffers
3635               message-buffer-list
3636               (>= (length message-buffer-list) message-max-buffers))
3637     ;; Kill the oldest buffer -- unless it has been changed.
3638     (let ((buffer (pop message-buffer-list)))
3639       (when (and (buffer-name buffer)
3640                  (not (buffer-modified-p buffer)))
3641         (kill-buffer buffer))))
3642   ;; Rename the buffer.
3643   (if message-send-rename-function
3644       (funcall message-send-rename-function)
3645     (when (string-match "\\`\\*\\(unsent \\)?" (buffer-name))
3646       (rename-buffer
3647        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3648   ;; Push the current buffer onto the list.
3649   (when message-max-buffers
3650     (setq message-buffer-list
3651           (nconc message-buffer-list (list (current-buffer))))))
3652
3653 ;;;(defvar mc-modes-alist)
3654 (defun message-setup (headers &optional replybuffer actions)
3655 ;;;   (when (and (boundp 'mc-modes-alist)
3656 ;;;          (not (assq 'message-mode mc-modes-alist)))
3657 ;;;     (push '(message-mode (encrypt . mc-encrypt-message)
3658 ;;;                      (sign . mc-sign-message))
3659 ;;;       mc-modes-alist))
3660   (when actions
3661     (setq message-send-actions actions))
3662   (setq message-reply-buffer replybuffer)
3663   (goto-char (point-min))
3664   ;; Insert all the headers.
3665   (mail-header-format
3666    (let ((h headers)
3667          (alist message-header-format-alist))
3668      (while h
3669        (unless (assq (caar h) message-header-format-alist)
3670          (push (list (caar h)) alist))
3671        (pop h))
3672      alist)
3673    headers)
3674   (delete-region (point) (progn (forward-line -1) (point)))
3675   (when message-default-headers
3676     (insert message-default-headers)
3677     (or (bolp) (insert ?\n)))
3678   (put-text-property
3679    (point)
3680    (progn
3681      (insert mail-header-separator "\n")
3682      (1- (point)))
3683    'read-only nil)
3684   (forward-line -1)
3685   (when (message-news-p)
3686     (when message-default-news-headers
3687       (insert message-default-news-headers)
3688       (or (bolp) (insert ?\n)))
3689     (when message-generate-headers-first
3690       (message-generate-headers
3691        (delq 'Lines
3692              (delq 'Subject
3693                    (copy-sequence message-required-news-headers))))))
3694   (when (message-mail-p)
3695     (when message-default-mail-headers
3696       (insert message-default-mail-headers)
3697       (or (bolp) (insert ?\n)))
3698     (when message-generate-headers-first
3699       (message-generate-headers
3700        (delq 'Lines
3701              (delq 'Subject
3702                    (copy-sequence message-required-mail-headers))))))
3703   (run-hooks 'message-signature-setup-hook)
3704   (message-insert-signature)
3705   (save-restriction
3706     (message-narrow-to-headers)
3707     (if message-alternative-emails
3708         (message-use-alternative-email-as-from))
3709     (run-hooks 'message-header-setup-hook))
3710   (set-buffer-modified-p nil)
3711   (setq buffer-undo-list nil)
3712   (run-hooks 'message-setup-hook)
3713   (message-position-point)
3714   (undo-boundary))
3715
3716 (defun message-set-auto-save-file-name ()
3717   "Associate the message buffer with a file in the drafts directory."
3718   (when message-auto-save-directory
3719     (unless (file-directory-p
3720              (directory-file-name message-auto-save-directory))
3721       (gnus-make-directory message-auto-save-directory))
3722     (if (gnus-alive-p)
3723         (setq message-draft-article
3724               (nndraft-request-associate-buffer "drafts"))
3725       (setq buffer-file-name (expand-file-name "*message*"
3726                                                message-auto-save-directory))
3727       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
3728     (clear-visited-file-modtime)
3729     (setq buffer-file-coding-system message-draft-coding-system)))
3730
3731 (defun message-disassociate-draft ()
3732   "Disassociate the message buffer from the drafts directory."
3733   (when message-draft-article
3734     (nndraft-request-expire-articles
3735      (list message-draft-article) "drafts" nil t)))
3736
3737 (defun message-insert-headers ()
3738   "Generate the headers for the article."
3739   (interactive)
3740   (save-excursion
3741     (save-restriction
3742       (message-narrow-to-headers)
3743       (when (message-news-p)
3744         (message-generate-headers
3745          (delq 'Lines
3746                (delq 'Subject
3747                      (copy-sequence message-required-news-headers)))))
3748       (when (message-mail-p)
3749         (message-generate-headers
3750          (delq 'Lines
3751                (delq 'Subject
3752                      (copy-sequence message-required-mail-headers))))))))
3753
3754 \f
3755
3756 ;;;
3757 ;;; Commands for interfacing with message
3758 ;;;
3759
3760 ;;;###autoload
3761 (defun message-mail (&optional to subject
3762                                other-headers continue switch-function
3763                                yank-action send-actions)
3764   "Start editing a mail message to be sent.
3765 OTHER-HEADERS is an alist of header/value pairs."
3766   (interactive)
3767   (let ((message-this-is-mail t))
3768     (message-pop-to-buffer (message-buffer-name "mail" to))
3769     (message-setup
3770      (nconc
3771       `((To . ,(or to "")) (Subject . ,(or subject "")))
3772       (when other-headers other-headers)))))
3773
3774 ;;;###autoload
3775 (defun message-news (&optional newsgroups subject)
3776   "Start editing a news article to be sent."
3777   (interactive)
3778   (let ((message-this-is-news t))
3779     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3780     (message-setup `((Newsgroups . ,(or newsgroups ""))
3781                      (Subject . ,(or subject ""))))))
3782
3783 (defun message-get-reply-headers (wide &optional to-address)
3784   (let (follow-to mct never-mct from to cc reply-to mrt mft ccalist)
3785     ;; Find all relevant headers we need.
3786     (setq from (message-fetch-field "from")
3787           to (message-fetch-field "to")
3788           cc (message-fetch-field "cc")
3789           mct (message-fetch-field "mail-copies-to")
3790           reply-to (message-fetch-field "reply-to")
3791           mrt (message-fetch-field "mail-reply-to")
3792           mft (message-fetch-field "mail-followup-to"))
3793
3794     ;; Handle special values of Mail-Copies-To.
3795     (when mct
3796       (cond ((or (equal (downcase mct) "never")
3797                  (equal (downcase mct) "nobody"))
3798              (setq never-mct t)
3799              (setq mct nil))
3800             ((or (equal (downcase mct) "always")
3801                  (equal (downcase mct) "poster"))
3802              (setq mct (or mrt reply-to from)))))
3803
3804     (if (or (not wide)
3805             to-address)
3806         (progn
3807           (setq follow-to (list (cons 'To (or to-address mrt reply-to from))))
3808           (when (and wide (or mft mct))
3809             (push (cons 'Cc (or mft mct)) follow-to)))
3810       (let (ccalist)
3811         (save-excursion
3812           (message-set-work-buffer)
3813           (if (and mft
3814                    message-use-followup-to
3815                    (or (not (eq message-use-followup-to 'ask))
3816                        (message-y-or-n-p
3817                         (concat "Obey Mail-Followup-To? ") t "\
3818 You should normally obey the Mail-Followup-To: header.  In this
3819 article, it has the value of
3820
3821 " mft "
3822
3823 which directs your response to " (if (string-match "," mft)
3824                                "the specified addresses"
3825                              "that address only") ".
3826
3827 If a message is posted to several mailing lists, Mail-Followup-To is
3828 often used to direct the following discussion to one list only,
3829 because discussions that are spread over several lists tend to be
3830 fragmented and very difficult to follow.
3831
3832 Also, some source/announcement lists are not indented for discussion;
3833 responses here are directed to other addresses.")))
3834               (insert mft)
3835             (unless never-mct
3836               (insert (or mrt reply-to from "")))
3837             (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3838             (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3839             (insert (if cc (concat (if (bolp) "" ", ") cc) "")))
3840           (goto-char (point-min))
3841           (while (re-search-forward "[ \t]+" nil t)
3842             (replace-match " " t t))
3843           ;; Remove addresses that match `rmail-dont-reply-to-names'.
3844           (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
3845             (insert (prog1 (rmail-dont-reply-to (buffer-string))
3846                       (erase-buffer))))
3847           (goto-char (point-min))
3848           ;; Perhaps "Mail-Copies-To: never" removed the only address?
3849           (when (eobp)
3850             (insert (or mrt reply-to from "")))
3851           (setq ccalist
3852                 (mapcar
3853                  (lambda (addr)
3854                    (cons (mail-strip-quoted-names addr) addr))
3855                  (message-tokenize-header (buffer-string))))
3856           (let ((s ccalist))
3857             (while s
3858               (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3859         (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3860         (when ccalist
3861           (let ((ccs (cons 'Cc (mapconcat
3862                                 (lambda (addr) (cdr addr)) ccalist ", "))))
3863             (when (string-match "^ +" (cdr ccs))
3864               (setcdr ccs (substring (cdr ccs) (match-end 0))))
3865             (push ccs follow-to)))))
3866     follow-to))
3867
3868
3869 ;;;###autoload
3870 (defun message-reply (&optional to-address wide)
3871   "Start editing a reply to the article in the current buffer."
3872   (interactive)
3873   (require 'gnus-sum)                   ; for gnus-list-identifiers
3874   (let ((cur (current-buffer))
3875         from subject date reply-to to cc
3876         references message-id follow-to
3877         (inhibit-point-motion-hooks t)
3878         (message-this-is-mail t)
3879         gnus-warning)
3880     (save-restriction
3881       (message-narrow-to-head)
3882       ;; Allow customizations to have their say.
3883       (if (not wide)
3884           ;; This is a regular reply.
3885           (if (message-functionp message-reply-to-function)
3886               (setq follow-to (funcall message-reply-to-function)))
3887         ;; This is a followup.
3888         (if (message-functionp message-wide-reply-to-function)
3889             (save-excursion
3890               (setq follow-to
3891                     (funcall message-wide-reply-to-function)))))
3892       (setq message-id (message-fetch-field "message-id" t)
3893             references (message-fetch-field "references")
3894             date (message-fetch-field "date")
3895             from (message-fetch-field "from")
3896             subject (or (message-fetch-field "subject") "none"))
3897     (if gnus-list-identifiers
3898         (setq subject (message-strip-list-identifiers subject)))
3899     (setq subject (concat "Re: " (message-strip-subject-re subject)))
3900
3901     (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3902                (string-match "<[^>]+>" gnus-warning))
3903       (setq message-id (match-string 0 gnus-warning)))
3904
3905     (unless follow-to
3906       (setq follow-to (message-get-reply-headers wide to-address))))
3907
3908     (message-pop-to-buffer
3909      (message-buffer-name
3910       (if wide "wide reply" "reply") from
3911       (if wide to-address nil)))
3912
3913     (setq message-reply-headers
3914           (vector 0 subject from date message-id references 0 0 ""))
3915
3916     (message-setup
3917      `((Subject . ,subject)
3918        ,@follow-to
3919        ,@(if (or references message-id)
3920              `((References . ,(concat (or references "") (and references " ")
3921                                       (or message-id ""))))
3922            nil))
3923      cur)))
3924
3925 ;;;###autoload
3926 (defun message-wide-reply (&optional to-address)
3927   "Make a \"wide\" reply to the message in the current buffer."
3928   (interactive)
3929   (message-reply to-address t))
3930
3931 ;;;###autoload
3932 (defun message-followup (&optional to-newsgroups)
3933   "Follow up to the message in the current buffer.
3934 If TO-NEWSGROUPS, use that as the new Newsgroups line."
3935   (interactive)
3936   (require 'gnus-sum)                   ; for gnus-list-identifiers
3937   (let ((cur (current-buffer))
3938         from subject date reply-to mrt mct
3939         references message-id follow-to
3940         (inhibit-point-motion-hooks t)
3941         (message-this-is-news t)
3942         followup-to distribution newsgroups gnus-warning posted-to)
3943     (save-restriction
3944       (narrow-to-region
3945        (goto-char (point-min))
3946        (if (search-forward "\n\n" nil t)
3947            (1- (point))
3948          (point-max)))
3949       (when (message-functionp message-followup-to-function)
3950         (setq follow-to
3951               (funcall message-followup-to-function)))
3952       (setq from (message-fetch-field "from")
3953             date (message-fetch-field "date")
3954             subject (or (message-fetch-field "subject") "none")
3955             references (message-fetch-field "references")
3956             message-id (message-fetch-field "message-id" t)
3957             followup-to (message-fetch-field "followup-to")
3958             newsgroups (message-fetch-field "newsgroups")
3959             posted-to (message-fetch-field "posted-to")
3960             reply-to (message-fetch-field "reply-to")
3961             mrt (message-fetch-field "mail-reply-to")
3962             distribution (message-fetch-field "distribution")
3963             mct (message-fetch-field "mail-copies-to"))
3964       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3965                  (string-match "<[^>]+>" gnus-warning))
3966         (setq message-id (match-string 0 gnus-warning)))
3967       ;; Remove bogus distribution.
3968       (when (and (stringp distribution)
3969                  (let ((case-fold-search t))
3970                    (string-match "world" distribution)))
3971         (setq distribution nil))
3972       (if gnus-list-identifiers
3973           (setq subject (message-strip-list-identifiers subject)))
3974       (setq subject (concat "Re: " (message-strip-subject-re subject)))
3975       (widen))
3976
3977     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3978
3979     (message-setup
3980      `((Subject . ,subject)
3981        ,@(cond
3982           (to-newsgroups
3983            (list (cons 'Newsgroups to-newsgroups)))
3984           (follow-to follow-to)
3985           ((and followup-to message-use-followup-to)
3986            (list
3987             (cond
3988              ((equal (downcase followup-to) "poster")
3989               (if (or (eq message-use-followup-to 'use)
3990                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
3991 You should normally obey the Followup-To: header.
3992
3993 `Followup-To: poster' sends your response via e-mail instead of news.
3994
3995 A typical situation where `Followup-To: poster' is used is when the poster
3996 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3997                   (progn
3998                     (setq message-this-is-news nil)
3999                     (cons 'To (or mrt reply-to from "")))
4000                 (cons 'Newsgroups newsgroups)))
4001              (t
4002               (if (or (equal followup-to newsgroups)
4003                       (not (eq message-use-followup-to 'ask))
4004                       (message-y-or-n-p
4005                        (concat "Obey Followup-To: " followup-to "? ") t "\
4006 You should normally obey the Followup-To: header.
4007
4008         `Followup-To: " followup-to "'
4009 directs your response to " (if (string-match "," followup-to)
4010                                "the specified newsgroups"
4011                              "that newsgroup only") ".
4012
4013 If a message is posted to several newsgroups, Followup-To is often
4014 used to direct the following discussion to one newsgroup only,
4015 because discussions that are spread over several newsgroup tend to
4016 be fragmented and very difficult to follow.
4017
4018 Also, some source/announcement newsgroups are not indented for discussion;
4019 responses here are directed to other newsgroups."))
4020                   (cons 'Newsgroups followup-to)
4021                 (cons 'Newsgroups newsgroups))))))
4022           (posted-to
4023            `((Newsgroups . ,posted-to)))
4024           (t
4025            `((Newsgroups . ,newsgroups))))
4026        ,@(and distribution (list (cons 'Distribution distribution)))
4027        ,@(if (or references message-id)
4028              `((References . ,(concat (or references "") (and references " ")
4029                                       (or message-id "")))))
4030        ,@(when (and mct
4031                     (not (or (equal (downcase mct) "never")
4032                              (equal (downcase mct) "nobody"))))
4033            (list (cons 'Cc (if (or (equal (downcase mct) "always")
4034                                    (equal (downcase mct) "poster"))
4035                                (or mrt reply-to from "")
4036                              mct)))))
4037
4038      cur)
4039
4040     (setq message-reply-headers
4041           (vector 0 subject from date message-id references 0 0 ""))))
4042
4043
4044 ;;;###autoload
4045 (defun message-cancel-news (&optional arg)
4046   "Cancel an article you posted.
4047 If ARG, allow editing of the cancellation message."
4048   (interactive "P")
4049   (unless (message-news-p)
4050     (error "This is not a news article; canceling is impossible"))
4051   (when (yes-or-no-p "Do you really want to cancel this article? ")
4052     (let (from newsgroups message-id distribution buf sender)
4053       (save-excursion
4054         ;; Get header info from original article.
4055         (save-restriction
4056           (message-narrow-to-head)
4057           (setq from (message-fetch-field "from")
4058                 sender (message-fetch-field "sender")
4059                 newsgroups (message-fetch-field "newsgroups")
4060                 message-id (message-fetch-field "message-id" t)
4061                 distribution (message-fetch-field "distribution")))
4062         ;; Make sure that this article was written by the user.
4063         (unless (or (and sender
4064                          (string-equal
4065                           (downcase sender)
4066                           (downcase (message-make-sender))))
4067                     (string-equal
4068                      (downcase (cadr (mail-extract-address-components from)))
4069                      (downcase (cadr (mail-extract-address-components
4070                                       (message-make-from))))))
4071           (error "This article is not yours"))
4072         ;; Make control message.
4073         (if arg
4074             (message-news)
4075           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
4076         (erase-buffer)
4077         (insert "Newsgroups: " newsgroups "\n"
4078                "From: " from "\n"
4079                 "Subject: cmsg cancel " message-id "\n"
4080                 "Control: cancel " message-id "\n"
4081                 (if distribution
4082                     (concat "Distribution: " distribution "\n")
4083                   "")
4084                 mail-header-separator "\n"
4085                 message-cancel-message)
4086         (run-hooks 'message-cancel-hook)
4087         (unless arg
4088           (message "Canceling your article...")
4089           (if (let ((message-syntax-checks
4090                      'dont-check-for-anything-just-trust-me))
4091                 (funcall message-send-news-function))
4092               (message "Canceling your article...done"))
4093           (kill-buffer buf))))))
4094
4095 ;;;###autoload
4096 (defun message-supersede ()
4097   "Start composing a message to supersede the current message.
4098 This is done simply by taking the old article and adding a Supersedes
4099 header line with the old Message-ID."
4100   (interactive)
4101   (let ((cur (current-buffer))
4102         (sender (message-fetch-field "sender"))
4103         (from (message-fetch-field "from")))
4104     ;; Check whether the user owns the article that is to be superseded.
4105     (unless (or (and sender
4106                      (string-equal
4107                       (downcase sender)
4108                       (downcase (message-make-sender))))
4109                 (string-equal
4110                  (downcase (cadr (mail-extract-address-components from)))
4111                  (downcase (cadr (mail-extract-address-components
4112                                   (message-make-from))))))
4113       (error "This article is not yours"))
4114     ;; Get a normal message buffer.
4115     (message-pop-to-buffer (message-buffer-name "supersede"))
4116     (insert-buffer-substring cur)
4117     (mime-to-mml)
4118     (message-narrow-to-head)
4119     ;; Remove unwanted headers.
4120     (when message-ignored-supersedes-headers
4121       (message-remove-header message-ignored-supersedes-headers t))
4122     (goto-char (point-min))
4123     (if (not (re-search-forward "^Message-ID: " nil t))
4124         (error "No Message-ID in this article")
4125       (replace-match "Supersedes: " t t))
4126     (goto-char (point-max))
4127     (insert mail-header-separator)
4128     (widen)
4129     (forward-line 1)))
4130
4131 ;;;###autoload
4132 (defun message-recover ()
4133   "Reread contents of current buffer from its last auto-save file."
4134   (interactive)
4135   (let ((file-name (make-auto-save-file-name)))
4136     (cond ((save-window-excursion
4137              (if (not (eq system-type 'vax-vms))
4138                  (with-output-to-temp-buffer "*Directory*"
4139                    (with-current-buffer standard-output
4140                      (fundamental-mode)) ; for Emacs 20.4+
4141                    (buffer-disable-undo standard-output)
4142                    (let ((default-directory "/"))
4143                      (call-process
4144                       "ls" nil standard-output nil "-l" file-name))))
4145              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
4146            (let ((buffer-read-only nil))
4147              (erase-buffer)
4148              (insert-file-contents file-name nil)))
4149           (t (error "message-recover cancelled")))))
4150
4151 ;;; Washing Subject:
4152
4153 (defun message-wash-subject (subject)
4154   "Remove junk like \"Re:\", \"(fwd)\", etc. that was added to the subject by previous forwarders, replyers, etc."
4155   (with-temp-buffer
4156     (insert-string subject)
4157     (goto-char (point-min))
4158     ;; strip Re/Fwd stuff off the beginning
4159     (while (re-search-forward
4160             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
4161       (replace-match ""))
4162
4163     ;; and gnus-style forwards [foo@bar.com] subject
4164     (goto-char (point-min))
4165     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
4166       (replace-match ""))
4167
4168     ;; and off the end
4169     (goto-char (point-max))
4170     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
4171       (replace-match ""))
4172
4173     ;; and finally, any whitespace that was left-over
4174     (goto-char (point-min))
4175     (while (re-search-forward "^[ \t]+" nil t)
4176       (replace-match ""))
4177     (goto-char (point-max))
4178     (while (re-search-backward "[ \t]+$" nil t)
4179       (replace-match ""))
4180
4181     (buffer-string)))
4182
4183 ;;; Forwarding messages.
4184
4185 (defun message-forward-subject-author-subject (subject)
4186   "Generate a subject for a forwarded message.
4187 The form is: [Source] Subject, where if the original message was mail,
4188 Source is the sender, and if the original message was news, Source is
4189 the list of newsgroups is was posted to."
4190   (concat "["
4191           (or (message-fetch-field
4192                (if (message-news-p) "newsgroups" "from"))
4193               "(nowhere)")
4194           "] " subject))
4195
4196 (defun message-forward-subject-fwd (subject)
4197   "Generate a subject for a forwarded message.
4198 The form is: Fwd: Subject, where Subject is the original subject of
4199 the message."
4200   (concat "Fwd: " subject))
4201
4202 (defun message-make-forward-subject ()
4203   "Return a Subject header suitable for the message in the current buffer."
4204   (save-excursion
4205     (save-restriction
4206       (current-buffer)
4207       (message-narrow-to-head)
4208       (let ((funcs message-make-forward-subject-function)
4209             (subject (if message-wash-forwarded-subjects
4210                          (message-wash-subject
4211                           (or (message-fetch-field "Subject") ""))
4212                        (or (message-fetch-field "Subject") ""))))
4213         ;; Make sure funcs is a list.
4214         (and funcs
4215              (not (listp funcs))
4216              (setq funcs (list funcs)))
4217         ;; Apply funcs in order, passing subject generated by previous
4218         ;; func to the next one.
4219         (while funcs
4220           (when (message-functionp (car funcs))
4221             (setq subject (funcall (car funcs) subject)))
4222           (setq funcs (cdr funcs)))
4223         subject))))
4224
4225 ;;;###autoload
4226 (defun message-forward (&optional news digest)
4227   "Forward the current message via mail.
4228 Optional NEWS will use news to forward instead of mail.
4229 Optional DIGEST will use digest to forward."
4230   (interactive "P")
4231   (let* ((cur (current-buffer))
4232          (subject (if message-forward-show-mml
4233                       (message-make-forward-subject)
4234                     (mail-decode-encoded-word-string
4235                      (message-make-forward-subject))))
4236          art-beg)
4237     (if news
4238         (message-news nil subject)
4239       (message-mail nil subject))
4240     ;; Put point where we want it before inserting the forwarded
4241     ;; message.
4242     (if message-forward-before-signature
4243         (message-goto-body)
4244       (goto-char (point-max)))
4245     (if message-forward-as-mime
4246         (if digest
4247             (insert "\n<#multipart type=digest>\n")
4248           (if message-forward-show-mml
4249               (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
4250             (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")))
4251       (insert "\n-------------------- Start of forwarded message --------------------\n"))
4252     (let ((b (point)) e)
4253       (if digest
4254           (if message-forward-as-mime
4255               (insert-buffer-substring cur)
4256             (mml-insert-buffer cur))
4257         (if message-forward-show-mml
4258             (insert-buffer-substring cur)
4259           (mml-insert-buffer cur)))
4260       (setq e (point))
4261       (if message-forward-as-mime
4262           (if digest
4263               (insert "<#/multipart>\n")
4264             (if message-forward-show-mml
4265                 (insert "<#/mml>\n")
4266               (insert "<#/part>\n")))
4267         (insert "\n-------------------- End of forwarded message --------------------\n"))
4268       (if (and digest message-forward-as-mime)
4269           (save-restriction
4270             (narrow-to-region b e)
4271             (goto-char b)
4272             (narrow-to-region (point) 
4273                               (or (search-forward "\n\n" nil t) (point)))
4274             (delete-region (point-min) (point-max)))
4275         (when (and (not current-prefix-arg)
4276                    message-forward-ignored-headers)
4277           (save-restriction
4278             (narrow-to-region b e)
4279             (goto-char b)
4280             (narrow-to-region (point) 
4281                               (or (search-forward "\n\n" nil t) (point)))
4282             (message-remove-header message-forward-ignored-headers t)))))
4283     (message-position-point)))
4284
4285 ;;;###autoload
4286 (defun message-resend (address)
4287   "Resend the current article to ADDRESS."
4288   (interactive
4289    (list (message-read-from-minibuffer "Resend message to: ")))
4290   (message "Resending message to %s..." address)
4291   (save-excursion
4292     (let ((cur (current-buffer))
4293           beg)
4294       ;; We first set up a normal mail buffer.
4295       (set-buffer (get-buffer-create " *message resend*"))
4296       (erase-buffer)
4297       (message-setup `((To . ,address)))
4298       ;; Insert our usual headers.
4299       (message-generate-headers '(From Date To))
4300       (message-narrow-to-headers)
4301       ;; Rename them all to "Resent-*".
4302       (while (re-search-forward "^[A-Za-z]" nil t)
4303         (forward-char -1)
4304         (insert "Resent-"))
4305       (widen)
4306       (forward-line)
4307       (delete-region (point) (point-max))
4308       (setq beg (point))
4309       ;; Insert the message to be resent.
4310       (insert-buffer-substring cur)
4311       (goto-char (point-min))
4312       (search-forward "\n\n")
4313       (forward-char -1)
4314       (save-restriction
4315         (narrow-to-region beg (point))
4316         (message-remove-header message-ignored-resent-headers t)
4317         (goto-char (point-max)))
4318       (insert mail-header-separator)
4319       ;; Rename all old ("Also-")Resent headers.
4320       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
4321         (beginning-of-line)
4322         (insert "Also-"))
4323       ;; Quote any "From " lines at the beginning.
4324       (goto-char beg)
4325       (when (looking-at "From ")
4326         (replace-match "X-From-Line: "))
4327       ;; Send it.
4328       (let ((message-inhibit-body-encoding t)
4329             message-required-mail-headers)
4330         (message-send-mail))
4331       (kill-buffer (current-buffer)))
4332     (message "Resending message to %s...done" address)))
4333
4334 ;;;###autoload
4335 (defun message-bounce ()
4336   "Re-mail the current message.
4337 This only makes sense if the current message is a bounce message that
4338 contains some mail you have written which has been bounced back to
4339 you."
4340   (interactive)
4341   (let ((handles (mm-dissect-buffer t))
4342         boundary)
4343     (message-pop-to-buffer (message-buffer-name "bounce"))
4344     (if (stringp (car handles))
4345         ;; This is a MIME bounce.
4346         (mm-insert-part (car (last handles)))
4347       ;; This is a non-MIME bounce, so we try to remove things
4348       ;; manually.
4349       (mm-insert-part handles)
4350       (undo-boundary)
4351       (goto-char (point-min))
4352       (search-forward "\n\n" nil t)
4353       (or (and (re-search-forward message-unsent-separator nil t)
4354                (forward-line 1))
4355           (re-search-forward "^Return-Path:.*\n" nil t))
4356       ;; We remove everything before the bounced mail.
4357       (delete-region
4358        (point-min)
4359        (if (re-search-forward "^[^ \n\t]+:" nil t)
4360            (match-beginning 0)
4361          (point))))
4362     (mm-enable-multibyte)
4363     (mime-to-mml)
4364     (save-restriction
4365       (message-narrow-to-head)
4366       (message-remove-header message-ignored-bounced-headers t)
4367       (goto-char (point-max))
4368       (insert mail-header-separator))
4369     (message-position-point)))
4370
4371 ;;;
4372 ;;; Interactive entry points for new message buffers.
4373 ;;;
4374
4375 ;;;###autoload
4376 (defun message-mail-other-window (&optional to subject)
4377   "Like `message-mail' command, but display mail buffer in another window."
4378   (interactive)
4379   (let ((pop-up-windows t)
4380         (special-display-buffer-names nil)
4381         (special-display-regexps nil)
4382         (same-window-buffer-names nil)
4383         (same-window-regexps nil))
4384     (message-pop-to-buffer (message-buffer-name "mail" to)))
4385   (let ((message-this-is-mail t))
4386     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4387
4388 ;;;###autoload
4389 (defun message-mail-other-frame (&optional to subject)
4390   "Like `message-mail' command, but display mail buffer in another frame."
4391   (interactive)
4392   (let ((pop-up-frames t)
4393         (special-display-buffer-names nil)
4394         (special-display-regexps nil)
4395         (same-window-buffer-names nil)
4396         (same-window-regexps nil))
4397     (message-pop-to-buffer (message-buffer-name "mail" to)))
4398   (let ((message-this-is-mail t))
4399     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4400
4401 ;;;###autoload
4402 (defun message-news-other-window (&optional newsgroups subject)
4403   "Start editing a news article to be sent."
4404   (interactive)
4405   (let ((pop-up-windows t)
4406         (special-display-buffer-names nil)
4407         (special-display-regexps nil)
4408         (same-window-buffer-names nil)
4409         (same-window-regexps nil))
4410     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4411   (let ((message-this-is-news t))
4412     (message-setup `((Newsgroups . ,(or newsgroups ""))
4413                      (Subject . ,(or subject ""))))))
4414
4415 ;;;###autoload
4416 (defun message-news-other-frame (&optional newsgroups subject)
4417   "Start editing a news article to be sent."
4418   (interactive)
4419   (let ((pop-up-frames t)
4420         (special-display-buffer-names nil)
4421         (special-display-regexps nil)
4422         (same-window-buffer-names nil)
4423         (same-window-regexps nil))
4424     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4425   (let ((message-this-is-news t))
4426     (message-setup `((Newsgroups . ,(or newsgroups ""))
4427                      (Subject . ,(or subject ""))))))
4428
4429 ;;; underline.el
4430
4431 ;; This code should be moved to underline.el (from which it is stolen).
4432
4433 ;;;###autoload
4434 (defun bold-region (start end)
4435   "Bold all nonblank characters in the region.
4436 Works by overstriking characters.
4437 Called from program, takes two arguments START and END
4438 which specify the range to operate on."
4439   (interactive "r")
4440   (save-excursion
4441     (let ((end1 (make-marker)))
4442       (move-marker end1 (max start end))
4443       (goto-char (min start end))
4444       (while (< (point) end1)
4445         (or (looking-at "[_\^@- ]")
4446             (insert (char-after) "\b"))
4447         (forward-char 1)))))
4448
4449 ;;;###autoload
4450 (defun unbold-region (start end)
4451   "Remove all boldness (overstruck characters) in the region.
4452 Called from program, takes two arguments START and END
4453 which specify the range to operate on."
4454   (interactive "r")
4455   (save-excursion
4456     (let ((end1 (make-marker)))
4457       (move-marker end1 (max start end))
4458       (goto-char (min start end))
4459       (while (re-search-forward "\b" end1 t)
4460         (if (eq (char-after) (char-after (- (point) 2)))
4461             (delete-char -2))))))
4462
4463 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
4464
4465 ;; Support for toolbar
4466 (eval-when-compile 
4467   (defvar tool-bar-map)
4468   (defvar tool-bar-mode))
4469 (if (featurep 'xemacs)
4470     (require 'messagexmas)
4471   (when (and (>= (string-to-int emacs-version) 21)
4472              ;; I hate warnings --zsh.
4473              (fboundp 'tool-bar-add-item-from-menu)
4474              tool-bar-mode)
4475     (defvar message-tool-bar-map
4476       (let ((tool-bar-map (copy-keymap tool-bar-map)))
4477         ;; Zap some items which aren't so relevant and take up space.
4478         (dolist (key '(print-buffer kill-buffer save-buffer write-file
4479                                     dired open-file))
4480           (define-key tool-bar-map (vector key) nil))
4481         
4482         (tool-bar-add-item-from-menu
4483          'message-send-and-exit "mail_send" message-mode-map)
4484         (tool-bar-add-item-from-menu
4485          'message-kill-buffer "close" message-mode-map)
4486         (tool-bar-add-item-from-menu
4487          'message-dont-send "cancel" message-mode-map)
4488         (tool-bar-add-item-from-menu
4489          'mml-attach-file "attach" message-mode-map)
4490         (tool-bar-add-item-from-menu
4491          'ispell-message "spell" message-mode-map)
4492         tool-bar-map))))
4493
4494 ;;; Group name completion.
4495
4496 (defvar message-newgroups-header-regexp
4497   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
4498   "Regexp that match headers that lists groups.")
4499
4500 (defun message-tab ()
4501   "Expand group names in Newsgroups and Followup-To headers.
4502 Do a `tab-to-tab-stop' if not in those headers."
4503   (interactive)
4504   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
4505         (mail-abbrev-in-expansion-header-p))
4506       (message-expand-group)
4507     (tab-to-tab-stop)))
4508
4509 (defun message-expand-group ()
4510   "Expand the group name under point."
4511   (let* ((b (save-excursion
4512               (save-restriction
4513                 (narrow-to-region
4514                  (save-excursion
4515                    (beginning-of-line)
4516                    (skip-chars-forward "^:")
4517                    (1+ (point)))
4518                  (point))
4519                 (skip-chars-backward "^, \t\n") (point))))
4520          (completion-ignore-case t)
4521          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
4522                                             (point))))
4523          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
4524          (completions (all-completions string hashtb))
4525          comp)
4526     (delete-region b (point))
4527     (cond
4528      ((= (length completions) 1)
4529       (if (string= (car completions) string)
4530           (progn
4531             (insert string)
4532             (message "Only matching group"))
4533         (insert (car completions))))
4534      ((and (setq comp (try-completion string hashtb))
4535            (not (string= comp string)))
4536       (insert comp))
4537      (t
4538       (insert string)
4539       (if (not comp)
4540           (message "No matching groups")
4541         (save-selected-window
4542           (pop-to-buffer "*Completions*")
4543           (buffer-disable-undo)
4544           (let ((buffer-read-only nil))
4545             (erase-buffer)
4546             (let ((standard-output (current-buffer)))
4547               (display-completion-list (sort completions 'string<)))
4548             (goto-char (point-min))
4549             (delete-region (point) (progn (forward-line 3) (point))))))))))
4550
4551 ;;; Help stuff.
4552
4553 (defun message-talkative-question (ask question show &rest text)
4554   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
4555 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
4556 The following arguments may contain lists of values."
4557   (if (and show
4558            (setq text (message-flatten-list text)))
4559       (save-window-excursion
4560         (save-excursion
4561           (with-output-to-temp-buffer " *MESSAGE information message*"
4562             (set-buffer " *MESSAGE information message*")
4563             (fundamental-mode)          ; for Emacs 20.4+
4564             (mapcar 'princ text)
4565             (goto-char (point-min))))
4566         (funcall ask question))
4567     (funcall ask question)))
4568
4569 (defun message-flatten-list (list)
4570   "Return a new, flat list that contains all elements of LIST.
4571
4572 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
4573 => (1 2 3 4 5 6 7)"
4574   (cond ((consp list)
4575          (apply 'append (mapcar 'message-flatten-list list)))
4576         (list
4577          (list list))))
4578
4579 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
4580   "Create and return a buffer with a name based on NAME using generate-new-buffer.
4581 Then clone the local variables and values from the old buffer to the
4582 new one, cloning only the locals having a substring matching the
4583 regexp varstr."
4584   (let ((oldbuf (current-buffer)))
4585     (save-excursion
4586       (set-buffer (generate-new-buffer name))
4587       (message-clone-locals oldbuf varstr)
4588       (current-buffer))))
4589
4590 (defun message-clone-locals (buffer &optional varstr)
4591   "Clone the local variables from BUFFER to the current buffer."
4592   (let ((locals (save-excursion
4593                   (set-buffer buffer)
4594                   (buffer-local-variables)))
4595         (regexp "^gnus\\|^nn\\|^message\\|^user-mail-address"))
4596     (mapcar
4597      (lambda (local)
4598        (when (and (consp local)
4599                   (car local)
4600                   (string-match regexp (symbol-name (car local)))
4601                   (or (null varstr)
4602                       (string-match varstr (symbol-name (car local)))))
4603          (ignore-errors
4604            (set (make-local-variable (car local))
4605                 (cdr local)))))
4606      locals)))
4607
4608 ;;; Miscellaneous functions
4609
4610 (defsubst message-replace-chars-in-string (string from to)
4611   (mm-subst-char-in-string from to string))
4612
4613 ;;;
4614 ;;; MIME functions
4615 ;;;
4616
4617 (defvar message-inhibit-body-encoding nil)
4618
4619 (defun message-encode-message-body ()
4620   (unless message-inhibit-body-encoding 
4621     (let ((mail-parse-charset (or mail-parse-charset
4622                                   message-default-charset))
4623           (case-fold-search t)
4624           lines content-type-p)
4625       (message-goto-body)
4626       (save-restriction
4627         (narrow-to-region (point) (point-max))
4628         (let ((new (mml-generate-mime)))
4629           (when new
4630             (delete-region (point-min) (point-max))
4631             (insert new)
4632             (goto-char (point-min))
4633             (if (eq (aref new 0) ?\n)
4634                 (delete-char 1)
4635               (search-forward "\n\n")
4636               (setq lines (buffer-substring (point-min) (1- (point))))
4637               (delete-region (point-min) (point))))))
4638       (save-restriction
4639         (message-narrow-to-headers-or-head)
4640         (message-remove-header "Mime-Version")
4641         (goto-char (point-max))
4642         (insert "MIME-Version: 1.0\n")
4643         (when lines
4644           (insert lines))
4645         (setq content-type-p
4646               (re-search-backward "^Content-Type:" nil t)))
4647       (save-restriction
4648         (message-narrow-to-headers-or-head)
4649         (message-remove-first-header "Content-Type")
4650         (message-remove-first-header "Content-Transfer-Encoding"))
4651       ;; We always make sure that the message has a Content-Type header.
4652       ;; This is because some broken MTAs and MUAs get awfully confused
4653       ;; when confronted with a message with a MIME-Version header and
4654       ;; without a Content-Type header.  For instance, Solaris'
4655       ;; /usr/bin/mail.
4656       (unless content-type-p
4657         (goto-char (point-min))
4658         (re-search-forward "^MIME-Version:")
4659         (forward-line 1)
4660         (insert "Content-Type: text/plain; charset=us-ascii\n")))))
4661
4662 (defun message-read-from-minibuffer (prompt)
4663   "Read from the minibuffer while providing abbrev expansion."
4664   (if (fboundp 'mail-abbrevs-setup)
4665       (let ((mail-abbrev-mode-regexp "")
4666             (minibuffer-setup-hook 'mail-abbrevs-setup))
4667         (read-from-minibuffer prompt))
4668     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook))
4669       (read-string prompt))))
4670
4671 (defun message-use-alternative-email-as-from ()
4672   (require 'mail-utils)
4673   (let* ((fields '("To" "Cc")) 
4674          (emails
4675           (split-string
4676            (mail-strip-quoted-names
4677             (mapconcat 'message-fetch-reply-field fields ","))
4678            "[ \f\t\n\r\v,]+"))
4679          email)
4680     (while emails
4681       (if (string-match message-alternative-emails (car emails))
4682           (setq email (car emails)
4683                 emails nil))
4684       (pop emails))
4685     (unless (or (not email) (equal email user-mail-address))
4686       (goto-char (point-max))
4687       (insert "From: " email "\n"))))
4688
4689 (defun message-options-get (symbol)
4690   (cdr (assq symbol message-options)))
4691
4692 (defun message-options-set (symbol value)
4693   (let ((the-cons (assq symbol message-options)))
4694     (if the-cons
4695         (if value 
4696             (setcdr the-cons value)
4697           (setq message-options (delq the-cons message-options)))
4698       (and value
4699            (push (cons symbol value) message-options))))
4700   value)
4701
4702 (defun message-options-set-recipient ()
4703   (save-restriction
4704     (message-narrow-to-headers-or-head)
4705     (message-options-set 'message-sender
4706                          (mail-strip-quoted-names 
4707                           (message-fetch-field "from")))
4708     (message-options-set 'message-recipients
4709                           (mail-strip-quoted-names 
4710                            (message-fetch-field "to")))))
4711
4712 (provide 'message)
4713
4714 (run-hooks 'message-load-hook)
4715
4716 ;; Local Variables:
4717 ;; coding: iso-8859-1
4718 ;; End:
4719
4720 ;;; message.el ends here