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