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